1.php5.* 和php7.* 的 aes-128-cbc实现都是不一样的。 2.php7.* 代码 openssl_encrypt($str, 'aes-128-cbc', $secrete_key,OPENSSL_NO_PADDING, $iv); 对应实现模式:AES/CBC/NOPADDING 3.使用Java实现
private static String encrypt(String data, String key) {
String ivStr="";
for (int i = 0; i < 16; i++) {
ivStr+="\0";
}
String secretKey = new String(Base64.decode(key)).trim();
data = addPKCS7Padding(data);
byte[] sub = ArrayUtil.sub(secretKey.getBytes(), 0, 16);
try {
SecretKeySpec desKeySpec = new SecretKeySpec(sub,"AES");
Cipher cipher = Cipher.getInstance("AES/CBC/noPadding");
IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes("utf-8"));
cipher.init(Cipher.ENCRYPT_MODE, desKeySpec, iv);
byte[] bytes = cipher.doFinal(data.getBytes());
return new String(Base64.encode(bytes));
} catch (Exception e) {
e.printStackTrace();
log.error("error", e);
}
return null;
4.aes其他填充 若使用AES/CBC/PKCS7Padding,可在jdk8直接运行,但是输出结果不一致,需使用其他provider
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
5.此provider pom
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
6.代码如下
private static String encrypt(String data, String key) {
String ivStr="";
for (int i = 0; i < 16; i++) {
ivStr+="0";
}
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
String secretKey = new String(Base64.decode(key)).trim();
data = addPKCS7Padding(data);
byte[] sub = ArrayUtil.sub(secretKey.getBytes(), 0, 16);
try {
SecretKeySpec desKeySpec = new SecretKeySpec(sub,"AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes("utf-8"));
cipher.init(Cipher.ENCRYPT_MODE, desKeySpec, iv);
byte[] bytes = cipher.doFinal(data.getBytes());
return new String(Base64.encode(bytes));
} catch (Exception e) {
e.printStackTrace();
log.error("error", e);
}
return null;
- note
ivstr为偏移向量,请自己实现, addPKCS7Padding方法为padding字符串方法,请自行实现, key为密钥,我使用的是base64字符串
|