由于对接很多第三方系统经常遇到aes的加解密,这里做个简单的记录。
Java代码:
package com.pft.api.util;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
private static final String IV_STRING = "初始化向量";
public static String encryptAES(String content, String key) {
try {
byte[] byteContent = content.getBytes("UTF-8");
// 注意,为了能与 iOS 统一
// 这里的 key 不可以使用 KeyGenerator、SecureRandom、SecretKey 生成
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
// 指定加密的算法、工作模式和填充方式
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encryptedBytes = cipher.doFinal(byteContent);
// 同样对加密后数据进行 base64 编码
Base64.Encoder encoder = Base64.getEncoder();
return encoder.encodeToString(encryptedBytes);
} catch (Exception e) {
}
return null;
}
public static String decryptAES(String content, String key) {
try {
// base64 解码
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedBytes = decoder.decode(content);
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] result = cipher.doFinal(encryptedBytes);
return new String(result, "UTF-8");
} catch (Exception e) {
}
return null;
}
public static void main(String[] args) {
String content = "{\"code\":\"1544496569178\",\"name\":\"test\",\"number\":\"123444\"}";
String key = "asdfghjklzxcvbnm";
String s = encryptAES(content, key);
System.out.println(s);
}
}
复制代码
PHP代码:
class Aes {
private $secretKey = '密钥';
private $iv = '初始化向量';
public function decode($secretData){
return openssl_decrypt(base64_decode($secretData),'AES-128-CBC',$this->secretKey,OPENSSL_RAW_DATA,$this->iv);
}
public function encode($data){
$data = base64_encode(openssl_encrypt($data, 'AES-128-CBC', $this->secretKey, OPENSSL_RAW_DATA, $this->iv));
return $data;
}
}
复制代码
刚开始PHP端一直失败的原因是$iv
对方没有提供,自己也忽略了这个参数; 另外就是要注意填充方式:OPENSSL_RAW_DATA
、OPENSSL_ZERO_PADDING
。