iosobjective-cencryptionnsstringrncryptor

How to decrypt nsstring using RNCryptor after conversion from NSData


Is there anyway to decrypt a NSString using RNcryptor that has been converted from NSData? I keep getting the unknown header error. Here is what I am doing to encrypt:

    NSData *data = [@"FeedMeMorePizzaPlease" dataUsingEncoding:NSUTF8StringEncoding];
    NSData *encryptedData = [RNEncryptor encryptData:data
                                  withSettings:kRNCryptorAES256Settings
                                        password:@"pizzaHutIsTheWorst"
                                           error:&error];
    NSString *encString = [encryptedData base64EncodedStringWithOptions:0];

I then take encString, put it in a text file on my server and then:

    NSURL  *gUrl = [NSURL URLWithString:@"https://myurlissupersecret.com/cheese.txt"];
    NSString *sillyString = [NSString stringWithContentsOfURL:gUrl encoding:(NSUTF8StringEncoding) error:nil];
    NSData *blindData  = [sillyString dataUsingEncoding:0];
    NSData *decryptedData = [RNDecryptor decryptData:blindData withSettings:kRNCryptorAES256Settings password:@"pizzaHutIsTheWorst" error:&error];

Is there anyway to do this? Or do I have to always encrypt / decrypt a file?


Solution

  • You missed a step in the decryption. sillyString is the base64 encoded string. You need to convert the base64 encoded string into NSData. Here is the updated code you need to decrypt:

    NSURL  *gUrl = [NSURL URLWithString:@"https://myurlissupersecret.com/cheese.txt"];
    NSString *encString = [NSString stringWithContentsOfURL:gUrl encoding:NSUTF8StringEncoding error:nil];
    NSData *encryptedData = [[NSData alloc] initWithBase64EncodedString:encString options:0];
    NSData *decryptedData = [RNDecryptor decryptData:encryptedData withSettings:kRNCryptorAES256Settings password:@"pizzaHutIsTheWorst" error:&error];