Converting a base64EncodedString back to P521.KeyAgreement.PublicKey

Hello,


Given the following example:


let privateKeyA = P521.KeyAgreement.PrivateKey() //Stored locally on device

let publicKeyA = privateKeyA.publicKey

let publicKeyAString = publicKeyA.rawRepresentation.base64EncodedString() //Stored on the server


My question is how do I later convert the publicKeyAString back into a proper publicKey of type: "P521.KeyAgreement.PublicKey"


With the end goal of something like:


let sharedSecret = try? privateKeyB.sharedSecretFromKeyAgreement(with: publicKeyA)

Accepted Reply

According to the docs, you can decode your Base-64 to `Data` and then construct an instance of `P521.KeyAgreement.PublicKey`:

if let data = Data(base64Encoded: publicKeyAString) {
    do {
        let publicKey = try P521.KeyAgreement.PublicKey(rawRepresentation: data)
        let sharedSecet = try privateKeyA.sharedSecretFromKeyAgreement(with: publicKey)
        //...
    } catch {
        print(error)
    }
} else {
    print("invalid base-64")
}

Replies

According to the docs, you can decode your Base-64 to `Data` and then construct an instance of `P521.KeyAgreement.PublicKey`:

if let data = Data(base64Encoded: publicKeyAString) {
    do {
        let publicKey = try P521.KeyAgreement.PublicKey(rawRepresentation: data)
        let sharedSecet = try privateKeyA.sharedSecretFromKeyAgreement(with: publicKey)
        //...
    } catch {
        print(error)
    }
} else {
    print("invalid base-64")
}

@OOPer,


Thank you. Where did you find this in the documentation?

P521.KeyAgreement.PublicKey


`P521.KeyAgreement.PublicKey` has an initializer `init(rawRepresentation:)`, and you can easily guess it is a counter part of `rawRepresentation` property.

Thanks!