在Objective-C中生成SHA256哈希 [英] Generate SHA256 hash in Objective-C
问题描述
所以我需要在Objective-C中生成一个Sha256密码,并且无法弄清楚我该怎么做!我只是想念一些简单的事情吗?
So I need to generate a Sha256 password in Objective-C, and can't figure out for the life of me how to do it! Is there something easy I'm just missing?
我尝试实现以下方法(该方法是为iPhone编写的,但我认为它可以像某些Objective-C代码一样跨平台工作)
I've tried implementing the following method (which was written for iPhone, but I figured maybe it'd work cross-platform, as some Objective-C code does)
-(NSString*)sha256HashFor:(NSString*)input
{
const char* str = [input UTF8String];
unsigned char result[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(str, strlen(str), result);
NSMutableString *ret = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2];
for(int i = 0; i<CC_SHA256_DIGEST_LENGTH; i++)
{
[ret appendFormat:@"%02x",result[i]];
}
return ret;
}
但这只是吐出关于CC_SHA256_DIGEST_LENGTH是未声明的标识符的错误.
But that just spat out errors about CC_SHA256_DIGEST_LENGTH being an undeclared identifier.
推荐答案
您需要包括相应的头文件:
You need to include the appropriate header file:
#include <CommonCrypto/CommonDigest.h>
According to the Cryptographic Services documentation this should be available on both iOS and OS X.
在OS X v10.5和更高版本以及iOS 5.0和更高版本中,Common Crypto为加密和解密提供了底层C支持.通用加密不像安全转换那样简单,但是提供了更广泛的功能,包括其他哈希方案,密码模式等.
In OS X v10.5 and later and iOS 5.0 and later, Common Crypto provides low-level C support for encryption and decryption. Common Crypto is not as straightforward as Security Transforms, but provides a wider range of features, including additional hashing schemes, cipher modes, and so on.
这篇关于在Objective-C中生成SHA256哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!