· 7 years ago · Jan 20, 2019, 08:28 PM
1import javax.crypto.Cipher;
2import javax.crypto.SecretKey;
3import javax.crypto.SecretKeyFactory;
4import javax.crypto.spec.GCMParameterSpec;
5import javax.crypto.spec.PBEKeySpec;
6import javax.crypto.spec.SecretKeySpec;
7
8public class T {
9 private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
10 private static String bytesToHex(byte[] bytes) {
11 char[] hexChars = new char[bytes.length * 2];
12 for ( int j = 0; j < bytes.length; j++ ) {
13 int v = bytes[j] & 0xFF;
14 hexChars[j * 2] = hexArray[v >>> 4];
15 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
16 }
17 return new String(hexChars);
18 }
19
20 public static void main(String[] args) throws Exception {
21 byte[] iv = new byte[]{45,45,23,65,23,76,12,121, 45,45,23,65,23,76,12,121};
22 String password = "password";
23 String text = "text";
24 System.out.println("IV: " + bytesToHex(iv));
25
26 PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), iv, 200_000, 128);
27 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
28 SecretKey pbeKey = factory.generateSecret(pbeKeySpec);
29 byte[] keyBytes = pbeKey.getEncoded();
30 System.out.println("KEY: " + bytesToHex(keyBytes));
31
32 SecretKey key = new SecretKeySpec(keyBytes, "AES");
33
34 GCMParameterSpec gcmSpec = new GCMParameterSpec(128, iv);
35
36 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
37 cipher.init(Cipher.ENCRYPT_MODE, key, gcmSpec);
38 byte[] ciphertext = cipher.doFinal(text.getBytes());
39
40 byte[] result = new byte[iv.length + ciphertext.length];
41 System.arraycopy(iv, 0, result, 0, iv.length);
42 System.arraycopy(ciphertext, 0, result, iv.length, ciphertext.length);
43
44 System.out.println(bytesToHex(result));
45 }
46}
47
48
49
50
51-------------------------------------------------------
52
53
54<?php
55
56$iv = implode(array_map("chr", array(45,45,23,65,23,76,12,121,45,45,23,65,23,76,12,121)));
57$pw = "password";
58$text = "text";
59echo 'IV: ' . bin2hex($iv) . "\n";
60
61
62// ----------------
63
64$key = hash_pbkdf2('sha256', $pw, $iv, 200000, 16, true);
65echo 'KEY: ' . bin2hex($key) . "\n";
66$encrypted = openssl_encrypt(
67 $text,
68 "aes-128-gcm",
69 $key,
70 $options=OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING,
71 $iv,
72 $tag,
73 "",
74 16
75);
76$result = $iv . $encrypted . $tag;
77
78echo strtoupper(bin2hex($result)). "\n";