0

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
  • It's not really your question, but you could just write `hash_bytes = hashlib.sha256(....).digest()`. Calling `digest()` gives you the result as a byte string. – Frank Yellin Jan 16 '22 at 04:24
  • Why do you think your code doesn't work? – Frank Yellin Jan 16 '22 at 04:25
  • Hi. Thanks for reply. No, I do not think that my code does not work. I just want to get correct golang algo which generates from example string `kerielle` following pubkey `0fa065fcaedecef9aebb5c79ea1c613e82bc5534c4b139d71f3a1cb0cb956652` – Billie Jean Jan 16 '22 at 04:32
  • Sorry. I don't know golang. I only know that Python gives the same result when you call `x25519.scalar_base_mult(b'1' * 32).hex()`. I looked at https://pkg.go.dev/crypto/sha256 and it has a function for sha256() and some sample code. – Frank Yellin Jan 16 '22 at 04:36
  • Thanks Frank Yellin. It works for me! – Billie Jean Jan 16 '22 at 07:08

1 Answers1

3

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

chuckx
  • 6,484
  • 1
  • 22
  • 23