2016-05-14 71 views
0

C#代码。使用SHA1在C#和IOS中加密

SHA1 hash = SHA1.Create(); 
ASCIIEncoding encoder = new ASCIIEncoding(); 
byte[] combined = encoder.GetBytes(password); 
hash.ComputeHash(combined); 
passwordHash = Convert.ToBase64String(hash.Hash); 

如何在IOS中获得相同的结果?请帮帮我。

到目前为止,我已经做了这么多,但结果比C#

NSString *password = @"XABCVKXMWJ"; // your password 

CFIndex asciiLength; 
// Determine length of converted data: 
CFStringGetBytes((__bridge CFStringRef)(password), CFRangeMake(0, [password length]), 
       kCFStringEncodingASCII, '?', false, NULL, 0, &asciiLength); 
// Allocate buffer: 
uint8_t *asciiBuffer = malloc(asciiLength); 
// Do the conversion: 
CFStringGetBytes((__bridge CFStringRef)(password), CFRangeMake(0, [password length]), 
       kCFStringEncodingASCII, '?', false, asciiBuffer, asciiLength, NULL); 
unsigned char hash[CC_SHA1_DIGEST_LENGTH]; 
CC_SHA1(asciiBuffer, asciiLength, hash); 
free(asciiBuffer); 
NSData *result = [NSData dataWithBytes:hash length:CC_SHA1_DIGEST_LENGTH]; 

是不同的,结果我从C#代码得到的是 uSFCLAZZHkBVN7xViO3hKkhhR/S =

和IOS,它是 uSFCLAZZHkBVN7xViO3hKkhhR + s =

+2

只是一个侧面说明:哈希是_not_加密! –

+1

您可以在iOS上使用CommonCrypto库。 – Paulw11

回答

0

iOS的结果是正确的,C#和iOS之间有一些区别,可能combined是不同的。验证C#代码中每个步骤的中间值,查看下面示例代码中的所有中间值。

这是我的Objective-C实现,它产生与您一样的结果。
注意:不需要使用Core Foundation或malloc

#import <CommonCrypto/CommonCrypto.h> 

NSString *password = @"XABCVKXMWJ"; 

NSData *combined = [password dataUsingEncoding:NSUTF8StringEncoding]; 
NSMutableData *hash = [NSMutableData dataWithLength:CC_SHA1_DIGEST_LENGTH]; 
CC_SHA1(combined.bytes, (unsigned int)combined.length, hash.mutableBytes); 
NSString *passwordHash = [hash base64EncodedStringWithOptions:0]; 

NSLog(@"password:  %@", password); 
NSLog(@"combined:  %@", combined); 
NSLog(@"hash:   %@", hash); 
NSLog(@"passwordHash: %@", passwordHash); 

输出:

 
password:  XABCVKXMWJ 
combined:  58414243564b584d574a 
hash:   b921422c06591e405537bc5588ede12a486147eb 
passwordHash: uSFCLAZZHkBVN7xViO3hKkhhR+s= 
相关问题