10 // pkcs1PrivateKey is a structure which mirrors the PKCS#1 ASN.1 for an RSA private key.
11 type pkcs1PrivateKey struct {
18 // We ignore these values, if present, because rsa will calculate them.
19 Dp *big.Int `asn1:"optional"`
20 Dq *big.Int `asn1:"optional"`
21 Qinv *big.Int `asn1:"optional"`
23 AdditionalPrimes []pkcs1AdditionalRSAPrime `asn1:"optional,omitempty"`
26 type pkcs1AdditionalRSAPrime struct {
29 // We ignore these values because rsa will calculate them.
34 // ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form.
35 func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error) {
36 var priv pkcs1PrivateKey
37 rest, err := asn1.Unmarshal(der, &priv)
39 return nil, asn1.SyntaxError{Msg: "trailing data"}
46 return nil, errors.New("x509: unsupported private key version")
49 if priv.N.Sign() <= 0 || priv.D.Sign() <= 0 || priv.P.Sign() <= 0 || priv.Q.Sign() <= 0 {
50 return nil, errors.New("x509: private key contains zero or negative value")
53 key := new(rsa.PrivateKey)
54 key.PublicKey = rsa.PublicKey{
60 key.Primes = make([]*big.Int, 2+len(priv.AdditionalPrimes))
61 key.Primes[0] = priv.P
62 key.Primes[1] = priv.Q
63 for i, a := range priv.AdditionalPrimes {
64 if a.Prime.Sign() <= 0 {
65 return nil, errors.New("x509: private key contains zero or negative prime")
67 key.Primes[i+2] = a.Prime
68 // We ignore the other two values because rsa will calculate
81 // MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.
82 func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
86 if len(key.Primes) > 2 {
90 priv := pkcs1PrivateKey{
97 Dp: key.Precomputed.Dp,
98 Dq: key.Precomputed.Dq,
99 Qinv: key.Precomputed.Qinv,
102 priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues))
103 for i, values := range key.Precomputed.CRTValues {
104 priv.AdditionalPrimes[i].Prime = key.Primes[2+i]
105 priv.AdditionalPrimes[i].Exp = values.Exp
106 priv.AdditionalPrimes[i].Coeff = values.Coeff
109 b, _ := asn1.Marshal(priv)
113 // rsaPublicKey reflects the ASN.1 structure of a PKCS#1 public key.
114 type rsaPublicKey struct {