github.com/hellobchain/newcryptosm@v0.0.0-20221019060107-edb949a317e9/x509/pkcs1.go (about)

     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  	"math/big"
    12  )
    13  
    14  // pkcs1PrivateKey is a structure which mirrors the PKCS#1 ASN.1 for an RSA private key.
    15  type pkcs1PrivateKey struct {
    16  	Version int
    17  	N       *big.Int
    18  	E       int
    19  	D       *big.Int
    20  	P       *big.Int
    21  	Q       *big.Int
    22  	// We ignore these values, if present, because rsa will calculate them.
    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  // ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form.
    45  func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error) {
    46  	var priv pkcs1PrivateKey
    47  	rest, err := asn1.Unmarshal(der, &priv)
    48  	if len(rest) > 0 {
    49  		return nil, asn1.SyntaxError{Msg: "trailing data"}
    50  	}
    51  	if err != nil {
    52  		if _, err := asn1.Unmarshal(der, &ecPrivateKey{}); err == nil {
    53  			return nil, errors.New("x509: failed to parse private key (use ParseECPrivateKey instead for this key format)")
    54  		}
    55  		if _, err := asn1.Unmarshal(der, &pkcs8{}); err == nil {
    56  			return nil, errors.New("x509: failed to parse private key (use ParsePKCS8PrivateKey instead for this key format)")
    57  		}
    58  		return nil, err
    59  	}
    60  
    61  	if priv.Version > 1 {
    62  		return nil, errors.New("x509: unsupported private key version")
    63  	}
    64  
    65  	if priv.N.Sign() <= 0 || priv.D.Sign() <= 0 || priv.P.Sign() <= 0 || priv.Q.Sign() <= 0 {
    66  		return nil, errors.New("x509: private key contains zero or negative value")
    67  	}
    68  
    69  	key := new(rsa.PrivateKey)
    70  	key.PublicKey = rsa.PublicKey{
    71  		E: priv.E,
    72  		N: priv.N,
    73  	}
    74  
    75  	key.D = priv.D
    76  	key.Primes = make([]*big.Int, 2+len(priv.AdditionalPrimes))
    77  	key.Primes[0] = priv.P
    78  	key.Primes[1] = priv.Q
    79  	for i, a := range priv.AdditionalPrimes {
    80  		if a.Prime.Sign() <= 0 {
    81  			return nil, errors.New("x509: private key contains zero or negative prime")
    82  		}
    83  		key.Primes[i+2] = a.Prime
    84  		// We ignore the other two values because rsa will calculate
    85  		// them as needed.
    86  	}
    87  
    88  	err = key.Validate()
    89  	if err != nil {
    90  		return nil, err
    91  	}
    92  	key.Precompute()
    93  
    94  	return key, nil
    95  }
    96  
    97  // MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.
    98  func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
    99  	key.Precompute()
   100  
   101  	version := 0
   102  	if len(key.Primes) > 2 {
   103  		version = 1
   104  	}
   105  
   106  	priv := pkcs1PrivateKey{
   107  		Version: version,
   108  		N:       key.N,
   109  		E:       key.PublicKey.E,
   110  		D:       key.D,
   111  		P:       key.Primes[0],
   112  		Q:       key.Primes[1],
   113  		Dp:      key.Precomputed.Dp,
   114  		Dq:      key.Precomputed.Dq,
   115  		Qinv:    key.Precomputed.Qinv,
   116  	}
   117  
   118  	priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues))
   119  	for i, values := range key.Precomputed.CRTValues {
   120  		priv.AdditionalPrimes[i].Prime = key.Primes[2+i]
   121  		priv.AdditionalPrimes[i].Exp = values.Exp
   122  		priv.AdditionalPrimes[i].Coeff = values.Coeff
   123  	}
   124  
   125  	b, _ := asn1.Marshal(priv)
   126  	return b
   127  }
   128  
   129  // ParsePKCS1PublicKey parses a PKCS#1 public key in ASN.1 DER form.
   130  func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error) {
   131  	var pub pkcs1PublicKey
   132  	rest, err := asn1.Unmarshal(der, &pub)
   133  	if err != nil {
   134  		return nil, err
   135  	}
   136  	if len(rest) > 0 {
   137  		return nil, asn1.SyntaxError{Msg: "trailing data"}
   138  	}
   139  
   140  	if pub.N.Sign() <= 0 || pub.E <= 0 {
   141  		return nil, errors.New("x509: public key contains zero or negative value")
   142  	}
   143  	if pub.E > 1<<31-1 {
   144  		return nil, errors.New("x509: public key contains large public exponent")
   145  	}
   146  
   147  	return &rsa.PublicKey{
   148  		E: pub.E,
   149  		N: pub.N,
   150  	}, nil
   151  }
   152  
   153  // MarshalPKCS1PublicKey converts an RSA public key to PKCS#1, ASN.1 DER form.
   154  func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte {
   155  	derBytes, _ := asn1.Marshal(pkcs1PublicKey{
   156  		N: key.N,
   157  		E: key.E,
   158  	})
   159  	return derBytes
   160  }