开发者

Equivalent Java javax.crypto libraries in Objective-C?

开发者 https://www.devze.com 2023-03-15 03:45 出处:网络
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):

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.getBy开发者_JAVA技巧tes(),"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]]);


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];


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消