Unexpected decryption of result using PHP AES CCM mode

I am trying to reproduce the encryption operation using AES-256-CCM, which is currently running in Java with the Bouncy Castle provider. When I try the same operation in PHP using openssl, I cannot find a set of parameters that produce the same result.

Since AEAD modes were recently added in PHP (7.1), documentation on how this works is not enough.

A minimal example of β€œworking” encryption in Java is as follows:

public static void main(String args[]) { try { java.security.Security.addProvider(new BouncyCastleProvider()); byte[] key = Base64.decodeBase64("Z4lAXU62WxDi46zSV67FeLj3hSK/th1Z73VD4/y6Eq4=".getBytes()); byte[] iv = Base64.decodeBase64("rcFcdcgZ3Q/A+uHW".getBytes()); SecretKey aesKey = new SecretKeySpec(key, 0, key.length, "AES"); Cipher aesCipher = Cipher.getInstance("AES/CCM/NoPadding", "BC"); aesCipher.init(1, aesKey, new IvParameterSpec(iv)); byte[] encrypted = aesCipher.doFinal("test".getBytes()); System.out.println(Hex.encodeHex(encrypted)); // Output: 411d89ff74205c106d8d85a8 } catch (Throwable e) { e.printStackTrace(); } } 

Since I am trying to re-do this using different two different libraries and languages, I set the key and iv to the known values.

When trying to recreate this using PHP and openssl, I try to use the following code

 $key = base64_decode("Z4lAXU62WxDi46zSV67FeLj3hSK/th1Z73VD4/y6Eq4="); $iv = base64_decode('rcFcdcgZ3Q/A+uHW'); $data = 'test'; $tag = null; $encrypted = openssl_encrypt($data,'aes-256-ccm', $key,OPENSSL_RAW_DATA, $iv, $tag,"",8); echo(bin2hex($encrypted . $tag)); // d1a7403799b8c37240f36edb 

Clearly, the results do not match. Looking for an answer about what is wrong, I created the same operation using SJCL in javascript. An example for this:

 var data = "test"; var key = sjcl.codec.base64.toBits("Z4lAXU62WxDi46zSV67FeLj3hSK/th1Z73VD4/y6Eq4="); var iv = sjcl.codec.base64.toBits("rcFcdcgZ3Q/A+uHW"); var p = { adata: "", iter: 0, mode: "ccm", ts: 64, ks: 256, iv: iv, salt: "" }; var encrypted = sjcl.encrypt(key, data, p, {}); console.log(encrypted); // Output: {"iv":"rcFcdcgZ3Q/A+uHW","v":1,"iter":0,"ks":256,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"","ct":"QR2J/3QgXBBtjYWo"} // QR2J/3QgXBBtjYWo === 411d89ff74205c106d8d85a8 

The Bouncy Castle and SJCL libraries produce the same output, but I cannot say the other.

I tried to pre-process the key using PBKDF2, as suggested in Encrypt in Javascript using SJCL and decrypt in PHP without success. I tried SHA256 key without success.

Why is the output in php / openssl different from Bouncy Castle and SJCL?

+5
source share

Source: https://habr.com/ru/post/1274406/


All Articles