Search code examples
iosobjective-cnsstringnsdata

How to convert NSString back to NSData after converting NSData to NSString?


I am generating SHA-256 key of a file using the function given below:

- (NSData *)doSha256:(NSData *)dataIn {
    NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];

    CC_SHA256( dataIn.bytes, dataIn.length, macOut.mutableBytes);

    return macOut;
}

This function is generating SHA-256 key and returning NSData however, I need to store the key in the database in String format. In order to convert the NSData to NSString I am using the code given below:

//converting sha256 to nsstring
    NSString * str = [sha256 base64EncodedStringWithOptions:0];

Then

I am trying to convert the str back to NSData using this code:

//converting str back to nsdata
    NSData* dataFrmString = [str dataUsingEncoding:NSUTF8StringEncoding];

Problem

When I am trying to compare the dataFrmString and sha256 its saying the both NSData are not same

//matching if the dataFrmString is equal to the sha256 data

if([dataFrmString isEqualTo:sha256])
{
    NSLog(@"sucessully back to nsdata");
}

Here is the whole code

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application

    // source file : whose sha 256 will be generated
    NSString* sourceFile = @"/Users/Paxcel/Downloads/Movies/World4uFRee.cc_dsam7dds.mkv";

    //getting nsdata of the file
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:sourceFile];

    //getting sha 256 of the file
    NSData *sha256 = [self doSha256:data];

    //converting sha256 to nsstring
    NSString * str = [sha256 base64EncodedStringWithOptions:0];

    //converting str back to nsdat
    NSData* dataFrmString = [[NSData alloc] initWithBase64EncodedString:str
                                                                options:0];
    //matching if the dataFrmString is equal to the sha256 data
    if([dataFrmString isEqualTo:sha256])
    {
        NSLog(@"sucessully back to nsdata");
    }



    NSString* destinationFile = @"/Users/Paxcel/Desktop/appcast2.xml";
    [sha256 writeToFile:destinationFile atomically:YES];


}

- (NSData *)doSha256:(NSData *)dataIn {
    NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];

    CC_SHA256( dataIn.bytes, dataIn.length, macOut.mutableBytes);

    return macOut;
}

Solution

  • You need to decode the base-64 encoded string, with something like:

    NSData *data = [[NSData alloc] initWithBase64EncodedString:str
                                                       options:0];
    

    Where str is the string read from the database.