之前在博文中實現的SHA1的安全性已經滿足不了使用者需求,今天把SHA224/SHA256/SHA384/SHA512的實現一併附上。 SHA即Secure Hash Algorithm(安全散列演算法)有多種不同位元的實現,常見的有SHA224/SHA256/SHA384/SHA512等
SHA224:
|
- (NSString*) sha224{ const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding]; NSData *data = [NSData dataWithBytes:cstr length:self.length]; uint8_t digest[CC_SHA224_DIGEST_LENGTH]; CC_SHA224(data.bytes, data.length, digest); NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA224_DIGEST_LENGTH * 2]; for(int i = 0; i < CC_SHA224_DIGEST_LENGTH; i++) [output appendFormat:@"%02x", digest[i]]; return output;} |
SHA256:
|
- (NSString*) sha256{ const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding]; NSData *data = [NSData dataWithBytes:cstr length:self.length]; 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;} |
SHA384:
|
- (NSString*) sha384{ const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding]; NSData *data = [NSData dataWithBytes:cstr length:self.length]; uint8_t digest[CC_SHA384_DIGEST_LENGTH]; CC_SHA384(data.bytes, data.length, digest); NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA384_DIGEST_LENGTH * 2]; for(int i = 0; i < CC_SHA384_DIGEST_LENGTH; i++) [output appendFormat:@"%02x", digest[i]]; return output;} |
SHA512:
|
- (NSString*) sha512{ const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding]; NSData *data = [NSData dataWithBytes:cstr length:self.length]; uint8_t digest[CC_SHA512_DIGEST_LENGTH]; CC_SHA512(data.bytes, data.length, digest); NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2]; for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++) [output appendFormat:@"%02x", digest[i]]; return output;} |
放到一起大團結
|
////NSString+SHA.h// #import <Foundation/Foundation.h>#import <CommonCrypto/CommonDigest.h>#import <CommonCrypto/CommonCryptor.h> @interface NSString(SHA)-(NSString *) sha1;-(NSString *) sha224;-(NSString *) sha256;-(NSString *) sha384;-(NSString *) sha512;@end ////NSString+SHA.m// #import "NSString+SHA.h" @implementation NSString(SHA) - (NSString*) sha1{ const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding]; NSData *data = [NSData dataWithBytes:cstr length:self.length]; 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;} - (NSString*) sha224{ const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding]; NSData *data = [NSData dataWithBytes:cstr length:self.length]; uint8_t digest[CC_SHA |