Hayden Young
Hayden Young

Reputation: 356

Can't convert withUnsafeBytes to non-deprecated code with SHA-256

I had an issue before with the withUnsafeBytes method on Data being deprecated. I managed to get it working with the newer method for using SHA-512.

I recently encountered the same issue again and tried to re-use the same solution as before but changed the SHA-512 to SHA-256 but it didn't decode the data into a string correctly

Here is what I have as me trying to see if it will work:

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
    ]

func sha256(data: Data) -> String {
        var keyWithHeader = data// Data(rsa2048Asn1Header)
        keyWithHeader.append(data)

        var hash: UnsafeMutablePointer<UInt8>! = nil/// [UInt8](repeating: 0,  count: Int(CC_SHA256_DIGEST_LENGTH))

        var result = Data(count: Int(CC_SHA256_DIGEST_LENGTH))
        _ = result.withUnsafeMutableBytes({ resultBytes in
            hash = resultBytes.baseAddress?.assumingMemoryBound(to: UInt8.self)
            keyWithHeader.withUnsafeBytes({ stringBytes in
                let sBytes = resultBytes.baseAddress?.assumingMemoryBound(to: UInt8.self)
                CC_SHA256(sBytes, CC_LONG(keyWithHeader.count), hash)
        })

        let string = String(cString: hash)
        return string.data(using: .utf8)!.base64EncodedString()
}

but the string it creates is completely wrong and not the same as using the deprecated method:

var hash = [UInt8](repeating: 0,  count: Int(CC_SHA256_DIGEST_LENGTH))

        keyWithHeader.withUnsafeBytes {
            _ = CC_SHA256($0, CC_LONG(keyWithHeader.count), &hash)
        }

I'm not sure what I've done wrong because it was working when I used this code with SHA-512

Upvotes: 2

Views: 499

Answers (1)

Sean Lintern
Sean Lintern

Reputation: 3141

You can now use the updated CryptoKit

import CommonCrypto

func cryptoSHA256(data : Data) -> String {
    let hash = SHA256.hash(data: keyWithHeader)
    return Data(hash).base64EncodedString()
}

Hope this helps.

Upvotes: 1

Related Questions