Skip to content

Instantly share code, notes, and snippets.

@sdorra
Created June 6, 2021 19:55
Show Gist options
  • Save sdorra/431dc55c8ce993be62ed7661d7374d58 to your computer and use it in GitHub Desktop.
Save sdorra/431dc55c8ce993be62ed7661d7374d58 to your computer and use it in GitHub Desktop.
ecdsa: sign in go, verify in node
openssl ecparam -name prime256v1 -genkey -noout -out private.pem
openssl ec -in private.pem -pubout -out public.pem
package main
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"log"
"os"
)
func main() {
if len(os.Args) != 2 {
log.Println("usage sign text")
}
msg := os.Args[1]
data, err := os.ReadFile("private.pem")
if err != nil {
log.Fatal("failed to reader private key", err)
}
block, _ := pem.Decode(data)
if block == nil {
log.Fatal("failed to read block from private key")
}
privateKey, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
log.Fatal("failed to parse private key", err)
}
hash := sha256.Sum256([]byte(msg))
sig, err := ecdsa.SignASN1(rand.Reader, privateKey, hash[:])
if err != nil {
panic(err)
}
signature := base64.StdEncoding.EncodeToString(sig)
fmt.Println(signature)
}
const { createVerify } = require("crypto");
const { readFileSync } = require("fs");
if (process.argv.length !== 4) {
console.log("usage verify message signature");
process.exit(2);
}
const message = process.argv[2];
const signature process.argv[3];
const publicKey = readFileSync("public.pem");
const verifier = createVerify("sha256");
verifier.update(message);
const verified = verifier.verify(publicKey, signature, "base64");
console.log(verified);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment