简体   繁体   中英

Coverting java code to php with AES and Cipher

I am finding it difficult to convert a piece of code to php from java. I searched on the internet about the meaning of each line of code written in my java code example but I didn't find any. I want to understand what each line does in this particular example.

This is what I tried.

function my_aes_encrypt($key, $data) {
 if(16 !== strlen($key)) $key = hash('MD5', $key, true);
 $padding = 16 - (strlen($data) % 16);
     $data .= str_repeat(chr($padding), $padding);
     return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_ECB, str_repeat("\0", 16)));
 }
function my_aes_decrypt($str, $key){ 
     $str = base64_decode($str);
     $str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB);
     $block = mcrypt_get_block_size('rijndael_128', 'ecb');
     $pad = ord($str[($len = strlen($str)) - 1]);
     $len = strlen($str);
     $pad = ord($str[$len-1]);
     return substr($str, 0, strlen($str) - $pad);
}

Convert from Java to PHP

//provided key 
byte[] keyBinary = DatatypeConverter.parseBase64Binary("r/RloSflFkLj3Pq2gFmdBQ==");  
SecretKey secret = new SecretKeySpec(keyBinary, "AES");    

// encrypted string   
byte[] bytes = DatatypeConverter.parseBase64Binary("IKWpOq9rhTAz/K1ZR0znPA=="); 

// iv 
byte[] iv = DatatypeConverter.parseBase64Binary("yzXzUhr3OAt1A47g7zmYxw==");       
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv)); 
String msisdn = new String(cipher.doFinal(bytes), "UTF-8"); 

It would be great if you guys let me know the details of each line written in Java.

The functionalities of the Java- and the PHP-code differ significantly. First of all, the Java-code contains only the decryption part, whereas the PHP-part contains both, the encryption- and decryption part. Contrary to the Java-code, in the PHP- my_aes_decrypt -method the insecure ECB-mode ( https://crypto.stackexchange.com/questions/20941/why-shouldnt-i-use-ecb-encryption ) seems to be used instead of the CBC-mode and thus, no IV is involved. Less important, but nonetheless different, the key doesn't seem to be base64-encoded because it's not decoded anywhere. In addition, in the PHP-code deprecated methods like mcrypt_encrypt ( http://php.net/manual/de/function.mcrypt-encrypt.php ) or cryptographic weak algorithms like MD5 ( https://en.wikipedia.org/wiki/MD5 ) are used.

If I get it right, the Java code is the reference code and you need the PHP-counterpart. Thus, I focus on the Java-code and ignore the differing and outdated PHP-code completely.

In the Java-code, the key, the data and the IV, all base64-encoded, become decoded and then, the encrypted data are decrypted using these decoded data.

A possible PHP-counterpart for the decryption could be:

<?php
$keyBinary = base64_decode('r/RloSflFkLj3Pq2gFmdBQ==');                                 // decode base64-encoded key in a string (internally, PHP strings are byte arrays)
$bytes = base64_decode('IKWpOq9rhTAz/K1ZR0znPA==');                                     // decode base64-encoded encrypted data in a string
$iv = base64_decode('yzXzUhr3OAt1A47g7zmYxw==');                                        // decode base64-encoded IV in a string   
$msisdn = openssl_decrypt($bytes, 'AES-128-CBC', $keyBinary, OPENSSL_RAW_DATA, $iv);    // decrypt data using AES-128, CBC-mode and PKCS7-Padding (default-padding)
                                                                                        // - when OPENSSL_RAW_DATA is specified raw data are returned, otherwise base64-encoded data (= default)
                                                                                        // - when OPENSSL_ZERO_PADDING is specified no padding is used, otherwise PKCS7-padding (= default)
                                                                                        // - The value XXX in AES-XXX-CBC is determined by the length of the key in Bit used in the Java-code,
                                                                                        //   e.g. for a 32 Byte (256 Bit)-key AES-256-CBC has to be used.  
print $msisdn."\n"; // Output: 1234567                                                  // print decrypted data

The desired explanation for the Java-code can be found in the comments:

//provided key 
byte[] keyBinary = DatatypeConverter.parseBase64Binary("r/RloSflFkLj3Pq2gFmdBQ==");     // decode base64-encoded key in a byte-array
SecretKey secret = new SecretKeySpec(keyBinary, "AES");                                 // create AES-key from byte-array (currently 16 Byte = 128 Bit long) 

// encrypted string    
byte[] bytes = DatatypeConverter.parseBase64Binary("IKWpOq9rhTAz/K1ZR0znPA==");         // decode base64-encoded encrypted data in a byte-array

// iv
byte[] iv = DatatypeConverter.parseBase64Binary("yzXzUhr3OAt1A47g7zmYxw==");            // decode base64-encoded IV in a byte-array     
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");                             // create cipher-instance for using AES in CBC-mode with PKCS5-Padding (Java counterpart to PKCS7)
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));                      // initialize cipher-instance for decryption with specified AES-key and IV (the latter created from corresponding byte-array) 
String msisdn = new String(cipher.doFinal(bytes), "UTF-8");                             // decrypt data using AES-128 (128 determined by length of used key in Bit), CBC-mode and PKCS5-Padding, 
                                                                                        // and put them in a UTF-8 string
System.out.println(msisdn); // Output: 1234567                                          // print decrypted data

The PHP-encryption part could be:

<?php
$keyBinary = base64_decode('r/RloSflFkLj3Pq2gFmdBQ==');                                 
$msisdn = '1234567';                                                                    // plain text
$iv = openssl_random_pseudo_bytes(16);                                                  // generate random IV
//$iv = base64_decode('yzXzUhr3OAt1A47g7zmYxw==');                                      // use this line for tests with your base64-encoded test-IV yzXzUhr3OAt1A47g7zmYxw==   
$bytes = openssl_encrypt($msisdn, 'AES-128-CBC', $keyBinary, OPENSSL_RAW_DATA, $iv);    // encrypt data using AES-128, CBC-mode and PKCS7-Padding (default-padding) 
$ivBase64 = base64_encode($iv);                                                         // base64-encode IV
$bytesBase64 = base64_encode($bytes);                                                   // base64-encode encrypted data
print $ivBase64."\n".$bytesBase64."\n";                                                 // print base64-encoded IV and encrypted data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM