[RESOLVIDO by Pozzo] - Unicode e Triple DES

2 respostas
olitree

Viva Pessoal.

Tenho uma dúvida há uns tempos atrás coloquei aqui um código para encriptar uma determinada String, mas de momento estou com um problema relativamente ao desencriptar caracteres especiais, ou seja:

Palavra Original : António
Palavra depois de Desencriptada: Ant?nio

Como resolver este problema, visto que tenho já o unicode para os carateres de lingua portuguesa ISO-8859-1.

package asi.ana.util;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESedeEncryption {

	private String unicode_format = "ISO-8859-1";

	private String algorithm = "DESede";

	private String desede_encryption_scheme = "DESede/CBC/PKCS5Padding";

	private String vector_initialization = "00000000";

	private String encryption_key = "000000000000000000000000";

	private KeySpec myKeySpec;

	private SecretKeyFactory mySecretKeyFactory;

	private Cipher cipher;

	private byte[] keyAsBytes;

	private IvParameterSpec iv;

	private SecretKey key;

	public DESedeEncryption() throws Exception {

		this.init();
	}

	public DESedeEncryption(String unicode, String algorithm,
			String encryptionScheme, String vectorInit, String encryptionKey)
			throws Exception {

		this.setUnicode_format(unicode);
		this.setAlgorithm(algorithm);
		this.setDesede_encryption_scheme(encryptionScheme);
		this.setVector_initialization(vectorInit);
		this.setEncryption_key(encryptionKey);
		this.init();

	}

	private void init() throws Exception {

		this.setIv(new IvParameterSpec(this.getVector_initialization()
				.getBytes()));
		this.setKeyAsBytes(this.getEncryption_key().getBytes(
				this.getUnicode_format()));
		this.setMyKeySpec(new DESedeKeySpec(this.getKeyAsBytes()));
		this.setMySecretKeyFactory(SecretKeyFactory.getInstance(this
				.getAlgorithm()));
		this.setKey(this.getMySecretKeyFactory().generateSecret(
				this.getMyKeySpec()));
	}

	/**
	 * Method To Encrypt The String
	 */
	public String encrypt(String unencryptedString) {
		String encryptedString = null;
		try {

			this.setCipher(Cipher.getInstance(this
					.getDesede_encryption_scheme()));
			this.getCipher().init(Cipher.ENCRYPT_MODE, this.getKey(),
					this.getIv());
			byte[] plainText = unencryptedString.getBytes(this
					.getUnicode_format());
			byte[] encryptedText = this.getCipher().doFinal(plainText);
			BASE64Encoder base64encoder = new BASE64Encoder();
			encryptedString = base64encoder.encode(encryptedText);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return encryptedString;
	}

	/**
	 * Method To Decrypt An Ecrypted String
	 */
	public String decrypt(String encryptedString) {
		String decryptedText = null;
		try {
			this.getCipher().init(Cipher.DECRYPT_MODE, this.getKey(),
					this.getIv());
			BASE64Decoder base64decoder = new BASE64Decoder();
			byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
			byte[] plainText = this.getCipher().doFinal(encryptedText);
			decryptedText = bytes2String(plainText);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return decryptedText;
	}

	/**
	 * Returns String From An Array Of Bytes
	 */
	private static String bytes2String(byte[] bytes) {
		StringBuffer stringBuffer = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			stringBuffer.append((char) bytes[i]);
		}
		return stringBuffer.toString();
	}

	/**
	 * Read the specified TripleDES SecretKey to the specified file
	 */
	public void readKey(String url) throws IOException,
			NoSuchAlgorithmException, InvalidKeyException,
			InvalidKeySpecException {

		File f = new File(url);
		// Read the raw bytes from the keyfile
		DataInputStream in = new DataInputStream(new FileInputStream(f));
		byte[] rawkey = new byte[(int) f.length()];
		in.readFully(rawkey);
		in.close();
		// Convert the raw bytes to a secret key like this
		DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);
		SecretKeyFactory keyfactory = SecretKeyFactory
				.getInstance(getAlgorithm());
		this.setKey(keyfactory.generateSecret(keyspec));
	}

	/**
	 * Save the specified TripleDES SecretKey to the specified file
	 */
	public void writeKey(String url) throws IOException,
			NoSuchAlgorithmException, InvalidKeySpecException {

		File f = new File(url);
		// Convert the secret key to an array of bytes like this
		SecretKeyFactory keyfactory = SecretKeyFactory
				.getInstance(getAlgorithm());
		DESedeKeySpec keyspec = (DESedeKeySpec) keyfactory.getKeySpec(key,
				DESedeKeySpec.class);
		byte[] rawkey = keyspec.getKey();
		// Write the raw key to the file
		FileOutputStream out = new FileOutputStream(f);
		out.write(rawkey);
		out.close();
	}

	/**
	 * @return the algorithm
	 */
	public String getAlgorithm() {
		return algorithm;
	}

	/**
	 * @param algorithm
	 *            the algorithm to set
	 */
	public void setAlgorithm(String algorithm) {
		this.algorithm = algorithm;
	}

	/**
	 * @return the desede_encryption_scheme
	 */
	public String getDesede_encryption_scheme() {
		return desede_encryption_scheme;
	}

	/**
	 * @param desede_encryption_scheme
	 *            the desede_encryption_scheme to set
	 */
	public void setDesede_encryption_scheme(String desede_encryption_scheme) {
		this.desede_encryption_scheme = desede_encryption_scheme;
	}

	/**
	 * @return the encryption_key
	 */
	public String getEncryption_key() {
		return encryption_key;
	}

	/**
	 * @param encryption_key
	 *            the encryption_key to set
	 */
	public void setEncryption_key(String encryption_key) {
		this.encryption_key = encryption_key;
	}

	/**
	 * @return the unicode_format
	 */
	public String getUnicode_format() {
		return unicode_format;
	}

	/**
	 * @param unicode_format
	 *            the unicode_format to set
	 */
	public void setUnicode_format(String unicode_format) {
		this.unicode_format = unicode_format;
	}

	/**
	 * @return the vector_initialization
	 */
	public String getVector_initialization() {
		return vector_initialization;
	}

	/**
	 * @param vector_initialization
	 *            the vector_initialization to set
	 */
	public void setVector_initialization(String vector_initialization) {
		this.vector_initialization = vector_initialization;
	}

	/**
	 * @return the key
	 */
	public SecretKey getKey() {
		return key;
	}

	/**
	 * @param key
	 *            the key to set
	 */
	public void setKey(SecretKey key) {
		this.key = key;
	}

	/**
	 * @return the iv
	 */
	public IvParameterSpec getIv() {
		return iv;
	}

	/**
	 * @param iv
	 *            the iv to set
	 */
	public void setIv(IvParameterSpec iv) {
		this.iv = iv;
	}

	/**
	 * @return the keyAsBytes
	 */
	public byte[] getKeyAsBytes() {
		return keyAsBytes;
	}

	/**
	 * @param keyAsBytes
	 *            the keyAsBytes to set
	 */
	public void setKeyAsBytes(byte[] keyAsBytes) {
		this.keyAsBytes = keyAsBytes;
	}

	/**
	 * @return the myKeySpec
	 */
	public KeySpec getMyKeySpec() {
		return myKeySpec;
	}

	/**
	 * @param myKeySpec
	 *            the myKeySpec to set
	 */
	public void setMyKeySpec(KeySpec myKeySpec) {
		this.myKeySpec = myKeySpec;
	}

	/**
	 * @return the mySecretKeyFactory
	 */
	public SecretKeyFactory getMySecretKeyFactory() {
		return mySecretKeyFactory;
	}

	/**
	 * @param mySecretKeyFactory
	 *            the mySecretKeyFactory to set
	 */
	public void setMySecretKeyFactory(SecretKeyFactory mySecretKeyFactory) {
		this.mySecretKeyFactory = mySecretKeyFactory;
	}

	/**
	 * @return the cipher
	 */
	public Cipher getCipher() {
		return cipher;
	}

	/**
	 * @param cipher
	 *            the cipher to set
	 */
	public void setCipher(Cipher cipher) {
		this.cipher = cipher;
	}


	/**
	 * Testing The DESede Encryption And Decryption Technique
	 */
	public static void main(String args[]) throws Exception {

		String unicode = "ISO-8859-1";
		String algorithm = "DESede";
		String encryptionScheme = "DESede/CBC/PKCS5Padding";
		String vectorInit = "shkebaoq";
		String encryptionKey = "esfghjklidgtravbnfdeaslr";

		DESedeEncryption myEncryptor = new DESedeEncryption(unicode, algorithm,
				encryptionScheme, vectorInit, encryptionKey);

		String stringToEncrypt = "António";
		String encrypted = myEncryptor.encrypt(stringToEncrypt);
		String decrypted = myEncryptor.decrypt(encrypted);

		System.out.println("String To Encrypt: " + stringToEncrypt);
		System.out.println("Encrypted Value :" + encrypted);
		System.out.println("Decrypted Value :" + decrypted);

	}
}

2 Respostas

P

Altere:

decryptedText = bytes2String(plainText);

Para:

decryptedText = new String(plainText, "ISO-8859-1");
olitree

Muito Obrigado POZZO.
Já funciona.

Criado 30 de setembro de 2009
Ultima resposta 30 de set. de 2009
Respostas 2
Participantes 2