sec1.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package x509
  5. import (
  6. "crypto/ecdsa"
  7. "crypto/elliptic"
  8. "errors"
  9. "fmt"
  10. "math/big"
  11. "github.com/google/certificate-transparency-go/asn1"
  12. )
  13. const ecPrivKeyVersion = 1
  14. // ecPrivateKey reflects an ASN.1 Elliptic Curve Private Key Structure.
  15. // References:
  16. //
  17. // RFC 5915
  18. // SEC1 - http://www.secg.org/sec1-v2.pdf
  19. //
  20. // Per RFC 5915 the NamedCurveOID is marked as ASN.1 OPTIONAL, however in
  21. // most cases it is not.
  22. type ecPrivateKey struct {
  23. Version int
  24. PrivateKey []byte
  25. NamedCurveOID asn1.ObjectIdentifier `asn1:"optional,explicit,tag:0"`
  26. PublicKey asn1.BitString `asn1:"optional,explicit,tag:1"`
  27. }
  28. // ParseECPrivateKey parses an EC private key in SEC 1, ASN.1 DER form.
  29. //
  30. // This kind of key is commonly encoded in PEM blocks of type "EC PRIVATE KEY".
  31. func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error) {
  32. return parseECPrivateKey(nil, der)
  33. }
  34. // MarshalECPrivateKey converts an EC private key to SEC 1, ASN.1 DER form.
  35. //
  36. // This kind of key is commonly encoded in PEM blocks of type "EC PRIVATE KEY".
  37. // For a more flexible key format which is not EC specific, use
  38. // MarshalPKCS8PrivateKey.
  39. func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error) {
  40. oid, ok := OIDFromNamedCurve(key.Curve)
  41. if !ok {
  42. return nil, errors.New("x509: unknown elliptic curve")
  43. }
  44. return marshalECPrivateKeyWithOID(key, oid)
  45. }
  46. // marshalECPrivateKey marshals an EC private key into ASN.1, DER format and
  47. // sets the curve ID to the given OID, or omits it if OID is nil.
  48. func marshalECPrivateKeyWithOID(key *ecdsa.PrivateKey, oid asn1.ObjectIdentifier) ([]byte, error) {
  49. privateKeyBytes := key.D.Bytes()
  50. paddedPrivateKey := make([]byte, (key.Curve.Params().N.BitLen()+7)/8)
  51. copy(paddedPrivateKey[len(paddedPrivateKey)-len(privateKeyBytes):], privateKeyBytes)
  52. return asn1.Marshal(ecPrivateKey{
  53. Version: 1,
  54. PrivateKey: paddedPrivateKey,
  55. NamedCurveOID: oid,
  56. PublicKey: asn1.BitString{Bytes: elliptic.Marshal(key.Curve, key.X, key.Y)},
  57. })
  58. }
  59. // parseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.
  60. // The OID for the named curve may be provided from another source (such as
  61. // the PKCS8 container) - if it is provided then use this instead of the OID
  62. // that may exist in the EC private key structure.
  63. func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error) {
  64. var privKey ecPrivateKey
  65. if _, err := asn1.Unmarshal(der, &privKey); err != nil {
  66. if _, err := asn1.Unmarshal(der, &pkcs8{}); err == nil {
  67. return nil, errors.New("x509: failed to parse private key (use ParsePKCS8PrivateKey instead for this key format)")
  68. }
  69. if _, err := asn1.Unmarshal(der, &pkcs1PrivateKey{}); err == nil {
  70. return nil, errors.New("x509: failed to parse private key (use ParsePKCS1PrivateKey instead for this key format)")
  71. }
  72. return nil, errors.New("x509: failed to parse EC private key: " + err.Error())
  73. }
  74. if privKey.Version != ecPrivKeyVersion {
  75. return nil, fmt.Errorf("x509: unknown EC private key version %d", privKey.Version)
  76. }
  77. var nfe NonFatalErrors
  78. var curve elliptic.Curve
  79. if namedCurveOID != nil {
  80. curve = namedCurveFromOID(*namedCurveOID, &nfe)
  81. } else {
  82. curve = namedCurveFromOID(privKey.NamedCurveOID, &nfe)
  83. }
  84. if curve == nil {
  85. return nil, errors.New("x509: unknown elliptic curve")
  86. }
  87. k := new(big.Int).SetBytes(privKey.PrivateKey)
  88. curveOrder := curve.Params().N
  89. if k.Cmp(curveOrder) >= 0 {
  90. return nil, errors.New("x509: invalid elliptic curve private key value")
  91. }
  92. priv := new(ecdsa.PrivateKey)
  93. priv.Curve = curve
  94. priv.D = k
  95. privateKey := make([]byte, (curveOrder.BitLen()+7)/8)
  96. // Some private keys have leading zero padding. This is invalid
  97. // according to [SEC1], but this code will ignore it.
  98. for len(privKey.PrivateKey) > len(privateKey) {
  99. if privKey.PrivateKey[0] != 0 {
  100. return nil, errors.New("x509: invalid private key length")
  101. }
  102. privKey.PrivateKey = privKey.PrivateKey[1:]
  103. }
  104. // Some private keys remove all leading zeros, this is also invalid
  105. // according to [SEC1] but since OpenSSL used to do this, we ignore
  106. // this too.
  107. copy(privateKey[len(privateKey)-len(privKey.PrivateKey):], privKey.PrivateKey)
  108. priv.X, priv.Y = curve.ScalarBaseMult(privateKey)
  109. return priv, nil
  110. }