github.com/pavlo67/common@v0.5.3/common/encrlib/rsa.go (about) 1 package encrlib 2 3 import ( 4 "crypto/rand" 5 "crypto/rsa" 6 "encoding/json" 7 "io/ioutil" 8 "os" 9 10 "github.com/pkg/errors" 11 ) 12 13 const onNewRSAPrivateKey = "on encrlib.NewRSAPrivateKey()" 14 15 func NewRSAPrivateKey(pathToStore string) (*rsa.PrivateKey, error) { 16 if pathToStore != "" { 17 if _, err := os.Stat(pathToStore); !os.IsNotExist(err) { 18 keyJSON, err := ioutil.ReadFile(pathToStore) 19 if err != nil { 20 return nil, errors.Wrapf(err, onNewRSAPrivateKey+": can't read file (%s)", pathToStore) 21 } 22 23 var privateKey rsa.PrivateKey 24 err = json.Unmarshal(keyJSON, &privateKey) 25 if err != nil { 26 return nil, errors.Wrapf(err, onNewRSAPrivateKey+": can't .json.Unmarshal file (%s --> %s)", pathToStore, keyJSON) 27 } 28 29 return &privateKey, nil 30 } 31 } 32 33 privateKey, err := rsa.GenerateKey(rand.Reader, 2048) 34 if err != nil { 35 return nil, errors.Wrap(err, onNewRSAPrivateKey) 36 } 37 38 if privateKey == nil { 39 return nil, errors.New(onNewRSAPrivateKey + ": nil key was generated") 40 } 41 42 if pathToStore != "" { 43 keyJSON, err := json.Marshal(privateKey) 44 if err != nil { 45 return nil, errors.Wrapf(err, onNewRSAPrivateKey+": can't .json.Marshal key (%#v)", privateKey) 46 } 47 48 if err = ioutil.WriteFile(pathToStore, keyJSON, 0644); err != nil { 49 return nil, errors.Wrapf(err, onNewRSAPrivateKey+": can't write file (%s)", pathToStore) 50 } 51 } 52 53 return privateKey, nil 54 }