SHA256 Swift 到 Objective C 的等价 [英] SHA256 Swift to Objective C equivalence

查看:54
本文介绍了SHA256 Swift 到 Objective C 的等价的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我是第一次使用 SHA256,我正在尝试学习关于此的教程,我的问题是在 SHA 256 的目标 C 中编写等效项.我试图了解我的功能在下面向您展示,但我仍然有关于如何在 Objective C 中找到这个 Swift 函数的等价性的问题

Hello everyone I'm working for the first time with SHA256 and I'm trying to follow a tutorial on this my problem is to write the equivalence in Objective C of SHA 256. I'm trying to understand the function that I show you below but I still have problems on how to find the equivalence in Objective C of this Swift function

let rsa2048Asn1Header:[UInt8] = [
        0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
        0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00
    ]

 private func sha256(data : Data) -> String {
        var keyWithHeader = Data(bytes: rsa2048Asn1Header)
        keyWithHeader.append(data)
        var hash = [UInt8](repeating: 0,  count: Int(CC_SHA256_DIGEST_LENGTH))
        keyWithHeader.withUnsafeBytes {
            _ = CC_SHA256($0, CC_LONG(keyWithHeader.count), &hash)
        }
        return Data(hash).base64EncodedString()
    }

你能帮我吗?

推荐答案

在 Objective-C 中处理原始字节通常比 Swift 更简单一些.像这样的实现应该是等效的.

Working with raw bytes in Objective-C is generally a little more straightforward than Swift. An implementation like this should be equivalent.

#define RSA_2048_ASN1_HDR_LEN 24

- (NSString *)sha256:(NSData *)data {
    NSMutableData *keyWithHeader = [NSMutableData dataWithBytes:rsa2048Asn1Header length:RSA_2048_ASN1_HDR_LEN];
    [keyWithHeader appendData:data];
    UInt8 hash[CC_SHA256_DIGEST_LENGTH] = { 0 };
    CC_SHA256(keyWithHeader.bytes, (CC_LONG) keyWithHeader.length, hash);
    return [[NSData dataWithBytes:hash length:CC_SHA256_DIGEST_LENGTH] base64EncodedStringWithOptions:0];
}

请注意,您还需要将通用加密库导入到您的 Objective-C 文件中:

Note that you'll also need to import the common crypto library into your Objective-C file as well:

#import <CommonCrypto/CommonDigest.h>

这篇关于SHA256 Swift 到 Objective C 的等价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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