Search code examples
swiftcryptographyelliptic-curveapple-cryptokit

SECP256K1 Verify using SawTooth Swift


I'm trying to use SawTooth SDK in order to make a sign/verify of a Secp256k1 keys pair. Everyone seems to be great expect the end when I try to verify :

let context = Secp256k1Context()

//PrivateKey init
let privateKey = Secp256k1PrivateKey.init(privKey: [0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0xf4,0x27,0x86,0xb5,0xdd,0x7b,0x76,0xba,0xea,0x42,0xa9,0xaa,0x60,0xff,0x4c,0x31,0x23,0xfa,0xf0,0x9b,0x8a])

//PublicKey init
let publicKey = Secp256k1PublicKey.init(pubKey: [0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x6c,0xd0,0x7b,0xd5,0xa3,0x85,0x6f,0x92,0xe7,0xbc,0x15,0xf3,0x40,0x8a,0xa5,0x4f,0x6c,0x3c,0x11,0x55,0x25,0x37,0x48,0xc9,0x93,0x0d,0x7a,0x18,0x4b,0x29,0x30,0xde,0xcd,0xbf,0xb3,0x94,0x4c,0x7f,0xdf,0xd2,0xda,0x51,0xcd,0x87,0xb5,0x00,0x8a,0x15,0xc5,0x16,0x1c,0x73,0xca])

let message_string = "hello"
let message_bytes: [UInt8] = Array(message_string.utf8)

let signer = Signer(context: context, privateKey: privateKey)

do {
    let signature = try signer.sign(data: message_bytes)
    let verif = try context.verify(signature: signature, data: message_bytes, publicKey: publicKey)
    print(verif)
}
catch {
    print("Verification failed..")
}

I always get "Verification failed..." Any idea what I'm making wrong ? Thanks!


Solution

  • Adding an answer based on our discussion above.

    Yes, you're exactly right.

    secp256r1 is a curve defined as:

    y^2 = x^3-3x+41058363725152142129326129780047268409114441015993725554835256314039467401291

    These constants, come from our friends at the NSA.

    secp256k1 on the other hand is a curve defined by the equation:

    y^2 = x^3+0x+7

    There may be some cross over with regard to x,y co-ordindates that satisfy both of the curve equations, however, with regard to signature processes above, the public keys are not interchangeable with regard to the signing context.

    Remember that private keys in ECC are simply 256-bit numbers, however each curve has it's own defined generator point G, which must be scalar multiplied by the private key to obtain the public key (which is simply a point on the curve itself).

    So, you just need to define the private key as a 256-bit number, and multiply this by the y^2 = x^3+0x+7 curves generator point, 02 79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798.

    By the way, the above is the raw math required to find the public key, in your sawtooth SDK, you can just use this method to derive the public key from the private key.