github.com/haraldrudell/parl@v0.4.176/parlca/private-key.go (about) 1 /* 2 © 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package parlca 7 8 import ( 9 "crypto/x509" 10 "os" 11 12 "github.com/haraldrudell/parl" 13 "github.com/haraldrudell/parl/perrors" 14 "github.com/haraldrudell/parl/punix" 15 ) 16 17 func NewPrivateKey(algo x509.PublicKeyAlgorithm) (privateKey parl.PrivateKey, err error) { 18 switch algo { 19 case x509.Ed25519: 20 privateKey, err = NewEd25519() 21 case x509.RSA: 22 privateKey, err = NewRsa() 23 case x509.ECDSA: 24 privateKey, err = NewEcdsa() 25 default: 26 err = x509.ErrUnsupportedAlgorithm 27 } 28 return 29 } 30 31 func NewPrivateKey2(algo x509.PublicKeyAlgorithm, privateKeyDer parl.PrivateKeyDer) (privateKey parl.PrivateKey, err error) { 32 switch algo { 33 case x509.Ed25519: 34 privateKey, err = NewEd25519() 35 case x509.RSA: 36 privateKey, err = NewRsa() 37 case x509.ECDSA: 38 privateKey, err = NewEcdsa() 39 default: 40 err = x509.ErrUnsupportedAlgorithm 41 } 42 return 43 } 44 45 func LoadPrivateKeyFromDer(filename string, algo x509.PublicKeyAlgorithm, allowNotFound ...bool) (privateKey parl.PrivateKey, err error) { 46 allowNotFound0 := len(allowNotFound) > 0 && allowNotFound[0] 47 var privateKeyDer parl.PrivateKeyDer 48 if privateKeyDer, err = ReadFile(filename, allowNotFound0); err != nil { 49 return // file read error return 50 } else if allowNotFound0 && privateKeyDer == nil { 51 return 52 } 53 if privateKey, err = NewPrivateKey2(algo, privateKeyDer); err != nil { 54 return 55 } 56 // TODO 220624 validate privateKey? 57 return 58 } 59 60 func LoadFromPem(filename string, allowNotFound ...bool) ( 61 certificate parl.Certificate, privateKey parl.PrivateKey, publicKey parl.PublicKey, 62 err error) { 63 allowNotFound0 := len(allowNotFound) > 0 && allowNotFound[0] 64 var pemBytes parl.PemBytes 65 if pemBytes, err = ReadFile(filename, allowNotFound0); err != nil { 66 return // file read error return 67 } else if allowNotFound0 && pemBytes == nil { 68 return 69 } 70 // TODO 220624 validate privateKey? 71 return ParsePEM(pemBytes) 72 } 73 74 func ReadFile(filename string, allowNotFound bool) (byts []byte, err error) { 75 if byts, err = os.ReadFile(filename); err != nil { 76 if allowNotFound && punix.IsENOENT(err) { 77 err = nil 78 return // cert file does not exist: byts == nil, err == nil 79 } 80 perrors.IsPF(&err, "os.ReadFile %w", err) 81 } 82 return 83 }