简体   繁体   English

使用AES和密码将Java代码覆盖到PHP

[英]Coverting java code to php with AES and Cipher

I am finding it difficult to convert a piece of code to php from java. 我发现很难将一段代码从Java转换为php。 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. 我在互联网上搜索了我的Java代码示例中编写的每一行代码的含义,但没有找到任何含义。 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 从Java转换为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. 如果你们让我知道用Java编写的每一行的细节,那将是很棒的。

The functionalities of the Java- and the PHP-code differ significantly. Java和PHP代码的功能差异很大。 First of all, the Java-code contains only the decryption part, whereas the PHP-part contains both, the encryption- and decryption part. 首先,Java代码仅包含解密部分,而PHP部分包含加密和解密部分。 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. 与Java代码相反,在PHP- my_aes_decrypt方法中,似乎使用了不安全的ECB模式( https://crypto.stackexchange.com/questions/20941/why-shouldnt-i-use-ecb-encryption )而不是CBC模式,因此不涉及IV。 Less important, but nonetheless different, the key doesn't seem to be base64-encoded because it's not decoded anywhere. 重要性不那么重要,但又有所不同,该密钥似乎没有经过base64编码,因为它没有在任何地方解码。 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. 此外,在PHP代码中,已弃用的方法(例如mcrypt_encrypthttp://php.net/manual/de/function.mcrypt-encrypt.php ))或加密弱算法(例如MD5)( https://en.wikipedia.org/使用wiki / MD5 )。

If I get it right, the Java code is the reference code and you need the PHP-counterpart. 如果我理解正确,则Java代码是参考代码,并且您需要PHP对应部分。 Thus, I focus on the Java-code and ignore the differing and outdated PHP-code completely. 因此,我专注于Java代码,而完全忽略了不同而过时的PHP代码。

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. 在Java代码中,对所有base64编码的密钥,数据和IV进行了解码,然后使用这些解码后的数据对加密后的数据进行解密。

A possible PHP-counterpart for the decryption could be: 用于解密的可能的PHP对应对象可能是:

<?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: 可以在注释中找到所需的Java代码说明:

//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加密部分可以是:

<?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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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