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.
14 // pkcs1PrivateKey is a structure which mirrors the PKCS#1 ASN.1 for an RSA private key.
15 type pkcs1PrivateKey
struct {
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"`
27 AdditionalPrimes
[]pkcs1AdditionalRSAPrime
`asn1:"optional,omitempty"`
30 type pkcs1AdditionalRSAPrime
struct {
33 // We ignore these values because rsa will calculate them.
38 // ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form.
39 func ParsePKCS1PrivateKey(der
[]byte) (key
*rsa
.PrivateKey
, err error
) {
40 var priv pkcs1PrivateKey
41 rest
, err
:= asn1
.Unmarshal(der
, &priv
)
43 err
= asn1
.SyntaxError
{Msg
: "trailing data"}
51 return nil, errors
.New("x509: unsupported private key version")
54 if priv
.N
.Sign() <= 0 || priv
.D
.Sign() <= 0 || priv
.P
.Sign() <= 0 || priv
.Q
.Sign() <= 0 {
55 return nil, errors
.New("x509: private key contains zero or negative value")
58 key
= new(rsa
.PrivateKey
)
59 key
.PublicKey
= rsa
.PublicKey
{
65 key
.Primes
= make([]*big
.Int
, 2+len(priv
.AdditionalPrimes
))
66 key
.Primes
[0] = priv
.P
67 key
.Primes
[1] = priv
.Q
68 for i
, a
:= range priv
.AdditionalPrimes
{
69 if a
.Prime
.Sign() <= 0 {
70 return nil, errors
.New("x509: private key contains zero or negative prime")
72 key
.Primes
[i
+2] = a
.Prime
73 // We ignore the other two values because rsa will calculate
86 // MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.
87 func MarshalPKCS1PrivateKey(key
*rsa
.PrivateKey
) []byte {
91 if len(key
.Primes
) > 2 {
95 priv
:= pkcs1PrivateKey
{
102 Dp
: key
.Precomputed
.Dp
,
103 Dq
: key
.Precomputed
.Dq
,
104 Qinv
: key
.Precomputed
.Qinv
,
107 priv
.AdditionalPrimes
= make([]pkcs1AdditionalRSAPrime
, len(key
.Precomputed
.CRTValues
))
108 for i
, values
:= range key
.Precomputed
.CRTValues
{
109 priv
.AdditionalPrimes
[i
].Prime
= key
.Primes
[2+i
]
110 priv
.AdditionalPrimes
[i
].Exp
= values
.Exp
111 priv
.AdditionalPrimes
[i
].Coeff
= values
.Coeff
114 b
, _
:= asn1
.Marshal(priv
)
118 // rsaPublicKey reflects the ASN.1 structure of a PKCS#1 public key.
119 type rsaPublicKey
struct {