github.com/haraldrudell/parl@v0.4.176/parlca/ecdsa-private.go (about) 1 /* 2 © 2022–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/ecdsa" 10 "crypto/elliptic" 11 "crypto/rand" 12 "crypto/x509" 13 "encoding/pem" 14 15 "github.com/haraldrudell/parl" 16 "github.com/haraldrudell/parl/perrors" 17 ) 18 19 type EcdsaPrivateKey struct { 20 ecdsa.PrivateKey 21 } 22 23 func NewEcdsa() (privateKey parl.PrivateKey, err error) { 24 var ecdsaPrivateKey *ecdsa.PrivateKey 25 // P-256 is 128 bit security 26 if ecdsaPrivateKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); perrors.IsPF(&err, "ecdsa.GenerateKey %w", err) { 27 return 28 } 29 privateKey = &EcdsaPrivateKey{PrivateKey: *ecdsaPrivateKey} 30 return 31 } 32 33 func (key *EcdsaPrivateKey) Algo() (algo x509.PublicKeyAlgorithm) { 34 return x509.ECDSA 35 } 36 37 func (key *EcdsaPrivateKey) DER() (bytes parl.PrivateKeyDer, err error) { 38 if bytes, err = x509.MarshalPKCS8PrivateKey(&key.PrivateKey); err != nil { 39 err = perrors.Errorf("x509.MarshalPKCS8PrivateKey: '%w'", err) 40 } 41 return 42 } 43 44 func (key *EcdsaPrivateKey) DERe() (privateKeyDer parl.PrivateKeyDer) { 45 var err error 46 if privateKeyDer, err = key.DER(); err != nil { 47 panic(err) 48 } 49 return 50 } 51 52 func (key *EcdsaPrivateKey) PEM() (pemBytes parl.PemBytes, err error) { 53 block := pem.Block{ 54 Type: pemPrivateKeyType, 55 } 56 if block.Bytes, err = key.DER(); err != nil { 57 return 58 } 59 pemBytes = append([]byte(PemText(block.Bytes)), pem.EncodeToMemory(&block)...) 60 return 61 } 62 63 func (key *EcdsaPrivateKey) PEMe() (pemBytes parl.PemBytes) { 64 var err error 65 if pemBytes, err = key.PEM(); err != nil { 66 panic(err) 67 } 68 return 69 } 70 71 func (key *EcdsaPrivateKey) PublicKey() (publicKey parl.PublicKey) { 72 return &EcdsaPublicKey{PublicKey: key.PrivateKey.PublicKey} 73 } 74 75 func (key *EcdsaPrivateKey) Validate() (err error) { 76 if key.PrivateKey.D == nil { 77 err = perrors.New("Uninitialized ecdsa private key") 78 return 79 } 80 return 81 }