Source file src/crypto/x509/pkcs1.go

     1  // Copyright 2011 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  
     5  package x509
     6  
     7  import (
     8  	"crypto/rsa"
     9  	"encoding/asn1"
    10  	"errors"
    11  	"internal/godebug"
    12  	"math/big"
    13  )
    14  
    15  // pkcs1PrivateKey is a structure which mirrors the PKCS #1 ASN.1 for an RSA private key.
    16  type pkcs1PrivateKey struct {
    17  	Version int
    18  	N       *big.Int
    19  	E       int
    20  	D       *big.Int
    21  	P       *big.Int
    22  	Q       *big.Int
    23  	Dp      *big.Int `asn1:"optional"`
    24  	Dq      *big.Int `asn1:"optional"`
    25  	Qinv    *big.Int `asn1:"optional"`
    26  
    27  	AdditionalPrimes []pkcs1AdditionalRSAPrime `asn1:"optional,omitempty"`
    28  }
    29  
    30  type pkcs1AdditionalRSAPrime struct {
    31  	Prime *big.Int
    32  
    33  	// We ignore these values because rsa will calculate them.
    34  	Exp   *big.Int
    35  	Coeff *big.Int
    36  }
    37  
    38  // pkcs1PublicKey reflects the ASN.1 structure of a PKCS #1 public key.
    39  type pkcs1PublicKey struct {
    40  	N *big.Int
    41  	E int
    42  }
    43  
    44  // x509rsacrt, if zero, makes ParsePKCS1PrivateKey ignore and recompute invalid
    45  // CRT values in the RSA private key.
    46  var x509rsacrt = godebug.New("x509rsacrt")
    47  
    48  // ParsePKCS1PrivateKey parses an [RSA] private key in PKCS #1, ASN.1 DER form.
    49  //
    50  // This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY".
    51  //
    52  // Before Go 1.24, the CRT parameters were ignored and recomputed. To restore
    53  // the old behavior, use the GODEBUG=x509rsacrt=0 environment variable.
    54  func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error) {
    55  	var priv pkcs1PrivateKey
    56  	rest, err := asn1.Unmarshal(der, &priv)
    57  	if len(rest) > 0 {
    58  		return nil, asn1.SyntaxError{Msg: "trailing data"}
    59  	}
    60  	if err != nil {
    61  		if _, err := asn1.Unmarshal(der, &ecPrivateKey{}); err == nil {
    62  			return nil, errors.New("x509: failed to parse private key (use ParseECPrivateKey instead for this key format)")
    63  		}
    64  		if _, err := asn1.Unmarshal(der, &pkcs8{}); err == nil {
    65  			return nil, errors.New("x509: failed to parse private key (use ParsePKCS8PrivateKey instead for this key format)")
    66  		}
    67  		return nil, err
    68  	}
    69  
    70  	if priv.Version > 1 {
    71  		return nil, errors.New("x509: unsupported private key version")
    72  	}
    73  
    74  	if priv.N.Sign() <= 0 || priv.D.Sign() <= 0 || priv.P.Sign() <= 0 || priv.Q.Sign() <= 0 ||
    75  		priv.Dp != nil && priv.Dp.Sign() <= 0 ||
    76  		priv.Dq != nil && priv.Dq.Sign() <= 0 ||
    77  		priv.Qinv != nil && priv.Qinv.Sign() <= 0 {
    78  		return nil, errors.New("x509: private key contains zero or negative value")
    79  	}
    80  
    81  	key := new(rsa.PrivateKey)
    82  	key.PublicKey = rsa.PublicKey{
    83  		E: priv.E,
    84  		N: priv.N,
    85  	}
    86  
    87  	key.D = priv.D
    88  	key.Primes = make([]*big.Int, 2+len(priv.AdditionalPrimes))
    89  	key.Primes[0] = priv.P
    90  	key.Primes[1] = priv.Q
    91  	key.Precomputed.Dp = priv.Dp
    92  	key.Precomputed.Dq = priv.Dq
    93  	key.Precomputed.Qinv = priv.Qinv
    94  	for i, a := range priv.AdditionalPrimes {
    95  		if a.Prime.Sign() <= 0 {
    96  			return nil, errors.New("x509: private key contains zero or negative prime")
    97  		}
    98  		key.Primes[i+2] = a.Prime
    99  		// We ignore the other two values because rsa will calculate
   100  		// them as needed.
   101  	}
   102  
   103  	key.Precompute()
   104  	if err := key.Validate(); err != nil {
   105  		// If x509rsacrt=0 is set, try dropping the CRT values and
   106  		// rerunning precomputation and key validation.
   107  		if x509rsacrt.Value() == "0" {
   108  			key.Precomputed.Dp = nil
   109  			key.Precomputed.Dq = nil
   110  			key.Precomputed.Qinv = nil
   111  			key.Precompute()
   112  			if err := key.Validate(); err == nil {
   113  				x509rsacrt.IncNonDefault()
   114  				return key, nil
   115  			}
   116  		}
   117  
   118  		return nil, err
   119  	}
   120  
   121  	return key, nil
   122  }
   123  
   124  // MarshalPKCS1PrivateKey converts an [RSA] private key to PKCS #1, ASN.1 DER form.
   125  //
   126  // This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY".
   127  // For a more flexible key format which is not [RSA] specific, use
   128  // [MarshalPKCS8PrivateKey].
   129  //
   130  // The key must have passed validation by calling [rsa.PrivateKey.Validate]
   131  // first. MarshalPKCS1PrivateKey calls [rsa.PrivateKey.Precompute], which may
   132  // modify the key if not already precomputed.
   133  func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
   134  	key.Precompute()
   135  
   136  	version := 0
   137  	if len(key.Primes) > 2 {
   138  		version = 1
   139  	}
   140  
   141  	priv := pkcs1PrivateKey{
   142  		Version: version,
   143  		N:       key.N,
   144  		E:       key.PublicKey.E,
   145  		D:       key.D,
   146  		P:       key.Primes[0],
   147  		Q:       key.Primes[1],
   148  		Dp:      key.Precomputed.Dp,
   149  		Dq:      key.Precomputed.Dq,
   150  		Qinv:    key.Precomputed.Qinv,
   151  	}
   152  
   153  	priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues))
   154  	for i, values := range key.Precomputed.CRTValues {
   155  		priv.AdditionalPrimes[i].Prime = key.Primes[2+i]
   156  		priv.AdditionalPrimes[i].Exp = values.Exp
   157  		priv.AdditionalPrimes[i].Coeff = values.Coeff
   158  	}
   159  
   160  	b, _ := asn1.Marshal(priv)
   161  	return b
   162  }
   163  
   164  // ParsePKCS1PublicKey parses an [RSA] public key in PKCS #1, ASN.1 DER form.
   165  //
   166  // This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".
   167  func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error) {
   168  	var pub pkcs1PublicKey
   169  	rest, err := asn1.Unmarshal(der, &pub)
   170  	if err != nil {
   171  		if _, err := asn1.Unmarshal(der, &publicKeyInfo{}); err == nil {
   172  			return nil, errors.New("x509: failed to parse public key (use ParsePKIXPublicKey instead for this key format)")
   173  		}
   174  		return nil, err
   175  	}
   176  	if len(rest) > 0 {
   177  		return nil, asn1.SyntaxError{Msg: "trailing data"}
   178  	}
   179  
   180  	if pub.N.Sign() <= 0 || pub.E <= 0 {
   181  		return nil, errors.New("x509: public key contains zero or negative value")
   182  	}
   183  	if pub.E > 1<<31-1 {
   184  		return nil, errors.New("x509: public key contains large public exponent")
   185  	}
   186  
   187  	return &rsa.PublicKey{
   188  		E: pub.E,
   189  		N: pub.N,
   190  	}, nil
   191  }
   192  
   193  // MarshalPKCS1PublicKey converts an [RSA] public key to PKCS #1, ASN.1 DER form.
   194  //
   195  // This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".
   196  func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte {
   197  	derBytes, _ := asn1.Marshal(pkcs1PublicKey{
   198  		N: key.N,
   199  		E: key.E,
   200  	})
   201  	return derBytes
   202  }
   203  

View as plain text