2

I am using this Objective-C category to encrypt and decrypt my string data: https://gist.github.com/leeprobert/b83f07ca90ad657a1cd17f94b13138b1

and I have an NSString category like so:

@implementation NSString (AESCrypt)

- (NSString *)AES128EncryptWithKey:(NSString *)key
{
    NSData *plainData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSData *encryptedData = [plainData AES128EncryptedDataWithKey:key];

    NSString *encryptedString = [encryptedData base64Encoding];

    return encryptedString;
}

- (NSString *)AES128DecryptWithKey:(NSString *)key
{
    NSData *plainData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSData *decryptedData = [plainData AES128DecryptedDataWithKey:key];

    NSString *decryptedString = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];

    return decryptedString;
}

@end

My problem is that when I test this I get garbage out:

NSString* stringToEncrypt = @"Mary had a little lamb";
        NSString* encryptedString = [stringToEncrypt AES128EncryptWithKey:eKey];
        NSString* decryptedString = [encryptedString AES128DecryptWithKey:eKey];

        NSLog(@"encryptedString = %@, decryptedString = %@", encryptedString, decryptedString);

this will log as:

encryptedString = wLnJKED9oE4zC8dS9X7XskTs8kMTP59LUj8aatxW9+c=, decryptedString = (null)

I'm not convinced I need to do the base64encoding in the encryption process. This part was someone else's code. I am trying to do the decryption now.

Lee Probert
  • 10,308
  • 8
  • 43
  • 70

1 Answers1

2

You haven't accounted for the Base64 encoding during your decryption. Rather than [self dataUsingEncoding:NSUTF8StringEncoding] you should use [[NSData alloc] initWithBase64EncodedString:self options:0].

Whether or not you want to use Base64 just depends on what you're doing. It's a convenient way of taking NSData (which is the encryption output / decryption input) and turning it into string with a small character set (A-Za-z0-9+/=).

jtbandes
  • 115,675
  • 35
  • 233
  • 266