Encrypt in openssl decrypt in Java
843811Mar 26 2007 — edited May 25 2007I am fairly new to JCA and have a question regarding encrypting a file using openSSL and decrypting using java.
The openssl command used to generate the base64 encoded output is:
openssl enc -a -in tmp -out tmp1 -e -K 30313233343536373839414243444546 -iv 3031323334353637 -nosalt -des-ede3-cbc
As is apparent from the command, i need to use des-ede3 in cbc mode to encrypt the file. Encoding in base64 is not so much a requirement but did that so that i don't have to deal with reading binary file (as i wasn't sure how many bytes i am decrypting at a time).
On the java side, the code looks something like this.
package mystuff.util;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import sun.misc.BASE64Decoder;
public class DecryptOpenSSL
{
public String decryptData(String encryptedData)
throws BadPaddingException, IllegalBlockSizeException, Exception
{
// decrypting the data
byte[] actualValue = getCipher("DECRYPT").doFinal(new BASE64Decoder()
.decodeBuffer(encryptedData));
// return decrypted value
return new String(actualValue, "UTF-8");
}
private Cipher getCipher(String mode)
throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchPaddingException,InvalidAlgorithmParameterException
{
// encryption Key used in openSSL command
byte[] encryptKey = "30313233343536373839414243444546".getBytes();
// IV stuff, hex representation of the IV used in openSSL
IvParameterSpec IvParameters = new IvParameterSpec(new byte[]
{0X30,0X31,0X32,0X33,0X34,0X35,0X36,0X37});
// creating a DES key spec from the byte array key
DESedeKeySpec spec = new DESedeKeySpec(encryptKey);
// initializing secret key factory for generating DES keys
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
// creating a DES SecretKey object
SecretKey theKey = keyFactory.generateSecret(spec);
// obtaining a DES Cipher object
Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
// Initializing the cipher and put it into decrypt mode
cipher.init(Cipher.DECRYPT_MODE, theKey, IvParameters);
return cipher;
}
public static void main(String args[])
{
try
{
DecryptOpenSSL ds = new DecryptOpenSSL();
System.out.println(ds.decryptData("V9DxfBvvZTijadFZqi87to9jPHN+Ecru"));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}