xil3
xil3

Reputation: 16439

Equivalent Java javax.crypto libraries in Objective-C?

I'm doing the following in Java, which I would like to do the equivalent in Objective-C (minus the Base64 bit, which I already got working):

Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec secret = new SecretKeySpec(PRIVATE_KEY.getBytes(),"HmacSHA1");
mac.init(secret);
result =  Base64.encodeToString(mac.doFinal(data), Base64.DEFAULT);

Are there any Objective-C libraries that can help me do the equivalent?

* UPDATE *

Just an update - I got the following code running, but the out comes out null:

NSData *keyData = [PRIVATE_KEY dataUsingEncoding:NSUTF8StringEncoding];
NSData *clearTextData = [data dataUsingEncoding:NSUTF8StringEncoding];

uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};

CCHmacContext hmacContext;
CCHmacInit(&hmacContext, kCCHmacAlgSHA1, keyData.bytes, keyData.length);
CCHmacUpdate(&hmacContext, clearTextData.bytes, clearTextData.length);
CCHmacFinal(&hmacContext, digest);

NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];

NSLog(@"encrypted data: %@", [NSString stringWithUTF8String:[out bytes]]);

Upvotes: 0

Views: 1756

Answers (2)

Bill Brasky
Bill Brasky

Reputation: 2644

I recently worked on another project that did HMAC-SHA1 on iPhone. Here you go!

The secret key is Base64 encoded in a NSString called secretKey The string to sign is in the NSString called signString. If you already have NSData, just use that instead of clearTextData.

The output signature will be in base64Enc, or simply 'out' if you don't want it encoded.

NSData *keyData = [NSData dataWithBase64EncodedString:secretKey];
NSData *clearTextData = [signStr dataUsingEncoding:NSUTF8StringEncoding];

uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};

CCHmacContext hmacContext;
CCHmacInit(&hmacContext, kCCHmacAlgSHA1, keyData.bytes, keyData.length);
CCHmacUpdate(&hmacContext, clearTextData.bytes, clearTextData.length);
CCHmacFinal(&hmacContext, digest);

NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
NSString *base64Enc = [out base64Encoding];

Upvotes: 1

Stephen Darlington
Stephen Darlington

Reputation: 52565

Have a look at section 3cc of the manual. It includes various crypto-related algorithms including SHA1, HMAC and MD5. They're pretty low-level compared to a lot of Objective-C code, but they're pretty straight-forward as long as you know pointers.

Upvotes: 1

Related Questions