SHA256 Swift to Objective C equivalence

痴心易碎 提交于 2020-01-17 16:34:47

问题


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()
    }

Can you help me ?


回答1:


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];
}

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

#import <CommonCrypto/CommonDigest.h>


来源:https://stackoverflow.com/questions/53361681/sha256-swift-to-objective-c-equivalence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!