我想加密一个 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 的文章,但这对于我正在尝试做的事情来说似乎有点矫枉过正(我读过的加密方法都是针对密码或其他敏感数据)
Best Answer-推荐答案 strong>
最简单的一种是使用您自己的加密,例如
Utils.h
@interface Utils : NSObject
+(NSString*)encyptStringNSString*)str;
+(NSString*)decryptStringNSString*)str;
@end
Utils.m
#import "Utils.h"
int offset = 15;
@implementation Utils
+(NSString*)encyptStringNSString*)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*)decryptStringNSString*)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
关于ios - 加密一个 NSString,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/18168874/
|