2016-05-14 46 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=