如何将非托管<seckey>编码为base64以发送到另一台服务器?</seckey>

时间:2015-01-03 19:00:07

标签: swift base64 public-key-encryption

我尝试使用密钥对加密来验证我的应用和我的PHP服务器之间的身份。为此,我需要在我的应用程序中生成公钥后将公钥发送到服务器。

if let pubKey = NSData(base64EncodedData: publicKey, options: NSDataBase64DecodingOptions.allZeros)! {
    println(pubKey)
}

publicKey的类型为Unmanaged<SecKey>

我在上述代码中遇到的错误是:Extra argument 'base64EncodedData' in call

我该怎么做?还有更好的方法吗?

编辑:这是生成密钥对的方式:

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?

3 个答案:

答案 0 :(得分:6)

您似乎可以将密钥临时存储到钥匙串中,然后将其恢复并将其转换为数据:

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
    }
}

答案 1 :(得分:0)

虽然事实几乎没有记录,但可以使用SecKeySecKeyCopyAttributes中提取您需要的所有内容(即模数和指数)。

有关详细信息,请参阅here

答案 2 :(得分:0)

快速4方法从SecKey,publicKey中获取base64字符串:)

guard let publicKeyData = SecKeyCopyExternalRepresentation(publicKey!, nil) else {
            NSLog("\tError obtaining export of public key.")
            return ""
        }
        let publicKeyNSData = NSData(data: publicKeyData as Data)
        let publicKeyBase64Str = publicKeyNSData.base64EncodedString()