Php 函数mcrypt_decrypt()仅适用于短字符串

Php 函数mcrypt_decrypt()仅适用于短字符串,php,ios,objective-c,encryption,Php,Ios,Objective C,Encryption,我现在用iOS加密,用PHP解密。如果我正在加密/解密的字符串长度小于16个字符,它就可以正常工作 要加密的iOS代码: - (NSData *)AES128Encrypt:(NSData *)this { // ‘key’ should be 16 bytes for AES128 char keyPtr[kCCKeySizeAES128 + 1]; // room for terminator (unused) bzero( keyPtr, sizeof( k

我现在用iOS加密,用PHP解密。如果我正在加密/解密的字符串长度小于16个字符,它就可以正常工作

要加密的iOS代码:

    - (NSData *)AES128Encrypt:(NSData *)this
{
    // ‘key’ should be 16 bytes for AES128
    char keyPtr[kCCKeySizeAES128 + 1]; // room for terminator (unused)
    bzero( keyPtr, sizeof( keyPtr ) ); // fill with zeroes (for padding)
    NSString *key = @"1234567890123456";
    // fetch key data
    [key getCString:keyPtr maxLength:sizeof( keyPtr ) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [this length];

    //See the doc: For block ciphers, the output size will always be less than or
    //equal to the input size plus the size of one block.
    //That’s why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc( bufferSize );

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt( kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode | kCCOptionPKCS7Padding,
                                          keyPtr, kCCKeySizeAES128,
                                          NULL /* initialization vector (optional) */,
                                          [this bytes], dataLength, /* input */
                                          buffer, bufferSize, /* output */
                                          &numBytesEncrypted );
    if( cryptStatus == kCCSuccess )
    {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }

    free( buffer ); //free the buffer
    return nil;
}
要解密的PHP代码:

function decryptThis($key, $pass)
{

    $base64encoded_ciphertext = $pass;

    $res_non = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $base64encoded_ciphertext, MCRYPT_MODE_CBC);

    $decrypted = $res_non;
    $dec_s2 = strlen($decrypted);

    $padding = ord($decrypted[$dec_s2-1]);
    $decrypted = substr($decrypted, 0, -$padding);

    return  $decrypted;
}

如果解密的字符串长度超过16个字符,PHP只返回@“\n\n”。但是,像'what'这样的短字符串被正确解密,PHP返回@“what\n\n”。这是怎么回事?我希望能够解密长度超过500个字符的字符串。

您在iOS中使用ECB模式,在PHP上使用CBC模式。此外,PHP不会检测到不正确的填充,因此,如果(不正确的)填充明文的最后一个字节的值较高,它可能会生成一个空字符串。

在iOS中,CCCrypt函数只接受两个选项:kCCOptionECBMode和kCCOptionPKCS7Padding。删除ECB选项显然会在CBC中对其进行加密。我想使用CBC,因为我知道它可以容纳更长的字符串。@GabCas CBC模式应该用于字符串,因为ECB模式用于字符串不安全。两者都可以保存无限量的数据(可能受到底层分组密码安全考虑的限制)。CBC的安全使用要求使用随机IV,可以用密文以明文形式发送。