我正在尝试使用密钥对加密来验证我的应用程序和我的
PHP服务器之间的身份.为此,我需要在我的应用程序中生成公钥后将公钥发送到服务器.
if let pubKey = NSData(base64EncodedData: publicKey,options: NSDataBase64DecodingOptions.allZeros)! { println(pubKey) }
publicKey的类型为Unmanaged< SecKey>.
我在上面的代码中得到的错误是:调用中的额外参数’base64EncodedData’
我该怎么办?有没有更好的办法?
编辑:这是密钥对的生成方式:
var publicKeyPtr,privateKeyPtr: Unmanaged<SecKey>? let parameters = [ String(kSecAttrKeyType): kSecAttrKeyTypeRSA,String(kSecAttrKeySizeInBits): 2048 ] let result = SecKeyGeneratePair(parameters,&publicKeyPtr,&privateKeyPtr) let publicKey = publicKeyPtr!.takeRetainedValue() let privateKey = privateKeyPtr!.takeRetainedValue() let blockSize = SecKeyGetBlockSize(publicKey)
编辑2:所以问题是SecKey不是NSData,所以我的问题应该是:如何将publicKey:SecKey转换为NSData?
您似乎可以将密钥临时存储到钥匙串,然后将其恢复并将其转换为数据:
原文链接:https://www.f2er.com/swift/319553.htmlfunc convertSecKeyToBase64(inputKey: SecKey) ->String? { // First Temp add to keychain let tempTag = "de.a-bundle-id.temp" let addParameters :[String:AnyObject] = [ String(kSecClass): kSecClassKey,String(kSecAttrApplicationTag): tempTag,String(kSecAttrKeyType): kSecAttrKeyTypeRSA,String(kSecValueRef): inputKey,String(kSecReturnData):kcfBooleanTrue ] var keyPtr: Unmanaged<AnyObject>? let result = SecItemAdd(addParameters,&keyPtr) switch result { case noErr: let data = keyPtr!.takeRetainedValue() as! NSData // Remove from Keychain again: SecItemDelete(addParameters) let encodingParameter = NSDataBase64EncodingOptions(rawValue: 0) return data.base64EncodedStringWithOptions(encodingParameter) case errSecDuplicateItem: println("Duplicate Item") SecItemDelete(addParameters) return nil case errSecItemNotFound: println("Not found!") return nil default: println("Error: \(result)") return nil } }