我如何连接code非托管&LT; SecKey&GT;为Base64发送到另一台服务器? [英] How do I encode an unmanaged<SecKey> to base64 to send to another server?
问题描述
我试图使用密钥对加密到我的应用程序,我的PHP服务器之间的验证身份。要做到这一点,我需要在发送公钥到服务器之后我生成它在我的应用程序。
I'm trying to use key pair encryption to validate identity between my app and my PHP server. To do this I need to send the public key over to the server after I generate it in my app.
if let pubKey = NSData(base64EncodedData: publicKey, options: NSDataBase64DecodingOptions.allZeros)! {
println(pubKey)
}
公钥
的类型为未管理&LT; SecKey方式&gt;
我得到在上面code中的错误是:额外的参数'base64En codedData呼叫
The error I'm getting in the above code is: Extra argument 'base64EncodedData' in call
我会怎么做呢?有没有更好的办法?
How would I do this? Is there a better way?
编辑:这是如何生成密钥对:
This is how the keypair is generated:
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的,所以在这里我的问题应该是:我如何转换公钥:SecKey到NSData的
Edit 2: So the issue is that SecKey is not NSData, so my question here should be: How do I convert a publicKey:SecKey to NSData?
推荐答案
看来你可以临时存储的关键,钥匙圈,然后拿回来,并将其转换为数据:
It seems that you can temporary store the key to keychain and then get it back and convert it to data:
func 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
}
}
这篇关于我如何连接code非托管&LT; SecKey&GT;为Base64发送到另一台服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!