RNCryptor AES256加密和解密在PHP中

时间:2022-09-28 18:28:52

I am trying to use RNCryptor to do AES256 encryption at iOS side and AES256 decryption at remote site in PHP. But I am not able to get the correct decrypted data with php. Please help review if anything I am doing wrong.

我正在尝试使用RNCryptor在iOS端进行AES256加密,在PHP远程站点进行AES256解密。但是我无法用php获得正确的解密数据。如果我做错了,请帮忙检查一下。

Below is my code for iOS.

以下是我的iOS代码。

 NSString *key = @"1234567890123456789012";
 NSData *encryptedData = [RNEncryptor encryptData:data
                                    withSettings:kRNCryptorAES256Settings
                                        password:key
                                           error:&error];

Then I post the encryptedData to server which is in PHP. Below is my PHP code.

然后我将encryptedData发布到PHP中的服务器。下面是我的PHP代码。

$key ="1234567890123456789012"  //32-bit key
$username = aes256Decrypt ($key, $username);

function aes256Decrypt($key, $data) {
    if(32 !== strlen($key)) $key = hash('SHA256', $key, true);
    $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, 
                str_repeat("\0", 16));
    $padding = ord($data[strlen($data) - 1]);
    $result = substr($data, 0, -$padding);
    return substr($data, 0, -$padding);
}

1 个解决方案

#1


1  

Based on some quick research, it appears that RNCryptor has its own output format. An example is shown below (taken from the page I linked):

基于一些快速研究,似乎RNCryptor有自己的输出格式。下面显示了一个示例(取自我链接的页面):

DESCRIPTION: | version/cryptor | options | encryptionSalt | HMACSalt |  IV   | ... ciphertext ... |   HMAC   |
 BYTE INDEX: |        0        |    1    |      2-9       |  10-17   | 18-33 | <-      ...     -> | n-32 - n |

Your PHP code is going to have to extract the data from this format before attempting to decrypt. You will need the IV value and the ciphertext in order to retrieve the original plaintext.

在尝试解密之前,您的PHP代码必须从此格式中提取数据。您将需要IV值和密文以检索原始明文。

Alternatively, switch to a different method of encryption for iOS that doesn't invent its own data format.

或者,切换到iOS的不同加密方法,而不是发明自己的数据格式。

#1


1  

Based on some quick research, it appears that RNCryptor has its own output format. An example is shown below (taken from the page I linked):

基于一些快速研究,似乎RNCryptor有自己的输出格式。下面显示了一个示例(取自我链接的页面):

DESCRIPTION: | version/cryptor | options | encryptionSalt | HMACSalt |  IV   | ... ciphertext ... |   HMAC   |
 BYTE INDEX: |        0        |    1    |      2-9       |  10-17   | 18-33 | <-      ...     -> | n-32 - n |

Your PHP code is going to have to extract the data from this format before attempting to decrypt. You will need the IV value and the ciphertext in order to retrieve the original plaintext.

在尝试解密之前,您的PHP代码必须从此格式中提取数据。您将需要IV值和密文以检索原始明文。

Alternatively, switch to a different method of encryption for iOS that doesn't invent its own data format.

或者,切换到iOS的不同加密方法,而不是发明自己的数据格式。