【问题标题】:How to appropriately encrypt and decrypt a NSString with AES 128如何使用 AES 128 适当地加密和解密 NSString
【发布时间】:2016-02-04 00:34:49
【问题描述】:

我正在使用http://aes.online-domain-tools.com 加密我的 NSString,我从中得到的是一个无符号字符数组,例如 c2 84 6b 71 72 6d d2 e7 cd 0b a6 08 cd 85 c3 0c。

然后在我的代码中使用它来将其转换为 NSString:

const unsigned char encrpytedAppIDbytes[] = {0xe5, 0x35, 0xdf, 0x72, 0x57, 0xaf, 0xf7, 0xe6, 0x1f, 0x6d, 0x51, 0x1d, 0x26, 0xe8, 0x5e, 0xa2};
NSData *appIDToDecrypt = [NSData dataWithBytes:encrpytedAppIDbytes length:sizeof(encrpytedAppIDbytes)];
NSString *decryptedAppID = [[NSString alloc] initWithData:[appIDToDecrypt AES128DecryptedDataWithKey:@"something"] encoding:NSUTF8StringEncoding];

if([decryptedAppID isEqualToString:@"Something"]){} // This fails even when i look at them in the debugger they are the same.

但是当我尝试解密它时,它显示为相同的字符串,但是当我将它与相同的 NSString 硬代码进行比较以检查它是否是相同的字符串时,它不起作用。 这未通过我在我的应用中进行的一些身份验证检查。

请指出我在这里做错了什么。

谢谢,

【问题讨论】:

  • 显示比较代码。
  • 请看我上面的编辑
  • 里面好像有很多重复的代码。您使用即时创建的字符串记录,然后将authUssernameTextfield.text 设置为从数据创建的字符串。然后从 that 字符串创建一个 base-64 字符串。这是一团糟,答案在于对冗余代码的肆意过度重用。将其简化为最简单的术语,答案就会揭晓。
  • 当我尝试在解密后进行比较时,它似乎失败了,所以问题似乎出在我尝试解密它时。你觉得这有什么问题吗?
  • 如前所述,代码是一团糟。首先整理一下。

标签: ios objective-c encryption cryptography nsstringencoding


【解决方案1】:

好吧,花了几个小时后,我终于找到了可能不是最佳但适用于我的情况的解决方案。

似乎在解密之后,字符串包含一些在调试器中不可见的其他字符,但是当我尝试检查长度时,它显示的长度大于其中的字符数,这表明有问题。现在我所做的是:

const unsigned char nameBytes[] = {0xa6, 0xf0, 0xea, 0x36, 0x5f, 0x78, 0xb7, 0x52, 0x29, 0x6a, 0x67, 0xb7, 0xeb, 0x73, 0xd5, 0x14};

    NSData *nameBytesData = [NSData dataWithBytes:nameBytes length:sizeof(nameBytes)];
    NSString *nameBytesString = [[NSString alloc] initWithData:[nameBytesData AES128DecryptedDataWithKey:@"PaymentGateway"] encoding:NSUTF8StringEncoding];
     NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789"] invertedSet];

    NSString *safeSearchString = [[nameBytesString componentsSeparatedByCharactersInSet:set] componentsJoinedByString:@""];

    NSLog(@"length:%lu",(unsigned long)[safeSearchString length]);
    NSLog(@"lengthActual:%lu",(unsigned long)[@"ashutosh" length]);
    if ([safeSearchString isEqualToString:@"ashutosh"]) {
        NSLog(@"Success");
    }
    NSLog(@"Decrypted:%@",nameBytesString);

上面的代码删除了所有的特殊字符并将其替换为@"",因此结果字符串只有有效的字符。要添加支持以将更多字符视为有效,只需将它们添加到 NSCharacterSet * 集。

【讨论】:

    猜你喜欢
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2013-08-12
    • 2013-08-11
    • 2015-10-31
    • 2013-08-24
    相关资源
    最近更新 更多