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.

Revisions

  1. sdorra revised this gist Jun 6, 2021. No changes.
  2. sdorra created this gist Jun 6, 2021.
    2 changes: 2 additions & 0 deletions generate-keys.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    openssl ecparam -name prime256v1 -genkey -noout -out private.pem
    openssl ec -in private.pem -pubout -out public.pem
    46 changes: 46 additions & 0 deletions sign.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    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)
    }
    17 changes: 17 additions & 0 deletions verify.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    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);