Encriptação 3DES em VB.NET como desencriptar em Java

Olá a todos.

O meu problema é o seguinte, estou a trabalhar no desenvolvimento de um interfaces entre dois sistemas e há necessidade que um parâmetro do XML, seja passado de modo encriptado. O problema surge que os dois sistemas usam linguagens de encriptação diferentes. Eu Java e o outro sistema VB.NET. E acontece o seguinte no exemplo:

em VB tem este parâmetros:

Texto Desencriptado: “MAXIMO”
Chave: “esfghjklidgtravbnfdeaslr”
Vector de Inicialização: “shkebaoq”
Texto Encriptado: “225|127|116|212|166|254|115|120”

Em java obtenho isto usando um exemplo retirado da net:

Texto Desencriptado: “MAXIMO”
Chave: “esfghjklidgtravbnfdeaslr”
Texto Encriptado: “0bGpe7tWsrE=”

Vector de inicialização: Onde entra no java?

Ou existe alguma alternativa?

Obrigado

package javaapplication5;

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESedeEncryption {

    private static final String UNICODE_FORMAT = "UTF8";
    public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
    private KeySpec myKeySpec;
    private SecretKeyFactory mySecretKeyFactory;
    private Cipher cipher;
    byte[] keyAsBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    SecretKey key;

    public DESedeEncryption() throws Exception {

        myEncryptionKey = "esfghjklidgtravbnfdeaslr";
        myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
        keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        myKeySpec = new DESedeKeySpec(keyAsBytes);
        mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = mySecretKeyFactory.generateSecret(myKeySpec);
    }

    /**
     * Method To Encrypt The String
     */
    public String encrypt(String unencryptedString) {
        String encryptedString = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            byte[] encryptedText = cipher.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 {
            cipher.init(Cipher.DECRYPT_MODE, key);
            BASE64Decoder base64decoder = new BASE64Decoder();
            byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
            byte[] plainText = cipher.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();
    }

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

        String stringToEncrypt = "MAXIMO";
        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);

    }
}

Criar o Initialization Vector:

byte IV[] = {....};
IvParameterSpec ivSpec = new IvParameterSpec(IV);

aí é só passar o ivSpec para o método init do cipher.

Quanto à diferença, você está pegando o texto criptografado e passando por um Base64, sendo que aquele que foi escrito em .net não está base64 encoded.

Obrigado Filipe. O problema do vector foi solucionado com a adição do código que colocou anteriormente mais um getInstance do Cipher com o tipo de encriptação.

Agora como posso ver o código cifrado no tipo,

Texto Encriptado: “225|127|116|212|166|254|115|120”

Visto que é este tipo de formato que tenho que desencriptar, já tentei apanhar o código ande do base64, mas não é nada semelhante.

package javaapplication5;

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 static final String UNICODE_FORMAT = "UTF8";
    public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
    private KeySpec myKeySpec;
    private SecretKeyFactory mySecretKeyFactory;
    private Cipher cipher;
    byte[] keyAsBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    private IvParameterSpec iv;
    SecretKey key;

    public DESedeEncryption() throws Exception {

        iv = new IvParameterSpec("shkebaoq".getBytes());
        myEncryptionKey = "esfghjklidgtravbnfdeaslr";
        myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
        keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        myKeySpec = new DESedeKeySpec(keyAsBytes);
        mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = mySecretKeyFactory.generateSecret(myKeySpec);
    }

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

            cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key,iv);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            byte[] encryptedText = cipher.doFinal(plainText);
            //System.out.println(encryptedText);
            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 {
            cipher.init(Cipher.DECRYPT_MODE, key, iv);
            BASE64Decoder base64decoder = new BASE64Decoder();
            byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
            byte[] plainText = cipher.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();
    }

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

        String stringToEncrypt = "MAXIMO";
        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);

    }
}

O que você precisa é trabalhar com Arrays de Bytes nos métodos de criptografar e descriptografar.

Você tem: Texto Encriptado: “225|127|116|212|166|254|115|120”

Presumo que seja um byte[] com valor { 225, 127, 116, 212, 166, 254, 115, 120 }

Você precisará passar esse byte array para o método que irá descriptografar. Se é que eu entendi direito o que vc tá querendo.

Obrigado filpe. Era isso mesmo a outra parte já colocou em base64. o meu código final ficou assim:

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 = "UTF8";

	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 = "UTF8";
//		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 = "MAXIMO";
//		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);
//
//		// byte[] b = { (byte) 225, (byte) 127, (byte) 116, (byte) 212,
//		// (byte) 166, (byte) 254, (byte) 115, (byte) 120 };
//		// System.out.println(b);
//	}
}