IOS sha1错误输出

时间:2014-10-23 07:30:02

标签: c# ios

我试图在IOS中输入相同的Sha1,但结果并不相同。

由于这个答案SO,它应该没问题,结果相同

这是我的C#代码:

    using (SHA1 sha1Hash = SHA1.Create())
     {
            string hash1 = GetSHA1Hash(sha1Hash, "8390495498");
     }

    static string GetSHA1Hash(SHA1 sha1Hash, string input)
    { 
        byte[] data = sha1_Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
        StringBuilder sBuilder = new StringBuilder();
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }
        return sBuilder.ToString();
    }

结果是:d763bd0b5b346a3c95eb4f2912be40c2ce6f0a41

我的Objective C代码:

   [sh1obj sha1:@"8390495498"]
- (NSString *)sha1:(NSString *)str {
    NSData *data = [str dataUsingEncoding:NSUnicodeStringEncoding];

    NSString *unicodePassword = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding];
    data = [unicodePassword dataUsingEncoding:NSUnicodeStringEncoding];
    data = [NSData dataWithBytes:[data bytes] + 2 length:[data length] - 2];

    unsigned char hash[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1([data bytes], [data length], hash);
    NSData *result = [NSData dataWithBytes:hash length:CC_SHA1_DIGEST_LENGTH];
    NSLog(@"Result: %@",result);

    return result;
}

结果是:&lt; 241cdda1 6867aaad cb69faed d0975579 f6ec3a07&gt;

我甚至也试过这个:

  [sh1obj sha1:@"8390495498"]
- (NSString *)sha1:(NSString *)str {

    const char *cStr = [str UTF8String];
    unsigned char result[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(cStr, strlen(cStr), result);
    NSString *s = [NSString  stringWithFormat:
                   @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                   result[0], result[1], result[2], result[3], result[4],
                   result[5], result[6], result[7],
                   result[8], result[9], result[10], result[11], result[12],
                   result[13], result[14], result[15],
                   result[16], result[17], result[18], result[19]
                   ];
    NSLog(@"Result: %@",s);
    return s;
}

,结果是:cbdb5d7936ac9a56846cabad5e9d41942a08b49c

1 个答案:

答案 0 :(得分:1)

我认为Objective-C代码是正确的:

$ echo -n 8390495498 | openssl sha1  
cbdb5d7936ac9a56846cabad5e9d41942a08b49c