尝试编写NSString sha1函数,但它返回null [英] Trying to Write NSString sha1 function, but it's returning null

查看:110
本文介绍了尝试编写NSString sha1函数,但它返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Objective-C函数:

I have the following Objective-C function:

+(NSString *)stringToSha1:(NSString *)str{
    NSMutableData *dataToHash = [[NSMutableData alloc] init];
    [dataToHash appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];

    unsigned char hashBytes[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1([dataToHash bytes], [dataToHash length], hashBytes);
    NSData *encodedData = [NSData dataWithBytes:hashBytes length:CC_SHA1_DIGEST_LENGTH];
    [dataToHash release];
    NSString *encodedStr = [NSString stringWithUTF8String:[encodedData bytes]];
    //NSString *encodedStr = [[NSString alloc]  initWithBytes:[encodedData bytes]
    //                                            length:[encodedData length] encoding: NSUTF8StringEncoding];
    NSLog(@"String is %@", encodedStr);

    return encodedStr;

}

我要做的是采取NSString和SHA1编码。这部分似乎正在起作用,我认为我所处的位置是如何将NSData对象转换回清晰的字符串。如果我使用UTF8编码,我会变成空白,如果我说ASCII,我会得到奇怪的字符。我真正想要的是十六进制字符串,但我不知道如何获得它。这是使用iPhone 3.0 SDK。

What I'm trying to do is take an NSString and SHA1 encode it. That part seems to be working, I think where I am falling over is in how to convert the NSData object back to a legible string. If I use UTF8 encoding I get blank, if I say ASCII I get weird characters. What I really want is the hex string, but I have no idea how to get it. This is using the iPhone 3.0 SDK.

目前我传入的任何字符串都会返回NULL。

At the moment any String I pass in comes back out NULL.

推荐答案

简答:打开gcc警告(-Wall)。

Short answer: turn on gcc warnings (-Wall).

长答案:

NSMutableData *dataToHash = [[NSMutableData alloc] init];
[dataToHash appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];

已损坏:您尝试使用需要NSData参数的C字符串。使用

is broken: You try to use a C string where an NSData argument is expected. Use

NSMutableData *dataToHash = [str dataUsingEncoding:NSUTF8StringEncoding];

而不是。

其余的获取SHA1缓冲区并尝试将此数据解释为UTF-8 C字符串,这可能会崩溃或产生任何意外结果。首先,缓冲区不是UTF-8字符串。其次,它不是空终止。

The rest of the method takes the SHA1 buffer and tries interpret this data as an UTF-8 C string, which might crash or give any unexpected result. First, the buffer is not a UTF-8 string. Secondly, it's not null terminated.

你想要的是将SHA1转换为基数64或类似的字符串。 这是一个很好的帖子,关于如何做那个。

What you want is to convert the SHA1 to a base 64 or similar string. Here's a nice post about how to do that.

这篇关于尝试编写NSString sha1函数,但它返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆