Pebble Coding

ソフトウェアエンジニアによるIT技術、数学の備忘録

go 言語 でed25519ライブラリを使う

go の標準ライブラリにはed25519は含まれない($ go list std | grep cryptoで確認できます。)ため、 以下のライブラリを使います。

github.com

以下のコマンドでインストールします。

$ go get -u golang.org/x/crypto/ed25519

a.goというファイル名で以下を作成します。

package main
import "fmt"
import "golang.org/x/crypto/ed25519"
import "encoding/hex"

type zeroReader struct{}

func (zeroReader) Read(buf []byte) (int, error) {
    for i := range buf {
        buf[i] = 0
    }
    return len(buf), nil
}

func main() {
    var zero zeroReader
    pub, priv, err := ed25519.GenerateKey(zero)
    if err == nil {
        fmt.Print("GenerateKey success\n")
    } else {
        fmt.Print("GenerateKey error\n")
    }
    fmt.Print("pub:\n")
    fmt.Print(hex.Dump(pub))
    fmt.Print("priv:\n")
    fmt.Print(hex.Dump(priv))
    message := []byte("Hello, world!")
    signature := ed25519.Sign(priv, message)
    result := ed25519.Verify(pub, message, signature)
    if result {
        fmt.Print("Verify success\n")
    } else {
        fmt.Print("Verify error\n")
    }
}
~$ go run a.go
GenerateKey success
pub:
00000000  3b 6a 27 bc ce b6 a4 2d  62 a3 a8 d0 2a 6f 0d 73  |;j'....-b...*o.s|
00000010  65 32 15 77 1d e2 43 a6  3a c0 48 a1 8b 59 da 29  |e2.w..C.:.H..Y.)|
priv:
00000000  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000010  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000020  3b 6a 27 bc ce b6 a4 2d  62 a3 a8 d0 2a 6f 0d 73  |;j'....-b...*o.s|
00000030  65 32 15 77 1d e2 43 a6  3a c0 48 a1 8b 59 da 29  |e2.w..C.:.H..Y.)|
Verify success