在Objective-C中生成SHA256哈希

gar*_*ley 11 passwords macos objective-c sha256 password-hash

所以我需要在Objective-C中生成一个Sha256密码,并且无法弄清楚我的生活怎么做!有什么容易的东西,我只是缺少?

我已经尝试实现以下方法(这是为iPhone编写的,但我想也许它可以跨平台工作,就像一些Objective-C代码那样)

-(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;
}
Run Code Online (Sandbox Code Playgroud)

但这只是吐出有关CC_SHA256_DIGEST_LENGTH是未声明标识符的错误.

Jam*_*ess 19

您需要包含适当的头文件:

#include <CommonCrypto/CommonDigest.h>
Run Code Online (Sandbox Code Playgroud)

根据Cryptographic Services文档,这应该可以在iOS和OS X上使用.

在OS X v10.5及更高版本以及iOS 5.0及更高版本中,Common Crypto为加密和解密提供低级C支持.Common Crypto并不像Security Transforms那样简单,但提供了更广泛的功能,包括其他散列方案,密码模式等.

  • 我建议使用#import 而不是#include,因为它确保标头仅包含一次。#import 防止递归包含。 (2认同)
  • @doodle 虽然它是一个 C 头文件 - 它已经内置了该检查。 (2认同)

zap*_*aph 9

#import <CommonCrypto/CommonDigest.h>
Run Code Online (Sandbox Code Playgroud)

Objective-C:SHA256只有两行:

+ (NSData *)doSha256:(NSData *)dataIn {
    NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(dataIn.bytes, dataIn.length, macOut.mutableBytes);
    return macOut;
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

func sha256Hex(string: String) -> String? {
    guard let messageData = string.data(using:String.Encoding.utf8) else { return nil }
    var digestData = Data(count: Int(CC_SHA256_DIGEST_LENGTH))

    _ = digestData.withUnsafeMutableBytes {digestBytes in
        messageData.withUnsafeBytes {messageBytes in
            CC_SHA256(messageBytes, CC_LONG(messageData.count), digestBytes)
        }
    }

    return digestData.map { String(format: "%02hhx", $0) }.joined()
}
Run Code Online (Sandbox Code Playgroud)

//测试

let sha256HexString = sha256Hex(string:"Hello")
print("sha256HexString: \(sha256HexString!)")
Run Code Online (Sandbox Code Playgroud)

sha256HexString:"185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969"


Dan*_*ark 6

Objective-C 方法,其输出与在线随机站点的输出匹配

-(NSString*)sha256HashForText:(NSString*)text {
    const char* utf8chars = [text UTF8String];
    unsigned char result[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(utf8chars, (CC_LONG)strlen(utf8chars), 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;
}
Run Code Online (Sandbox Code Playgroud)

摘自这个要点