package main import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/asn1" "encoding/gob" "encoding/pem" "os" ) // TicketKeysGenerator 创建 ticket 密钥 type TicketKeysGenerator struct{} func (g *TicketKeysGenerator) Generate() (err error) { defer func() { if recovered := recover(); recovered != nil { err = recovered.(error) } }() reader := rand.Reader bitSize := 2048 key, err := rsa.GenerateKey(reader, bitSize) g.checkError(err) publicKey := key.PublicKey g.saveGobKey("private.key", key) g.savePEMKey("private.pem", key) g.saveGobKey("public.key", publicKey) g.savePublicPEMKey("public.pem", publicKey) return } func (g *TicketKeysGenerator) saveGobKey(fileName string, key interface{}) { outFile, err := os.Create(fileName) g.checkError(err) defer outFile.Close() encoder := gob.NewEncoder(outFile) err = encoder.Encode(key) g.checkError(err) } func (g *TicketKeysGenerator) savePEMKey(fileName string, key *rsa.PrivateKey) { outFile, err := os.Create(fileName) g.checkError(err) defer outFile.Close() var privateKey = &pem.Block{ Type: "PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key), } err = pem.Encode(outFile, privateKey) g.checkError(err) } func (g *TicketKeysGenerator) savePublicPEMKey(fileName string, pubkey rsa.PublicKey) { asn1Bytes, err := asn1.Marshal(pubkey) g.checkError(err) var pemkey = &pem.Block{ Type: "PUBLIC KEY", Bytes: asn1Bytes, } pemfile, err := os.Create(fileName) g.checkError(err) defer pemfile.Close() err = pem.Encode(pemfile, pemkey) g.checkError(err) } func (g *TicketKeysGenerator) checkError(err error) { if err != nil { panic(err) } }