如何在 iOS 中计算 SHA-2(最好是 SHA 256 或 SHA 512)哈希? [英] How can I compute a SHA-2 (ideally SHA 256 or SHA 512) hash in iOS?
问题描述
安全服务 API 似乎不允许我直接计算哈希.有很多可用的公共领域和自由许可版本,但如果可能,我宁愿使用系统库实现.
The Security services API doesn't appear to allow me to compute a hash directly. There are plenty of public domain and liberally licensed versions available, but I'd rather use a system library implementation if possible.
可以通过 NSData 或普通指针访问数据.
The data is accessible via NSData, or plain pointers.
散列的加密强度对我很重要.SHA-256 是可接受的最小哈希大小.
The cryptographic strength of the hash is important to me. SHA-256 is the minimum acceptable hash size.
推荐答案
这是我用于 SHA1 的内容:
This is what I'm using for 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;
}
将 CC_SHA1
替换为 CC_SHA256
(或您需要的任何一个),以及将 CC_SHA1_DIGEST_LENGTH
替换为 CC_SHA256_DIGEST_LENGTH
.
Replace CC_SHA1
with CC_SHA256
(or whichever you need), as well as CC_SHA1_DIGEST_LENGTH
with CC_SHA256_DIGEST_LENGTH
.
这篇关于如何在 iOS 中计算 SHA-2(最好是 SHA 256 或 SHA 512)哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!