【问题标题】:Function mcrypt_decrypt() only working for short strings函数 mcrypt_decrypt() 仅适用于短字符串
【发布时间】:2013-03-19 15:57:34
【问题描述】:

我目前在 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 多个字符长的字符串。

【问题讨论】:

    标签: php ios objective-c encryption


    【解决方案1】:

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

    【讨论】:

    • 在 iOS 中,CCCrypt 函数只接受 2 个选项:kCCOptionECBMode 和 kCCOptionPKCS7Padding。删除 ECB 选项显然会在 CBC 中对其进行加密。我想使用 CBC,因为我读到它可以容纳更长的字符串。
    • @GabCas CBC 模式应该用于字符串,因为 ECB 模式不能安全地用于字符串。两者都可以保存无限量的数据(可能受到底层分组密码的安全考虑的限制)。 CBC 的安全使用要求一个随机 IV,它可以与密文一起明文发送。
    猜你喜欢
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多