2

我有一个与 AES 加密有关的问题。问题是我需要使用带有初始化向量、Salt、RFC2898 迭代的 AES 加密技术对字符串进行加密,并使用 sha1 算法生成密钥。

我用了这段代码

+(NSString *)stringToSha1:(NSString *)str{
const char *s = [str cStringUsingEncoding:NSASCIIStringEncoding];
NSData *keyData = [NSData dataWithBytes:s length:strlen(s)];

// This is the destination
uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};
// This one function does an unkeyed SHA1 hash of your hash data
CC_SHA1(keyData.bytes, keyData.length, digest);

// Now convert to NSData structure to make it usable again
NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
// description converts to hex but puts <> around it and spaces every 4 bytes
NSString *hash = [out description];
hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];

NSLog(@"Hash is %@ for string %@", hash, str);

return hash;
}

对于 sha1 密钥生成,但它产生的效果与 .net 和 Android 中的这种技术完全不同。

Android 和 .net 已经有类和库可以做到这一点,我独自离开了,所以我如何在 iPhone 中做到这一点。

4

1 回答 1

0

这应该是你需要的

+ (NSData *)sha1HashFromString:(NSString *)stringToHash {
    NSData *stringData = [stringToHash dataUsingEncoding:NSASCIIStringEncoding];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};
    CC_SHA1([stringData bytes], [stringData length], digest);
    NSData *hashedData = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
    return [hashedData autorelease];
}
于 2011-10-21T11:20:17.527 回答