openssl evp aes_128_cbc
package com.self;
import java.security.Key;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class OpensslDemo {
/**
* 加密openssl evp aes_128_cbc
* @param src
* @param key
* @param iv
* @return
*/
public static String encrypt(String src, String key, String iv) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Key skey = new SecretKeySpec(key.getBytes(), "AES");
//IvParameterSpec param = new IvParameterSpec(decodeBase64(iv));
IvParameterSpec param = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skey, param);
return encodeBase64(cipher.doFinal(src.getBytes()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 解密openssl evp aes_128_cbc
* @param src
* @param key
* @param iv
* @return
*/
public static String decrypt(byte[] src, String key, String iv) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Key skey = new SecretKeySpec(key.getBytes(), "AES");
//IvParameterSpec param = new IvParameterSpec(decodeBase64(iv));
IvParameterSpec param = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skey, param);
return new String(cipher.doFinal(src));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static byte[] decodeBase64(String value) throws Exception {
return new BASE64Decoder().decodeBuffer(value);
}
private static String encodeBase64(byte[] value) throws Exception {
return new BASE64Encoder().encodeBuffer(value);
}
}