如何在将NSData转换为NSString后将NSString转换回NSData?

时间:2015-10-14 07:01:43

标签: ios objective-c nsstring nsdata

我使用下面给出的函数生成文件的SHA-256密钥:

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

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

    return macOut;
}

此函数生成SHA-256密钥并返回NSData但是,我需要以String格式将密钥存储在数据库中。为了将NSData转换为NSString,我使用下面给出的代码:

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

,然后

我正在尝试使用以下代码将 str 转换回NSData:

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

问题

当我尝试比较 dataFrmString sha256 时,它说两个NSData都不相同

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

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

以下是整个代码

- (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;
}

1 个答案:

答案 0 :(得分:1)

您需要解码base-64编码的字符串,例如:

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

其中str是从数据库中读取的字符串。