【问题标题】:Encrypt an NSString加密一个 NSString
【发布时间】:2013-08-11 13:18:51
【问题描述】:

我想加密一个 NSString 使其不可读。安全级别不合适(换句话说,如果有人要解密文本,就不会有任何敏感信息可供他们窃取。

NSString *myTextToEncrypt = @"Hello World!";

[myTextToEncrypt encrypt];

// myTextToEncrypt is now something unreadable, like '2rwzdn1405'

那我应该可以解密这个字符串了

[myTextToEncrypt unencrypt]; // myTextToEncrypt should now be @"Hello World!" again

我该怎么做?我读过一些关于 CommonCrypto 和 AES Encryption 的文章,但这对于我正在尝试做的事情来说似乎有点过头了(我读过的加密方法都是用于密码或其他敏感数据)

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    最简单的一种是使用您自己的加密,例如

    Utils.h

    @interface Utils : NSObject
    +(NSString*)encyptString:(NSString*)str;
    +(NSString*)decryptString:(NSString*)str;
    @end
    

    Utils.m

    #import "Utils.h"
    
    int offset = 15;
    @implementation Utils
    +(NSString*)encyptString:(NSString*)str
    {
        NSMutableString *encrptedString = [[NSMutableString alloc] init];
        for (int i = 0; i < str.length; i++) {
            unichar character = [str characterAtIndex:i];
            character += offset;
            [encrptedString appendFormat:@"%C",character];
        }
        return encrptedString;
    }
    
    +(NSString*)decryptString:(NSString*)str
    {
        NSMutableString *decrptedString = [[NSMutableString alloc] init];
        for (int i = 0; i < str.length; i++) {
            unichar character = [str characterAtIndex:i];
            character -= offset;
            [decrptedString appendFormat:@"%C",character];
        }
        return decrptedString;
    }
    @end
    

    使用方法

    NSString *str = @"hello world";
    NSString *enr = [Utils encyptString:str];
    NSLog(@"Encrypted Text=%@", enr);
    NSLog(@"Decrypted Text=%@", [Utils decryptString:enr]);
    

    日志

    2013-08-11 10:44:09.409 DeviceTest[445:c07] Encrypted Text=wt{{~/~{s
    2013-08-11 10:44:09.412 DeviceTest[445:c07] Decrypted Text=hello world
    

    【讨论】:

    • 这不是加密,这是编码,更容易被渗透。
    • @Jasconius 渗透有多容易?我正在考虑使用编码来“加密”一些短信。
    • @InderKumarRathore 偏移量需要有限制吗?或者无论文本是什么,我都可以传递我想要的数字吗?
    【解决方案2】:

    您可以使用base64 来执行此操作。

    Objective-C 中有一些可用的实现(如this one)。

    请注意,内容在编码后会大 30% 左右。

    【讨论】:

      猜你喜欢
      • 2011-12-10
      • 2012-09-28
      • 1970-01-01
      • 2015-10-31
      • 1970-01-01
      • 2023-03-30
      • 2010-11-26
      • 2013-11-23
      相关资源
      最近更新 更多