【问题标题】:Unable to decrypted Base64 encoded AES-256-CBC encrypted string in iOS, always results in nil string无法在 iOS 中解密 Base64 编码的 AES-256-CBC 加密字符串,总是导致 nil 字符串
【发布时间】:2017-04-27 03:41:08
【问题描述】:

我正在从服务器检索加密数据,加密是使用 PHP 中的以下代码完成的:

$password = '1234567890123456';

$iv_size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encryptedString = openssl_encrypt('I am a testing string', "AES-256-CBC", $password, 0, $iv);

$json['encrypted_feed'] = base64_encode($iv . $encryptedString);
$json['iv'] = base64_encode($iv);

echo json_encode($json);

然后在以下 JSON 对象中从服务器检索数据后:

{
    "encrypted_string":"IRcqgAMvXlEm17wUwrwwmE5NRmVrbUlpSEp4NUpta2JNdmMrdzhFOVVzRFR4bkVXUjluMVJwaXNYYTA9",
    "iv":"IRcqgAMvXlEm17wUwrwwmA=="
}

然后在我的 iOS 应用程序中,我尝试通过各种方式对其进行解密:

1.使用CommonCrypto tools here 中的实用程序:

** responseObject 是字典

NSString *password = @"1234567890123456";
NSData *pwData = [password dataUsingEncoding:NSUTF8StringEncoding];

NSString *base64FeedStr = [responseObject objectForKey:@"encrypted_feed"];
NSString *base64IVStr = [responseObject objectForKey:@"iv"];

NSData *base64FeedData = [[NSData alloc] initWithBase64EncodedString:b64FeedStr options:0];
NSData *base64IVData = [[NSData alloc] initWithBase64EncodedString:base64IVStr options:0];

NSData *decryptedFeedData = [b64FeedData decryptedDataUsingAlgorithm:kCCAlgorithmAES key:password initializationVector:b64IVData options:kCCOptionPKCS7Padding error:nil];

NSString *result = [[NSString alloc] initWithData:decryptedFeedData encoding:NSUTF8StringEncoding];

在此之后,我还尝试将开头附加的IV数据砍掉,然后按照上面的解密顺序进行,但结果保持不变。

2。与BBAES toos here

// According to the header:
// @param iv: the IV used to encrypt the data or nil if the encryption uses the `BBAESEncryptionOptionsIncludeIV` parameter
// i.e. the IV is saved along with the ciphertext (the IV is stored as the first block of the encrypted data).

// I also tried passing the IV into it but no luck.
NSData *resultData = [BBAES decryptedDataFromString:b64FeedStr IV:nil key:pwData];

NSString *result = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];

我也尝试在 php 中使用AES-128,但结果保持不变,即在生成的 NSString 中使用nil

我对密码学的了解很浅。经过所有这些调整并得到相同的结果,我感到很沮丧,不知道哪个部分出了问题。

如果对如何解密和检索原始字符串有任何见解,我将不胜感激。非常感谢!

【问题讨论】:

  • 最好不要使用mcrypt,它已经废弃了近十年了。因此,它已被弃用,并将在 PHP 7.2 中从核心中移除并进入 PECL。它不支持标准 PKCS#7 (née PKCS#5) 填充,仅支持甚至不能用于二进制数据的非标准空填充。 mcrypt 有许多出色的 bugs 可以追溯到 2003 年。请考虑使用 defuseRNCryptor,它们提供了完整的解决方案,正在维护并且是正确的。

标签: php ios objective-c encryption cryptography


【解决方案1】:
  1. MCRYPT_CAST_256 指定已弃用的 Cast 加密算法,而不是 AES。

  2. 不要使用 Cast,使用 AES

  3. AES 是MCRYPT_RIJNDAEL_128(mcrypt 没有说明清楚)。

  4. 在加密期间使用了 IV,并将其添加到加密数据中。 not 必须用于解密。 Base64解码,拆分IV和加密数据。

  5. 最好使用完整的跨平台库,如RNCryptor。很难从加密原语中获得正确和安全的加密。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    相关资源
    最近更新 更多