[英]Encryption in C# and IOS using SHA1
C#代码。
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 =
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=
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.