Black Lives Matter. Support the Equal Justice Initiative.

Source file src/crypto/x509/x509.go

Documentation: crypto/x509

     1  // Copyright 2009 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 parses X.509-encoded keys and certificates.
     6  package x509
     7  
     8  import (
     9  	"bytes"
    10  	"crypto"
    11  	"crypto/ecdsa"
    12  	"crypto/ed25519"
    13  	"crypto/elliptic"
    14  	"crypto/rsa"
    15  	"crypto/sha1"
    16  	"crypto/x509/pkix"
    17  	"encoding/asn1"
    18  	"encoding/pem"
    19  	"errors"
    20  	"fmt"
    21  	"io"
    22  	"math/big"
    23  	"net"
    24  	"net/url"
    25  	"strconv"
    26  	"time"
    27  	"unicode"
    28  
    29  	// Explicitly import these for their crypto.RegisterHash init side-effects.
    30  	// Keep these as blank imports, even if they're imported above.
    31  	_ "crypto/sha1"
    32  	_ "crypto/sha256"
    33  	_ "crypto/sha512"
    34  
    35  	"golang.org/x/crypto/cryptobyte"
    36  	cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
    37  )
    38  
    39  // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
    40  // in RFC 3280.
    41  type pkixPublicKey struct {
    42  	Algo      pkix.AlgorithmIdentifier
    43  	BitString asn1.BitString
    44  }
    45  
    46  // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
    47  // The encoded public key is a SubjectPublicKeyInfo structure
    48  // (see RFC 5280, Section 4.1).
    49  //
    50  // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or
    51  // ed25519.PublicKey. More types might be supported in the future.
    52  //
    53  // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
    54  func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
    55  	var pki publicKeyInfo
    56  	if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
    57  		if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
    58  			return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
    59  		}
    60  		return nil, err
    61  	} else if len(rest) != 0 {
    62  		return nil, errors.New("x509: trailing data after ASN.1 of public-key")
    63  	}
    64  	algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
    65  	if algo == UnknownPublicKeyAlgorithm {
    66  		return nil, errors.New("x509: unknown public key algorithm")
    67  	}
    68  	return parsePublicKey(algo, &pki)
    69  }
    70  
    71  func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
    72  	switch pub := pub.(type) {
    73  	case *rsa.PublicKey:
    74  		publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
    75  			N: pub.N,
    76  			E: pub.E,
    77  		})
    78  		if err != nil {
    79  			return nil, pkix.AlgorithmIdentifier{}, err
    80  		}
    81  		publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
    82  		// This is a NULL parameters value which is required by
    83  		// RFC 3279, Section 2.3.1.
    84  		publicKeyAlgorithm.Parameters = asn1.NullRawValue
    85  	case *ecdsa.PublicKey:
    86  		publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
    87  		oid, ok := oidFromNamedCurve(pub.Curve)
    88  		if !ok {
    89  			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
    90  		}
    91  		publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
    92  		var paramBytes []byte
    93  		paramBytes, err = asn1.Marshal(oid)
    94  		if err != nil {
    95  			return
    96  		}
    97  		publicKeyAlgorithm.Parameters.FullBytes = paramBytes
    98  	case ed25519.PublicKey:
    99  		publicKeyBytes = pub
   100  		publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
   101  	default:
   102  		return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
   103  	}
   104  
   105  	return publicKeyBytes, publicKeyAlgorithm, nil
   106  }
   107  
   108  // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
   109  // The encoded public key is a SubjectPublicKeyInfo structure
   110  // (see RFC 5280, Section 4.1).
   111  //
   112  // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
   113  // and ed25519.PublicKey. Unsupported key types result in an error.
   114  //
   115  // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
   116  func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
   117  	var publicKeyBytes []byte
   118  	var publicKeyAlgorithm pkix.AlgorithmIdentifier
   119  	var err error
   120  
   121  	if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
   122  		return nil, err
   123  	}
   124  
   125  	pkix := pkixPublicKey{
   126  		Algo: publicKeyAlgorithm,
   127  		BitString: asn1.BitString{
   128  			Bytes:     publicKeyBytes,
   129  			BitLength: 8 * len(publicKeyBytes),
   130  		},
   131  	}
   132  
   133  	ret, _ := asn1.Marshal(pkix)
   134  	return ret, nil
   135  }
   136  
   137  // These structures reflect the ASN.1 structure of X.509 certificates.:
   138  
   139  type certificate struct {
   140  	Raw                asn1.RawContent
   141  	TBSCertificate     tbsCertificate
   142  	SignatureAlgorithm pkix.AlgorithmIdentifier
   143  	SignatureValue     asn1.BitString
   144  }
   145  
   146  type tbsCertificate struct {
   147  	Raw                asn1.RawContent
   148  	Version            int `asn1:"optional,explicit,default:0,tag:0"`
   149  	SerialNumber       *big.Int
   150  	SignatureAlgorithm pkix.AlgorithmIdentifier
   151  	Issuer             asn1.RawValue
   152  	Validity           validity
   153  	Subject            asn1.RawValue
   154  	PublicKey          publicKeyInfo
   155  	UniqueId           asn1.BitString   `asn1:"optional,tag:1"`
   156  	SubjectUniqueId    asn1.BitString   `asn1:"optional,tag:2"`
   157  	Extensions         []pkix.Extension `asn1:"optional,explicit,tag:3"`
   158  }
   159  
   160  type dsaAlgorithmParameters struct {
   161  	P, Q, G *big.Int
   162  }
   163  
   164  type validity struct {
   165  	NotBefore, NotAfter time.Time
   166  }
   167  
   168  type publicKeyInfo struct {
   169  	Raw       asn1.RawContent
   170  	Algorithm pkix.AlgorithmIdentifier
   171  	PublicKey asn1.BitString
   172  }
   173  
   174  // RFC 5280,  4.2.1.1
   175  type authKeyId struct {
   176  	Id []byte `asn1:"optional,tag:0"`
   177  }
   178  
   179  type SignatureAlgorithm int
   180  
   181  const (
   182  	UnknownSignatureAlgorithm SignatureAlgorithm = iota
   183  
   184  	MD2WithRSA // Unsupported.
   185  	MD5WithRSA // Only supported for signing, not verification.
   186  	SHA1WithRSA
   187  	SHA256WithRSA
   188  	SHA384WithRSA
   189  	SHA512WithRSA
   190  	DSAWithSHA1   // Unsupported.
   191  	DSAWithSHA256 // Unsupported.
   192  	ECDSAWithSHA1
   193  	ECDSAWithSHA256
   194  	ECDSAWithSHA384
   195  	ECDSAWithSHA512
   196  	SHA256WithRSAPSS
   197  	SHA384WithRSAPSS
   198  	SHA512WithRSAPSS
   199  	PureEd25519
   200  )
   201  
   202  func (algo SignatureAlgorithm) isRSAPSS() bool {
   203  	switch algo {
   204  	case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
   205  		return true
   206  	default:
   207  		return false
   208  	}
   209  }
   210  
   211  func (algo SignatureAlgorithm) String() string {
   212  	for _, details := range signatureAlgorithmDetails {
   213  		if details.algo == algo {
   214  			return details.name
   215  		}
   216  	}
   217  	return strconv.Itoa(int(algo))
   218  }
   219  
   220  type PublicKeyAlgorithm int
   221  
   222  const (
   223  	UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
   224  	RSA
   225  	DSA // Unsupported.
   226  	ECDSA
   227  	Ed25519
   228  )
   229  
   230  var publicKeyAlgoName = [...]string{
   231  	RSA:     "RSA",
   232  	DSA:     "DSA",
   233  	ECDSA:   "ECDSA",
   234  	Ed25519: "Ed25519",
   235  }
   236  
   237  func (algo PublicKeyAlgorithm) String() string {
   238  	if 0 < algo && int(algo) < len(publicKeyAlgoName) {
   239  		return publicKeyAlgoName[algo]
   240  	}
   241  	return strconv.Itoa(int(algo))
   242  }
   243  
   244  // OIDs for signature algorithms
   245  //
   246  // pkcs-1 OBJECT IDENTIFIER ::= {
   247  //    iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
   248  //
   249  //
   250  // RFC 3279 2.2.1 RSA Signature Algorithms
   251  //
   252  // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2