AES Encryption using IV, Salt, RFC2898 iteration, Key Generation using SHA1 algorithm in iPhone

1.4k views Asked by At

I have a problem related to AES Encryption. The problem is I need to encrypt the string using AES encryption technique with Intialization Vector, Salt, RFC2898 iteration and Generate a key using sha1 algorithm.

I used this code

+(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;
}

For sha1 key generation but it produces totally different as this technique do in .net and Android.

Android and .net already have classes and library to do this and i left alone so how I can do it in iPhone.

1

There are 1 answers

0
Vlad On

This should be what you need

+ (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];
}