使用IV,Salt,RFC2898迭代进行AES加密,使用iPhone中的SHA1算法生成密钥

时间:2011-10-21 10:29:13

标签: iphone aes sha1 salt initialization-vector

我遇到与AES加密有关的问题。问题是我需要使用AES加密技术加密字符串,使用Intialization Vector,Salt,RFC2898迭代并使用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中执行此操作。

1 个答案:

答案 0 :(得分: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];
}