Created
January 20, 2019 04:15
-
-
Save simlu/2f9ebc4cf24e6ceb90fb578a291b3a9c to your computer and use it in GitHub Desktop.
JAVA vs PHP aes gcm adae
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.crypto.Cipher; | |
import javax.crypto.SecretKey; | |
import javax.crypto.SecretKeyFactory; | |
import javax.crypto.spec.GCMParameterSpec; | |
import javax.crypto.spec.PBEKeySpec; | |
import javax.crypto.spec.SecretKeySpec; | |
public class T { | |
private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); | |
private static String bytesToHex(byte[] bytes) { | |
char[] hexChars = new char[bytes.length * 2]; | |
for ( int j = 0; j < bytes.length; j++ ) { | |
int v = bytes[j] & 0xFF; | |
hexChars[j * 2] = hexArray[v >>> 4]; | |
hexChars[j * 2 + 1] = hexArray[v & 0x0F]; | |
} | |
return new String(hexChars); | |
} | |
public static void main(String[] args) throws Exception { | |
byte[] iv = new byte[]{45,45,23,65,23,76,12,121, 45,45,23,65,23,76,12,121}; | |
String password = "password"; | |
String text = "text"; | |
System.out.println("IV: " + bytesToHex(iv)); | |
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), iv, 200_000, 128); | |
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); | |
SecretKey pbeKey = factory.generateSecret(pbeKeySpec); | |
byte[] keyBytes = pbeKey.getEncoded(); | |
System.out.println("KEY: " + bytesToHex(keyBytes)); | |
SecretKey key = new SecretKeySpec(keyBytes, "AES"); | |
GCMParameterSpec gcmSpec = new GCMParameterSpec(128, iv); | |
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); | |
cipher.init(Cipher.ENCRYPT_MODE, key, gcmSpec); | |
byte[] ciphertext = cipher.doFinal(text.getBytes()); | |
byte[] result = new byte[iv.length + ciphertext.length]; | |
System.arraycopy(iv, 0, result, 0, iv.length); | |
System.arraycopy(ciphertext, 0, result, iv.length, ciphertext.length); | |
System.out.println(bytesToHex(result)); | |
} | |
} | |
------------------------------------------------------- | |
<?php | |
$iv = implode(array_map("chr", array(45,45,23,65,23,76,12,121,45,45,23,65,23,76,12,121))); | |
$pw = "password"; | |
$text = "text"; | |
echo 'IV: ' . bin2hex($iv) . "\n"; | |
// ---------------- | |
$key = hash_pbkdf2('sha256', $pw, $iv, 200000, 16, true); | |
echo 'KEY: ' . bin2hex($key) . "\n"; | |
$encrypted = openssl_encrypt( | |
$text, | |
"aes-128-gcm", | |
$key, | |
$options=OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, | |
$iv, | |
$tag, | |
"", | |
16 | |
); | |
$result = $iv . $encrypted . $tag; | |
echo strtoupper(bin2hex($result)). "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment