SHA1哈希值产生不同的结果,在Objective-C和C#.NET [英] SHA1 hash producing different result in Objective-C and C#.NET

查看:224
本文介绍了SHA1哈希值产生不同的结果,在Objective-C和C#.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想要写函数,计算SHA1哈希值。

Basically I want to write function that computes sha1 hash.

到目前为止,我已经试过如下:

So far I have tried is as follows.

C#.NET

byte[] p2 = System.Text.Encoding.Unicode.GetBytes("password");
System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] result = sha.ComputeHash(p2);
string encodedPassword = Convert.ToBase64String(result);

输出:的6Pl / upEE0epQR5SObftn + s2fW3M =

Output : 6Pl/upEE0epQR5SObftn+s2fW3M=

的Objective-C

我添加类的Base64从 NSData_Base64类引用

I have added classes for Base64 from NSData_Base64 Classes reference.

NSString *password = @"password";
NSData *data = [password dataUsingEncoding:NSUTF8StringEncoding];
NSString *unicodePassword = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding];
data = [unicodePassword dataUsingEncoding:NSUnicodeStringEncoding];


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 base64EncodedString]);

输出:的dYusXVhObIBzJMgg1E1FJ9cK1NY =

Output : dYusXVhObIBzJMgg1E1FJ9cK1NY=

任何人都可以请建议我究竟做错了什么?

Can anyone please suggest what am I doing wrong ?

为什么这两个值不同?

Why these two values differs ?

请纠正我的错误。

推荐答案

这行是错误的,因为你跨preT UTF8 EN codeD数据,就好像它是统一code连接codeD

This line is wrong, since you interpret UTF8 encoded data as if it was Unicode encoded:

的NSString * UNI codePassword = [[NSString的页头] initWithData:数据编码:NSUni codeStringEncoding]。

NSString *unicodePassword = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding];

Replce所述第二线路与: 的NSData *数据= [密码dataUsingEncoding:NSUni codeStringEncoding];

Replce the second line with: NSData *data = [password dataUsingEncoding:NSUnicodeStringEncoding];

在数据的第2个字节是一个BOM(字节顺序标记)。

The 2 first bytes in data is a BOM (Byte order mark).

与删除这2个字节 数据= [NSData的dataWithBytes:[数据字节] + 2长度:[数据长度] - 2];

...然后散列数据的你将有相同的哈希在C#。

...and then hash that data any you will have the same hash as in C#.

这篇关于SHA1哈希值产生不同的结果,在Objective-C和C#.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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