21-DOT-DEV / swift-secp256k1

Elliptic Curve, Schnorr, and ZKP for Bitcoin. Supports iOS macOS tvOS watchOS visionOS + Linux.
MIT License
107 stars 53 forks source link

Shared Key with base64 public key #613

Closed YisusJesusA closed 2 days ago

YisusJesusA commented 3 days ago

Hello, am receiving a public key in base 64 format, and I am using the Elliptic Curve Diffie Hellman Key Agreement. But how can I obtain de shared key with this type of public key. Is it possible?

csjones commented 3 days ago

Hey @YisusJesusA 👋

Is this what you're looking for?

let base64PublicKey = "AjUh33uUJI/98NN/c4pHksw5Mraxbiefcc3eglE4Oybn" // Your BASE64 Public Key
let publicKeyData = Data(base64Encoded: base64PublicKey)!

// Convert to secp256k1 public key
let publicKey = try! secp256k1.KeyAgreement.PublicKey(dataRepresentation: publicKeyData)

// Your private key
let privateKey = try! secp256k1.KeyAgreement.PrivateKey()

// Perform Key Agreement
let sharedSecret = try! privateKey.sharedSecretFromKeyAgreement(with: publicKey)

// Get the shared secret as data
let sharedKeyData = Data(sharedSecret.bytes)

print("Shared Key: \(sharedKeyData.base64EncodedString())")
YisusJesusA commented 3 days ago

I am trying to do the same but my public key in base 64 is larger and getting this error.

This is my publickey public = "BP8CBxIFebe2xjpvI7R4d0c28v7uJRqIkQAnyNh5By8t/AMAlSw+eJzeNQt1cF2saaCVydbXZzkhv6bufIAAUSc="

this publickey string is like the one Im generating with this methods:

let publicKey = try! secp256k1.KeyAgreement.PrivateKey().publicKey let b64Key = String(publicKey.rawRepresentation.base64EncodedString())

but since im receiving base64 publickey from server I not able to use those methods

csjones commented 2 days ago

This is my publickey public = "BP8CBxIFebe2xjpvI7R4d0c28v7uJRqIkQAnyNh5By8t/AMAlSw+eJzeNQt1cF2saaCVydbXZzkhv6bufIAAUSc="

This is an uncompressed public key and therefore needs to be specified.

let base64PublicKey = "BP8CBxIFebe2xjpvI7R4d0c28v7uJRqIkQAnyNh5By8t/AMAlSw+eJzeNQt1cF2saaCVydbXZzkhv6bufIAAUSc="
let publicKeyData = Data(base64Encoded: base64PublicKey)!

// Create an uncompressed public key
let publicKey = try! secp256k1.KeyAgreement.PublicKey(
    dataRepresentation: publicKeyData,
    format: .uncompressed
)