Created
June 6, 2021 19:55
-
-
Save sdorra/431dc55c8ce993be62ed7661d7374d58 to your computer and use it in GitHub Desktop.
ecdsa: sign in go, verify in node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
openssl ecparam -name prime256v1 -genkey -noout -out private.pem | |
openssl ec -in private.pem -pubout -out public.pem |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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