关键点
- 秘钥长度如果是 16位, 对应 PHP 的 算法名为
AES-128-ECB, 128 = 16 * 8 - 秘钥长度如果是 32位, 则对应 PHP 的 算法名应为
AES-256-ECB, 256 = 32 * 8 - 在
AES-128-ECB 算法下, 使用长度超过16的秘钥,只会使用前16位
Java 代码
public static String encrypt(String str) {
try {
String key = "1245678124567812456781245678";
System.out.println("key => " + key);
byte[] kb = key.getBytes("utf-8");
SecretKeySpec sks = new SecretKeySpec(kb, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, sks);
byte[] eb = cipher.doFinal(str.getBytes("utf-8"));
return new Base64().encodeToString(eb);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
PHP代码
public function encrypt($content)
{
$key = $this->getSecretKey();
$data = openssl_encrypt($content, 'AES-256-ECB', $key);
return $data;
}