package x509
import (
)
type pkcs1PrivateKey struct {
Version int
N *big.Int
E int
D *big.Int
P *big.Int
Q *big.Int
Dp *big.Int `asn1:"optional"`
Dq *big.Int `asn1:"optional"`
Qinv *big.Int `asn1:"optional"`
AdditionalPrimes []pkcs1AdditionalRSAPrime `asn1:"optional,omitempty"`
}
type pkcs1AdditionalRSAPrime struct {
Prime *big.Int
Exp *big.Int
Coeff *big.Int
}
type pkcs1PublicKey struct {
N *big.Int
E int
}
func ( []byte) (*rsa.PrivateKey, error) {
var pkcs1PrivateKey
, := asn1.Unmarshal(, &)
if len() > 0 {
return nil, asn1.SyntaxError{Msg: "trailing data"}
}
if != nil {
if , := asn1.Unmarshal(, &ecPrivateKey{}); == nil {
return nil, errors.New("x509: failed to parse private key (use ParseECPrivateKey instead for this key format)")
}
if , := asn1.Unmarshal(, &pkcs8{}); == nil {
return nil, errors.New("x509: failed to parse private key (use ParsePKCS8PrivateKey instead for this key format)")
}
return nil,
}
if .Version > 1 {
return nil, errors.New("x509: unsupported private key version")
}
if .N.Sign() <= 0 || .D.Sign() <= 0 || .P.Sign() <= 0 || .Q.Sign() <= 0 {
return nil, errors.New("x509: private key contains zero or negative value")
}
:= new(rsa.PrivateKey)
.PublicKey = rsa.PublicKey{
E: .E,
N: .N,
}
.D = .D
.Primes = make([]*big.Int, 2+len(.AdditionalPrimes))
.Primes[0] = .P
.Primes[1] = .Q
for , := range .AdditionalPrimes {
if .Prime.Sign() <= 0 {
return nil, errors.New("x509: private key contains zero or negative prime")
}
.Primes[+2] = .Prime
}
= .Validate()
if != nil {
return nil,
}
.Precompute()
return , nil
}
func ( *rsa.PrivateKey) []byte {
.Precompute()
:= 0
if len(.Primes) > 2 {
= 1
}
:= pkcs1PrivateKey{
Version: ,
N: .N,
E: .PublicKey.E,
D: .D,
P: .Primes[0],
Q: .Primes[1],
Dp: .Precomputed.Dp,
Dq: .Precomputed.Dq,
Qinv: .Precomputed.Qinv,
}
.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(.Precomputed.CRTValues))
for , := range .Precomputed.CRTValues {
.AdditionalPrimes[].Prime = .Primes[2+]
.AdditionalPrimes[].Exp = .Exp
.AdditionalPrimes[].Coeff = .Coeff
}
, := asn1.Marshal()
return
}
func ( []byte) (*rsa.PublicKey, error) {
var pkcs1PublicKey
, := asn1.Unmarshal(, &)
if != nil {
if , := asn1.Unmarshal(, &publicKeyInfo{}); == nil {
return nil, errors.New("x509: failed to parse public key (use ParsePKIXPublicKey instead for this key format)")
}
return nil,
}
if len() > 0 {
return nil, asn1.SyntaxError{Msg: "trailing data"}
}
if .N.Sign() <= 0 || .E <= 0 {
return nil, errors.New("x509: public key contains zero or negative value")
}
if .E > 1<<31-1 {
return nil, errors.New("x509: public key contains large public exponent")
}
return &rsa.PublicKey{
E: .E,
N: .N,
}, nil
}
func ( *rsa.PublicKey) []byte {
, := asn1.Marshal(pkcs1PublicKey{
N: .N,
E: .E,
})
return
}