Code:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class test1280 {
public static final byte[] KEY =
{
(byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef,
(byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef,
(byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef,
};
public static final byte[] IV =
{
(byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef,
};
/**
* 十六进制打印字节数组
* @param b byte[]
*/
public static void printBytes(byte[] b)
{
for(int i=0;i<b.length;i++)
{
System.out.printf("%02x ", b[i]);
}
System.out.println();
}
public static void encrypt_des_ede_cbc_pkcs() throws Exception
{
byte[] in = "test1280".getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
SecretKey sk = skf.generateSecret(new DESedeKeySpec(KEY));
IvParameterSpec ips = new IvParameterSpec(IV);
cipher.init(Cipher.ENCRYPT_MODE, sk, ips);
byte[] out = cipher.doFinal(in);
printBytes(out);
}
public static void decrypt_des_ede_cbc_pkcs() throws Exception
{
byte[] out =
{
(byte) 0x64, (byte) 0x5a, (byte) 0x6b, (byte) 0xd6, (byte) 0xbf, (byte) 0xf8, (byte) 0x36, (byte) 0xb2,
(byte) 0x4f, (byte) 0xd1, (byte) 0x74, (byte) 0xf6, (byte) 0xe7, (byte) 0xf6, (byte) 0xaf, (byte) 0xdb,
};
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
SecretKey sk = skf.generateSecret(new DESedeKeySpec(KEY));
IvParameterSpec ips = new IvParameterSpec(IV);
cipher.init(Cipher.DECRYPT_MODE, sk, ips);
byte[] in = cipher.doFinal(out);
printBytes(in);
}
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub
encrypt_des_ede_cbc_pkcs();
decrypt_des_ede_cbc_pkcs();
}
}
执行:
64 5a 6b d6 bf f8 36 b2 4f d1 74 f6 e7 f6 af db
74 65 73 74 31 32 38 30
等价的,基于 openssl 实现 des ede3 cbc pkcs#5 算法,请参见:
https://blog.csdn.net/test1280/article/details/105254483