I am trying to compute ECDH ( secp256k1 ) shared secret based on private key "5785cb919db4984453826032a411248184536c632096c647f72db4e66a8bd091" and public key "0425a4ef791d8d855077c4d5dd6ca87cbda2f3296939a350e4ea57b3f0235fe1ba4d02cb29f6391675e866944065f9905a30a3e472c45c7ad7afa06143d87efa13"
我快速使用secp256k1。
let myPrKeyBytes: [UInt8] = [87, 133, 203, 145, 157, 180, 152, 68,
83, 130, 96, 50, 164, 17, 36, 129, 132,
83, 108, 99, 32, 150, 198, 71, 247, 45,
180, 230, 106, 139 ,208, 145]
let myPubKeyBytes: [UInt8] = [4, 37, 164, 239, 121, 29, 141, 133,
80, 119, 196, 213, 221, 108, 168, 124,
189, 162, 243, 41, 105, 57, 163, 80,
228, 234, 87, 179, 240, 35, 95, 225,
186, 77, 2, 203, 41, 246, 57, 22, 117,
232, 102, 148, 64, 101, 249, 144, 90,
48, 163, 228, 114, 196, 92, 122, 215,
175, 160, 97, 67, 216, 126, 250, 19]
let ctx = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN))
var publicKeyParsed = secp256k1_pubkey()
let publicKeyParseStatus = secp256k1_ec_pubkey_parse(
ctx!,
&publicKeyParsed,
myPubKeyBytes,
myPubKeyBytes.count
)
guard publicKeyParseStatus == 1 else {
fatalError("Couldn't parse the public key")
}
let sharedSecretLength = 32
let sharedSecret = UnsafeMutablePointer<UInt8>
.allocate(capacity: sharedSecretLength)
let sharedSecretComputeStatus = secp256k1_ecdh(
ctx!,
sharedSecret,
&publicKeyParsed,
myPrKeyBytes
)
guard sharedSecretComputeStatus == 1 else {
fatalError("Couldn't compute shared secret")
}
var sharedSecretBytes: [UInt8] = []
for i in 0..<sharedSecretLength {
sharedSecretBytes.append(sharedSecret[i])
}
let sharedSecretStr = sharedSecretBytes
.map { String(format: "%02x", $0) }
.joined()
print("Shared secret: \(sharedSecretStr)")
// Shared secret: 4d6f4351d68351c419408621efddfcfcc0bc10270669af822093fcf22c9ca26c
我有“4d6f4351d68351c419408621efddfcfcc0bc10270669af822093fcf22c9ca26c”共享秘密,但正确的秘密应该是“ccf231a0ce74e92d9a94265ab27aa4616a3683af5df5aa65f4a011ad83673b”