网站首页 » PHP » JAVA AES SHA1PRNG 用PHP 实现

JAVA AES SHA1PRNG 用PHP 实现

May 20, 2022 PHP

JAVA代码

public static byte[] encrypt(String content, String password) throws Exception{
   KeyGenerator kgen = KeyGenerator.getInstance("AES");
   SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
   random.setSeed(password.getBytes());
   kgen.init(128, random);
   SecretKey secretKey = kgen.generateKey();
   byte[] enCodeFormat = secretKey.getEncoded();
   SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
   Cipher cipher = Cipher.getInstance("AES");// 创建密码器
   byte[] byteContent = content.getBytes("utf-8");
   cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
   byte[] result = cipher.doFinal(byteContent);
   return result; // 加密
}

PHP实现

$key = '12345678';
$key = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
$decrypted = openssl_encrypt($encrypt, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);

另附PHP二进制转16进制字符串方法
bin2hex($raw)