我觉得我已经尝试了所有使用 AES 将 Java 转换为 PHP 的方法;但是,我发现在对它们进行哈希处理后,密钥并不相同。我将盐保留为字符串,因为我无法让它与空字节数组一起使用;但是,它并没有改变任何东西。我在某处听说在 PHP 中需要将密钥长度除以 8,所以这就是我拥有它的原因。
我知道用于检查匹配工作的哈希函数,因为我已经用随机字符串对其进行了测试,并且它们匹配。
爪哇:
public static void main(String[] args) {
SecretKey secret = generateSecret("PASSWORD");
System.out.println(hashString(new String(secret.getEncoded()));
}
public static SecretKey generateSecret(String password) throws Exception {
//byte[] salt = new byte[8];
byte[] salt = "SALT".getBytes("UTF-8");
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKey secretKey = factory.generateSecret(keySpec);
return new SecretKeySpec(secretKey.getEncoded(), "AES");
}
public static String hashString(String request) throws Exception {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
byte[] buffer = messageDigest.digest(request.getBytes());
StringBuffer sb = new StringBuffer(buffer.length * 2);
for (int i = 0; i < buffer.length; i++) {
int v = buffer[i] & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}
PHP:
$password = 'PASSWORD';
salt = 'SALT';//pack('nvc*', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
$bytes = derivateKey($password, $salt, 65536, 256);
echo hash('sha512', $bytes);
function derivateKey($password, $salt, $iterations, $keyLengthBits){
return hash_pbkdf2('sha512', $password, $salt, $iterations, $keyLengthBits/8, true);
}
Java 使用此哈希返回:
9E6B73EA6FA176F8D0651AC4DA73F0CEBE603DA6B31A226443CABBB80EDF51BCE663F92945F5DC1C0B8F0098DDE61C3117CCEDFEB7DB4A959315DE635BC7F1BB
php 返回此哈希:
135d49502ca99da44f3050f37e7ca0e8ca16c18a9b3120c95bb8cf45e97c0120053c51a3f134fbf38c4105186362086e9504a130dc3ad5633c9968f2b12c1ac6