From e9288ee253965100e54326babf4019ec4fff1097 Mon Sep 17 00:00:00 2001 From: hupeh Date: Tue, 19 Sep 2023 23:59:14 +0800 Subject: [PATCH] =?UTF-8?q?=E7=94=9F=E6=88=90=20RS256=20=E5=85=AC=E9=92=A5?= =?UTF-8?q?=E7=A7=81=E9=92=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/rs256/rs256.go | 76 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 scripts/rs256/rs256.go diff --git a/scripts/rs256/rs256.go b/scripts/rs256/rs256.go new file mode 100644 index 0000000..f8cc9cc --- /dev/null +++ b/scripts/rs256/rs256.go @@ -0,0 +1,76 @@ +package main + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/asn1" + "encoding/gob" + "encoding/pem" + "fmt" + "os" +) + +func main() { + reader := rand.Reader + bitSize := 2048 + + key, err := rsa.GenerateKey(reader, bitSize) + checkError(err) + + publicKey := key.PublicKey + + saveGobKey("private.key", key) + savePEMKey("private.pem", key) + + saveGobKey("public.key", publicKey) + savePublicPEMKey("public.pem", publicKey) +} + +func saveGobKey(fileName string, key interface{}) { + outFile, err := os.Create(fileName) + checkError(err) + defer outFile.Close() + + encoder := gob.NewEncoder(outFile) + err = encoder.Encode(key) + checkError(err) +} + +func savePEMKey(fileName string, key *rsa.PrivateKey) { + outFile, err := os.Create(fileName) + checkError(err) + defer outFile.Close() + + var privateKey = &pem.Block{ + Type: "PRIVATE KEY", + Bytes: x509.MarshalPKCS1PrivateKey(key), + } + + err = pem.Encode(outFile, privateKey) + checkError(err) +} + +func savePublicPEMKey(fileName string, pubkey rsa.PublicKey) { + asn1Bytes, err := asn1.Marshal(pubkey) + checkError(err) + + var pemkey = &pem.Block{ + Type: "PUBLIC KEY", + Bytes: asn1Bytes, + } + + pemfile, err := os.Create(fileName) + checkError(err) + defer pemfile.Close() + + err = pem.Encode(pemfile, pemkey) + checkError(err) +} + +func checkError(err error) { + if err != nil { + fmt.Println("Fatal error ", err.Error()) + os.Exit(1) + } +}