Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
216 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...