Objective-Cリハビリ中メモ。
環境: Xcode 4.6.3, iOS 6.
Objective-Cで md5, sha1, sha2 を作ってみる。
md5
// md5 +(NSString *) md5WithString:(NSString *)input { const char *cStr = [input UTF8String]; unsigned char digest[16]; CC_MD5( cStr, strlen(cStr), digest ); NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2]; for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) [output appendFormat:@"%02x", digest[i]]; return output; } |
sha1
// sha1 +(NSString *) sha1WithString:(NSString *)input { NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding]; uint8_t digest[CC_SHA1_DIGEST_LENGTH]; CC_SHA1(data.bytes, data.length, digest); NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) [output appendFormat:@"%02x", digest[i]]; return output; } |
sha2
// sha2 +(NSString *) sha2WithString:(NSString *)input { NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding]; uint8_t digest[CC_SHA256_DIGEST_LENGTH]; CC_SHA256(data.bytes, data.length, digest); NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2]; for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) [output appendFormat:@"%02x", digest[i]]; return output; } |
依存ライブラリ: libSystem.dylib
TARGETS選択
Summary > Linked Frameworks and Library > [+]
で追加すると、追加後にGroup位置変えてもリンクが切れなかった。
【参考】
How to get md5 and SHA1 in objective c (iOS sdk)
stackoverflow: MD5 algorithm in Objective C