2

I'd like to encrypt an NSString so that it isn't human-readable. The level of security doesnt manner (in other words, if somebody were to decrypt the text there wouldn't be any sensitive information for them to steal.

NSString *myTextToEncrypt = @"Hello World!";

[myTextToEncrypt encrypt];

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

Then I should be able to unencrypt this string

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

How do I do this? I've read some about CommonCrypto and AES Encryption but this all seems like overkill for what I'm trying to do (the encryption methods I've read are all for passwords or other sensitive pieces of data)

Bob Yousuk
  • 1,155
  • 3
  • 10
  • 16

2 Answers2

3

Simplest one is use your own encryption, e.g.

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

How to use it

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

Logs

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
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
2

You can use base64 to do this.

There are some implementations in Objective-C available (as this one).

Note that the content will be about 30% bigger after it's encoded.

Marcelo
  • 9,916
  • 3
  • 43
  • 52