Merge pull request #62 from cubemaze/cmd_x25519

feat: add command for generating a key pair for x25519 key exchange.
This commit is contained in:
Yuzuki 2023-06-02 08:27:03 +08:00 committed by GitHub
commit 5379a5a668
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

52
cmd/x25519.go Normal file
View File

@ -0,0 +1,52 @@
package cmd
import (
"crypto/rand"
"encoding/base64"
"fmt"
"github.com/spf13/cobra"
"golang.org/x/crypto/curve25519"
)
var x25519Command = cobra.Command{
Use: "x25519",
Short: "Generate key pair for x25519 key exchange",
Run: func(cmd *cobra.Command, args []string) {
executeX25519()
},
}
func init() {
command.AddCommand(&x25519Command)
}
func executeX25519() {
var output string
var err error
var privateKey []byte
var publicKey []byte
privateKey = make([]byte, curve25519.ScalarSize)
if _, err = rand.Read(privateKey); err != nil {
output = err.Error()
goto out
}
// Modify random bytes using algorithm described at:
// https://cr.yp.to/ecdh.html.
privateKey[0] &= 248
privateKey[31] &= 127
privateKey[31] |= 64
if publicKey, err = curve25519.X25519(privateKey, curve25519.Basepoint); err != nil {
output = err.Error()
goto out
}
output = fmt.Sprintf("Private key: %v\nPublic key: %v",
base64.RawURLEncoding.EncodeToString(privateKey),
base64.RawURLEncoding.EncodeToString(publicKey))
out:
fmt.Println(output)
}