我如何在iOS中计算SHA-2(理想的SHA 256或SHA 512)散列? [英] How can I compute a SHA-2 (ideally SHA 256 or SHA 512) hash in iOS?

查看:231
本文介绍了我如何在iOS中计算SHA-2(理想的SHA 256或SHA 512)散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

安全服务API似乎不允许我直接计算哈希。有很多公共领域和许可版本可用,但我宁愿使用系统库实现,如果可能的话。



数据可以通过NSData或普通指针。



散列的加密强度对我很重要。 SHA-256是最小可接受的散列大小。

解决方案

这是我用于SHA1的内容:

  +(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];
返回sha1;
}
return nil;

CC_SHA1 替换为 CC_SHA256 (或您需要的任何一个)以及 CC_SHA1_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH $ b

您需要 #import< CommonCrypto / CommonDigest.h>


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.

The data is accessible via NSData, or plain pointers.

The cryptographic strength of the hash is important to me. SHA-256 is the minimum acceptable hash size.

解决方案

This is what I'm using for SHA1:

+ (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;
}

Replace CC_SHA1 with CC_SHA256 (or whichever you need), as well as CC_SHA1_DIGEST_LENGTH with CC_SHA256_DIGEST_LENGTH.

You need to #import <CommonCrypto/CommonDigest.h>

这篇关于我如何在iOS中计算SHA-2(理想的SHA 256或SHA 512)散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆