github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/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  /*
     8  x509/pkcs1.go PKCS#1标准的DER字节数组与RSA公私钥之间相互转换
     9  */
    10  
    11  import (
    12  	"crypto/rsa"
    13  	"encoding/asn1"
    14  	"errors"
    15  	"math/big"
    16  )
    17  
    18  // pkcs1PrivateKey is a structure which mirrors the PKCS #1 ASN.1 for an RSA private key.
    19  type pkcs1PrivateKey struct {
    20  	Version int
    21  	N       *big.Int
    22  	E       int
    23  	D       *big.Int
    24  	P       *big.Int
    25  	Q       *big.Int
    26  	// We ignore these values, if present, because rsa will calculate them.
    27  	Dp   *big.Int `asn1:"optional"`
    28  	Dq   *big.Int `asn1:"optional"`
    29  	Qinv *big.Int `asn1:"optional"`
    30  
    31  	AdditionalPrimes []pkcs1AdditionalRSAPrime `asn1:"optional,omitempty"`
    32  }
    33  
    34  type pkcs1AdditionalRSAPrime struct {
    35  	Prime *big.Int
    36  
    37  	// We ignore these values because rsa will calculate them.
    38  	Exp   *big.Int
    39  	Coeff *big.Int
    40  }
    41  
    42  // pkcs1PublicKey reflects the ASN.1 structure of a PKCS #1 public key.
    43  type pkcs1PublicKey struct {
    44  	N *big.Int
    45  	E int
    46  }
    47  
    48  // ParsePKCS1PrivateKey 将PKCS #1, ASN.1 DER格式字节数组转为RSA私钥
    49  // ParsePKCS1PrivateKey parses an RSA private key in PKCS #1, ASN.1 DER form.
    50  //
    51  // This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY".
    52  func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error) {
    53  	var priv pkcs1PrivateKey
    54  	rest, err := asn1.Unmarshal(der, &priv)
    55  	if len(rest) > 0 {
    56  		return nil, asn1.SyntaxError{Msg: "trailing data"}
    57  	}
    58  	if err != nil {
    59  		if _, err := asn1.Unmarshal(der, &ecPrivateKey{}); err == nil {
    60  			return nil, errors.New("x509: failed to parse private key (use ParseECPrivateKey instead for this key format)")
    61  		}
    62  		if _, err := asn1.Unmarshal(der, &pkcs8{}); err == nil {
    63  			return nil, errors.New("x509: failed to parse private key (use ParsePKCS8PrivateKey instead for this key format)")
    64  		}
    65  		return nil, err
    66  	}
    67  
    68  	if priv.Version > 1 {
    69  		return nil, errors.New("x509: unsupported private key version")
    70  	}
    71  
    72  	if priv.N.Sign() <= 0 || priv.D.Sign() <= 0 || priv.P.Sign() <= 0 || priv.Q.Sign() <= 0 {
    73  		return nil, errors.New("x509: private key contains zero or negative value")
    74  	}
    75  
    76  	key := new(rsa.PrivateKey)
    77  	key.PublicKey = rsa.PublicKey{
    78  		E: priv.E,
    79  		N: priv.N,
    80  	}
    81  
    82  	key.D = priv.D
    83  	key.Primes = make([]*big.Int, 2+len(priv.AdditionalPrimes))
    84  	key.Primes[0] = priv.P
    85  	key.Primes[1] = priv.Q
    86  	for i, a := range priv.AdditionalPrimes {
    87  		if a.Prime.Sign() <= 0 {
    88  			return nil, errors.New("x509: private key contains zero or negative prime")
    89  		}
    90  		key.Primes[i+2] = a.Prime
    91  		// We ignore the other two values because rsa will calculate
    92  		// them as needed.
    93  	}
    94  
    95  	err = key.Validate()
    96  	if err != nil {
    97  		return nil, err
    98  	}
    99  	key.Precompute()
   100  
   101  	return key, nil
   102  }
   103  
   104  // MarshalPKCS1PrivateKey 将RSA私钥转为PKCS #1, ASN.1 DER格式字节数组
   105  // MarshalPKCS1PrivateKey converts an RSA private key to PKCS #1, ASN.1 DER form.
   106  //
   107  // This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY".
   108  // For a more flexible key format which is not RSA specific, use
   109  // MarshalPKCS8PrivateKey.
   110  func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
   111  	key.Precompute()
   112  
   113  	version := 0
   114  	if len(key.Primes) > 2 {
   115  		version = 1
   116  	}
   117  
   118  	priv := pkcs1PrivateKey{
   119  		Version: version,
   120  		N:       key.N,
   121  		E:       key.PublicKey.E,
   122  		D:       key.D,
   123  		P:       key.Primes[0],
   124  		Q:       key.Primes[1],
   125  		Dp:      key.Precomputed.Dp,
   126  		Dq:      key.Precomputed.Dq,
   127  		Qinv:    key.Precomputed.Qinv,
   128  	}
   129  
   130  	priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues))
   131  	for i, values := range key.Precomputed.CRTValues {
   132  		priv.AdditionalPrimes[i].Prime = key.Primes[2+i]
   133  		priv.AdditionalPrimes[i].Exp = values.Exp
   134  		priv.AdditionalPrimes[i].Coeff = values.Coeff
   135  	}
   136  
   137  	b, _ := asn1.Marshal(priv)
   138  	return b
   139  }
   140  
   141  // ParsePKCS1PublicKey 将PKCS #1, ASN.1 DER字节数组转为RSA公钥
   142  // ParsePKCS1PublicKey parses an RSA public key in PKCS #1, ASN.1 DER form.
   143  //
   144  // This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".
   145  func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error) {
   146  	var pub pkcs1PublicKey
   147  	rest, err := asn1.Unmarshal(der, &pub)
   148  	if err != nil {
   149  		if _, err := asn1.Unmarshal(der, &publicKeyInfo{}); err == nil {
   150  			return nil, errors.New("x509: failed to parse public key (use ParsePKIXPublicKey instead for this key format)")
   151  		}
   152  		return nil, err
   153  	}
   154  	if len(rest) > 0 {
   155  		return nil, asn1.SyntaxError{Msg: "trailing data"}
   156  	}
   157  
   158  	if pub.N.Sign() <= 0 || pub.E <= 0 {
   159  		return nil, errors.New("x509: public key contains zero or negative value")
   160  	}
   161  	if pub.E > 1<<31-1 {
   162  		return nil, errors.New("x509: public key contains large public exponent")
   163  	}
   164  
   165  	return &rsa.PublicKey{
   166  		E: pub.E,
   167  		N: pub.N,
   168  	}, nil
   169  }
   170  
   171  // MarshalPKCS1PublicKey 将RSA公钥转为PKCS #1, ASN.1 DER字节数组
   172  // MarshalPKCS1PublicKey converts an RSA public key to PKCS #1, ASN.1 DER form.
   173  //
   174  // This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".
   175  func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte {
   176  	derBytes, _ := asn1.Marshal(pkcs1PublicKey{
   177  		N: key.N,
   178  		E: key.E,
   179  	})
   180  	return derBytes
   181  }