phoreproject / bls

Go implementation of the BLS12-381 pairing
Apache License 2.0
89 stars 31 forks source link

Is there a easy understand example code how to implement ECDH on bls g1 ? #9

Closed zsp042 closed 5 years ago

zsp042 commented 5 years ago

I am an application programmer, not very familiar with encryption algorithms. I want to negotiate the key based on ECDH, but I don't know how to implement it based on BLS.

Is there a easy understand example code how to implement ECDH on bls g1 ?

just like this https://github.com/andreacorbellini/ecc/blob/master/scripts/ecdhe.py

# Alice generates her own keypair.
alice_private_key, alice_public_key = make_keypair()
print("Alice's private key:", hex(alice_private_key))
print("Alice's public key: (0x{:x}, 0x{:x})".format(*alice_public_key))

# Bob generates his own key pair.
bob_private_key, bob_public_key = make_keypair()
print("Bob's private key:", hex(bob_private_key))
print("Bob's public key: (0x{:x}, 0x{:x})".format(*bob_public_key))

# Alice and Bob exchange their public keys and calculate the shared secret.
s1 = scalar_mult(alice_private_key, bob_public_key)
s2 = scalar_mult(bob_private_key, alice_public_key)
assert s1 == s2

print('Shared secret: (0x{:x}, 0x{:x})'.format(*s1))
meyer9 commented 5 years ago
package main

import (
    "crypto/rand"
    "fmt"

    "github.com/phoreproject/bls"
)

func main() {
    alicePrivateKey, err := bls.RandFR(rand.Reader)
    if err != nil {
        panic(err)
    }

    alicePublicKey := bls.G1AffineOne.MulFR(alicePrivateKey.ToRepr())

    bobPrivateKey, err := bls.RandFR(rand.Reader)
    if err != nil {
        panic(err)
    }

    bobPublicKey := bls.G1AffineOne.MulFR(bobPrivateKey.ToRepr())

    s1 := bobPublicKey.MulFR(alicePrivateKey.ToRepr()).ToAffine()

    s2 := alicePublicKey.MulFR(bobPrivateKey.ToRepr()).ToAffine()

    if !s1.Equals(s2) {
        panic("shared secret should be the same")
    }

    fmt.Printf("shared secret: %s\n", s1)
}

I think that should work, but you should compare it with other implementations and probably not use it in production.

zsp042 commented 5 years ago

thanks