user3069232 user3069232 - 7 months ago 76
Swift Question

GenerateKeyPair changed in swift 2.2

Using swift 2.2, Xcode 7.3 running under El Capitan.

Just tried this...

public func generateKeyPair(publicKeyTag: String, privateKeyTag:String,` `keySize: Int) -> KeyPair? {

let privateKeyAttr: [NSString: AnyObject] = [
kSecAttrIsPermanent: true,
kSecAttrApplicationTag: privateKeyTag
]
let publicKeyAttr: [NSString: AnyObject] = [
kSecAttrIsPermanent: true,
kSecAttrApplicationTag: publicKeyTag
]
let parameters: [NSString: AnyObject] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeySizeInBits: keySize,
kSecPrivateKeyAttrs: privateKeyAttr,
kSecPublicKeyAttrs: publicKeyAttr
]

var publicKey: SecKey?
var privateKey: SecKey?
let result = SecKeyGeneratePair(parameters, &publicKey, &privateKey)

if result != errSecSuccess {
return nil
}
return KeyPair(publicKey: publicKey!, privateKey: privateKey!)


And unfortunately it produces nil, nil as a public/private key pair.

I called it with:

generateKeyPair("ch.blah.public",privateKeyTag: "ch.blah.private",keySize: 32)


What am I missing here? Apparently this used to work?

Generate keychain key with swift 2.0

The error no it prints is 0; which sort of suggests it did work?

Answer

You are using an invalid key length for RSA. Also, kSecAttrApplicationTag needs to be a NSData object, not a NSString object.

public func generateKeyPair(publicKeyTag: String, privateKeyTag:String, keySize: Int) {       
    let privateKeyAttr: [NSString: AnyObject] = [
        kSecAttrIsPermanent: true,
        kSecAttrApplicationTag: privateKeyTag.dataUsingEncoding(NSUTF8StringEncoding)!
    ]
    let publicKeyAttr: [NSString: AnyObject] = [
        kSecAttrIsPermanent: true,
        kSecAttrApplicationTag: publicKeyTag.dataUsingEncoding(NSUTF8StringEncoding)!
    ]
    let parameters: [NSString: AnyObject] = [
        kSecAttrKeyType: kSecAttrKeyTypeRSA,
        kSecAttrKeySizeInBits: keySize,
        kSecPrivateKeyAttrs: privateKeyAttr,
        kSecPublicKeyAttrs: publicKeyAttr
    ]

    var publicKey: SecKey?
    var privateKey: SecKey?
    let result = SecKeyGeneratePair(parameters, &publicKey, &privateKey)

    if result != errSecSuccess {
        print("Result: \(result)")
        return
    }

    print("Public: \(publicKey)")
    print("Private: \(privateKey)")
}

generateKeyPair("ch.blah.public", privateKeyTag: "ch.blah.private", keySize: 2048)
Comments