github.com/brimstone/sbuca@v0.0.0-20151202175429-8691d9eba5c5/pkix/key.go (about) 1 package pkix 2 3 import ( 4 "crypto" 5 "crypto/rand" 6 "crypto/rsa" 7 "crypto/x509" 8 "encoding/pem" 9 "errors" 10 "io/ioutil" 11 ) 12 13 type Key struct { 14 /* 15 PublicKey *crypto.PublicKey 16 PrivateKey *crypto.PrivateKey 17 */ 18 PublicKey crypto.PublicKey 19 PrivateKey *rsa.PrivateKey 20 DerBytes []byte 21 } 22 23 func NewKey() (*Key, error) { 24 privateKey, err := rsa.GenerateKey(rand.Reader, 2048) 25 if err != nil { 26 return nil, err 27 } 28 29 derBytes := x509.MarshalPKCS1PrivateKey(privateKey) 30 if derBytes == nil { 31 return nil, errors.New("marshal rsa failed") 32 } 33 34 newKey := &Key{ 35 PrivateKey: privateKey, 36 PublicKey: privateKey.Public(), 37 DerBytes: derBytes, 38 } 39 40 return newKey, nil 41 } 42 func NewKeyFromPrivateKeyPEM(pemBytes []byte) (*Key, error) { 43 // currently we only support rsa 44 45 pemBlock, _ := pem.Decode(pemBytes) 46 if pemBlock == nil { 47 return nil, errors.New("decode pem failed") 48 } 49 50 privateKey, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes) 51 if err != nil { 52 return nil, err 53 } 54 55 newKey := &Key{ 56 PrivateKey: privateKey, 57 PublicKey: privateKey.Public(), 58 DerBytes: pemBlock.Bytes, 59 } 60 61 return newKey, nil 62 } 63 func NewKeyFromPrivateKeyPEMFile(filename string) (*Key, error) { 64 65 data, err := ioutil.ReadFile(filename) 66 if err != nil { 67 return nil, err 68 } 69 70 return NewKeyFromPrivateKeyPEM(data) 71 72 } 73 func (key *Key) ToPEM() ([]byte, error) { 74 75 pemBlock := &pem.Block{ 76 Type: "RSA PRIVATE KEY", 77 Bytes: key.DerBytes, 78 } 79 pemBytes := pem.EncodeToMemory(pemBlock) 80 81 return pemBytes, nil 82 } 83 func (key *Key) ToPEMFile(filename string) error { 84 pemBytes, err := key.ToPEM() 85 if err != nil { 86 return err 87 } 88 89 return ioutil.WriteFile(filename, pemBytes, 0400) 90 }