使用在El Capitan下运行的swift 2.2,Xcode 7.3。
试过这个......
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!)
不幸的是,它产生nil,nil作为公钥/私钥对。
我打电话给:
generateKeyPair("ch.blah.public",privateKeyTag: "ch.blah.private",keySize: 32)
我在这里缺少什么?显然这曾经有用吗?
Generate keychain key with swift 2.0
它打印的错误是0;哪种表明它确实有效?
答案 0 :(得分:1)
您使用RSA的无效密钥长度。此外,kSecAttrApplicationTag
必须是NSData
对象,而不是NSString
对象。
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)