PHP vs Java Encryption key generation
Get the solution ↓↓↓I feel like I have tried everything to get java to PHP using AES; however, I have found that the keys are not the same after I hashed them. I have kept the salt as a string because I couldn't get it to work with an empty byte array; however, it hasn't changed anything. I heard somewhere that dividing the key length by 8 is needed in PHP, so that's why I have it.
I know the hash functions to check for matching works as I have tested it with a random string, and they match up.
JAVA:
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 returns with this hash:
9E6B73EA6FA176F8D0651AC4DA73F0CEBE603DA6B31A226443CABBB80EDF51BCE663F92945F5DC1C0B8F0098DDE61C3117CCEDFEB7DB4A959315DE635BC7F1BB
php returns with this hash:
135d49502ca99da44f3050f37e7ca0e8ca16c18a9b3120c95bb8cf45e97c0120053c51a3f134fbf38c4105186362086e9504a130dc3ad5633c9968f2b12c1ac6
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to a member function getclientoriginalname() on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.