Jam*_*mes 57 security hash objective-c sha256 ios
安全服务API似乎不允许我直接计算哈希.有很多公共领域和自由许可的版本可用,但我宁愿使用系统库实现,如果可能的话.
可以通过NSData或普通指针访问数据.
哈希的加密强度对我来说很重要.SHA-256是可接受的最小散列大小.
ale*_*x-i 79
这就是我用于SHA1的内容:
#import <CommonCrypto/CommonDigest.h>
+ (NSData *)sha1:(NSData *)data {
unsigned char hash[CC_SHA1_DIGEST_LENGTH];
if ( CC_SHA1([data bytes], [data length], hash) ) {
NSData *sha1 = [NSData dataWithBytes:hash length:CC_SHA1_DIGEST_LENGTH];
return sha1;
}
return nil;
}
Run Code Online (Sandbox Code Playgroud)
更换CC_SHA1用CC_SHA256(或任何你需要的),以及CC_SHA1_DIGEST_LENGTH用CC_SHA256_DIGEST_LENGTH.
Ege*_*nar 33
这是一个非常类似的基于NSString的
+ (NSString *)hashed_string:(NSString *)input
{
const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:input.length];
uint8_t digest[CC_SHA256_DIGEST_LENGTH];
// This is an iOS5-specific method.
// It takes in the data, how much data, and then output format, which in this case is an int array.
CC_SHA256(data.bytes, data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
// Parse through the CC_SHA256 results (stored inside of digest[]).
for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x", digest[i]];
}
return output;
}
Run Code Online (Sandbox Code Playgroud)
(学分转到http://www.raywenderlich.com/6475/basic-security-in-ios-5-tutorial-part-1)
| 归档时间: |
|
| 查看次数: |
32223 次 |
| 最近记录: |