Trying to Write NSString sha1 function, but it's returning null

后端 未结 4 877
有刺的猬
有刺的猬 2020-12-17 02:09

I have the following Objective-C function:

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


        
4条回答
  •  悲&欢浪女
    2020-12-17 03:00

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

    Long answer:

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

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

    NSMutableData *dataToHash = [str dataUsingEncoding:NSUTF8StringEncoding];
    

    instead.

    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.

    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.

提交回复
热议问题