Max
Max

Reputation: 5932

iOS swift : SecKeyCreateWithData returns nil

Trying to generate a SecKey from SecKeyCreateWithData function of swift as below. The SecKeyCreateWithData is always returning nil with below error log. Can anyone please help.

Note : Both cekKeyData as CFData and attributes as CFDictionary are not nil and have values in it.

log :

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

code

    let keydatalen = 256
    let algorithmID = ""
    let partyUInfo = ""

    let cekKeyData = DHSecretGenerator.createDeriveKey(
        Z: sharedKey,
        KeyLenght: keydatalen,
        AlgorithmID: KDFConcateWithLenght(text: algorithmID, encoding: .ascii),
        PartyUInfo: KDFConcateWithLenght(text: partyUInfo, encoding: .utf8),
        PartyVInfo: KDFConcateWithLenght(text: reference, encoding: .ascii),
        SuppPubInfo: numberToData(number: UInt32(keydatalen)),
        SuppPrivInfo: Data())

    let attributes: [String: Any] = [
                kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
                kSecAttrKeyClass as String: kSecAttrKeyClassSymmetric
            ]

    var error: Unmanaged<CFError>?
            var test: SecKey =
            let privKey : SecKey = SecKeyCreateWithData(cekKeyData as CFData,
                                                        attributes as CFDictionary, &error)!
            print(privKey)

Upvotes: 1

Views: 2679

Answers (1)

vaibby
vaibby

Reputation: 1265

Specify length and type of key Lengths for example 256 and all Type is public or private I guess Symmetric is which public and private is same but not pretty sure abt that.

let attributes: [String: Any] = [ kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeyClass as String: kSecAttrKeyClassPublic, kSecAttrKeySizeInBits as String: 256 ]

Upvotes: 1

Related Questions