简体   繁体   中英

Golang curve25519 pubkey generator

I'm trying to implement the curve25519 algo for pubkey generation. But I got stuck on how to generate pubkey from sha256 encoded string in Go?

I have no problems with generation pubkey from sha256 encoded string via Python:

import hashlib
import x25519

example_string = 'kerielle'

sha = hashlib.sha256(example_string.encode()).hexdigest()
hash_bytes = bytes.fromhex(sha)
public_key = x25519.scalar_base_mult(hash_bytes)
hex_res = public_key.hex()

print(hex_res)
>>> 0fa065fcaedecef9aebb5c79ea1c613e82bc5534c4b139d71f3a1cb0cb956652

But how to do the same in Go? Here basic example:

var publicKey [32]byte
privateKey := (*[32]byte)(bytes.Repeat([]byte("1"), 32))
curve25519.ScalarBaseMult(&publicKey, privateKey)

fmt.Printf("%x\n", publicKey)
>>> 04f5f29162c31a8defa18e6e742224ee806fc1718a278be859ba5620402b8f3a

This simply replicates the result of the Python code sample while also taking into account guidance from the curve25519.ScalarBaseMult() documentation :

It is recommended to use the X25519 function with Basepoint instead, as copying into fixed size arrays can lead to unexpected bugs.

package main

import (
    "crypto/sha256"
    "fmt"
    "log"

    "golang.org/x/crypto/curve25519"
)

func main() {
    example_string := "kerielle"
    hash := sha256.Sum256([]byte(example_string))
    publicKey, err := curve25519.X25519(hash[:], curve25519.Basepoint)
    if err != nil {
        log.Fatalf("curve25519.X25519() failed: %v", err)
    }
    fmt.Printf("%x\n", publicKey)
}

Output:

0fa065fcaedecef9aebb5c79ea1c613e82bc5534c4b139d71f3a1cb0cb956652

Go Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM