gitee.com/zhaochuninhefei/gmgo@v0.0.31-0.20240209061119-069254a02979/x509/x509.go (about) 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 /* 9 x509/x509.go 实现gmx509证书的相关操作: 10 ParsePKIXPublicKey : 将一个PKIX, ASN.1 DER格式字节数组转为对应的公钥 11 MarshalPKIXPublicKey : 将公钥转为PKIX, ASN.1 DER格式字节数组 12 Certificate : gmx509证书结构体 13 c.CheckSignatureFrom : 检查对c做的签名是否是父证书拥有者的有效签名(使用父证书中的公钥验签) 14 c.CheckSignature : 使用c的公钥检查签名是否有效 15 c.ToX509Certificate : gmx509转x509 16 c.FromX509Certificate : x509转gmx509 17 c.CheckCRLSignature : 检查证书撤销列表CRL是否由c签名 18 c.CreateCRL : 创建一个CRL 19 CreateCertificate : 根据证书模板生成gmx509证书(v3)的DER字节数组 20 ParseCRL : 将给定的字节数组(PEM/DER)转为CRL 21 ParseDERCRL : 将DER字节数组转为CRL 22 CertificateRequest : 证书申请结构体 23 CreateCertificateRequest : 基于证书申请模板生成一个新的证书申请 24 ParseCertificateRequest : 将DER字节数组转为单个证书申请 25 csr.CheckSignature : 检查证书申请c的签名是否有效 26 */ 27 28 import ( 29 "bytes" 30 "crypto" 31 "crypto/ecdsa" 32 "crypto/ed25519" 33 "crypto/elliptic" 34 "crypto/md5" 35 "crypto/rsa" 36 "crypto/sha1" 37 "crypto/sha256" 38 "crypto/sha512" 39 "crypto/x509" 40 "crypto/x509/pkix" 41 "encoding/asn1" 42 "encoding/binary" 43 "encoding/hex" 44 "encoding/pem" 45 "errors" 46 "fmt" 47 "gitee.com/zhaochuninhefei/gmgo/ecbase" 48 "gitee.com/zhaochuninhefei/gmgo/ecdsa_ext" 49 "gitee.com/zhaochuninhefei/zcgolog/zclog" 50 "io" 51 "math/big" 52 "net" 53 "net/url" 54 "strconv" 55 "time" 56 "unicode" 57 58 "gitee.com/zhaochuninhefei/gmgo/sm2" 59 "gitee.com/zhaochuninhefei/gmgo/sm3" 60 61 // Explicitly import these for their crypto.RegisterHash init side-effects. 62 // Keep these as blank imports, even if they're imported above. 63 _ "crypto/sha1" 64 _ "crypto/sha256" 65 _ "crypto/sha512" 66 67 "golang.org/x/crypto/cryptobyte" 68 cryptobyteasn1 "golang.org/x/crypto/cryptobyte/asn1" 69 "golang.org/x/crypto/sha3" 70 ) 71 72 // PKIX格式公钥结构体,用于x509证书中的公钥部分。 73 // pkixPublicKey reflects a PKIX public key structure. 74 // See SubjectPublicKeyInfo in RFC 3280. 75 type pkixPublicKey struct { 76 Algo pkix.AlgorithmIdentifier 77 BitString asn1.BitString 78 } 79 80 // ParsePKIXPublicKey 将一个PKIX, ASN.1 DER格式字节数组转为对应的公钥。 81 // 公钥支持 *sm2.PublicKey, *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey , 82 // 这些公钥的pem类型是"PUBLIC KEY"。 83 // 84 // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. 85 // The encoded public key is a SubjectPublicKeyInfo structure 86 // (see RFC 5280, Section 4.1). 87 // 88 // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or 89 // ed25519.PublicKey. More types might be supported in the future. 90 // 91 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY". 92 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) { 93 var pki publicKeyInfo 94 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil { 95 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil { 96 return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)") 97 } 98 return nil, err 99 } else if len(rest) != 0 { 100 return nil, errors.New("x509: trailing data after ASN.1 of public-key") 101 } 102 // 根据pki中的算法oid获取对应的算法 103 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm) 104 if algo == UnknownPublicKeyAlgorithm { 105 return nil, errors.New("x509: unknown public key algorithm") 106 } 107 return parsePublicKey(algo, &pki) 108 } 109 110 // 将公钥转为字节数组,同时返回对应的pkix算法标识符 111 func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) { 112 switch pub := pub.(type) { 113 case *sm2.PublicKey: 114 // 将椭圆曲线、公钥座标转换为字节数组 115 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) 116 // 获取椭圆曲线oid,注意,国标目前没有给出sm2椭圆曲线的oid,这里使用SM2算法的oid代替 117 oid, ok := oidFromNamedCurve(pub.Curve) 118 if !ok { 119 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported SM2 curve") 120 } 121 // 设定公钥算法的oid为sm2算法oid 122 publicKeyAlgorithm.Algorithm = oidPublicKeySM2 123 var paramBytes []byte 124 // 将椭圆曲线oid转为字节数组 125 paramBytes, err = asn1.Marshal(oid) 126 if err != nil { 127 return 128 } 129 publicKeyAlgorithm.Parameters.FullBytes = paramBytes 130 case *rsa.PublicKey: 131 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{ 132 N: pub.N, 133 E: pub.E, 134 }) 135 if err != nil { 136 return nil, pkix.AlgorithmIdentifier{}, err 137 } 138 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA 139 // This is a NULL parameters value which is required by 140 // RFC 3279, Section 2.3.1. 141 publicKeyAlgorithm.Parameters = asn1.NullRawValue 142 case *ecdsa.PublicKey: 143 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) 144 oid, ok := oidFromNamedCurve(pub.Curve) 145 if !ok { 146 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve") 147 } 148 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA 149 var paramBytes []byte 150 paramBytes, err = asn1.Marshal(oid) 151 if err != nil { 152 return 153 } 154 publicKeyAlgorithm.Parameters.FullBytes = paramBytes 155 case *ecdsa_ext.PublicKey: 156 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) 157 oid, ok := oidFromNamedCurve(pub.Curve) 158 if !ok { 159 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve") 160 } 161 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSAEXT 162 var paramBytes []byte 163 paramBytes, err = asn1.Marshal(oid) 164 if err != nil { 165 return 166 } 167 publicKeyAlgorithm.Parameters.FullBytes = paramBytes 168 case ed25519.PublicKey: 169 publicKeyBytes = pub 170 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519 171 default: 172 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub) 173 } 174 175 return publicKeyBytes, publicKeyAlgorithm, nil 176 } 177 178 // MarshalPKIXPublicKey 将公钥转为PKIX, ASN.1 DER格式字节数组。 179 // 公钥支持 *sm2.PublicKey, *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey , 180 // 这些公钥的pem类型是"PUBLIC KEY"。 181 // 182 // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form. 183 // The encoded public key is a SubjectPublicKeyInfo structure 184 // (see RFC 5280, Section 4.1). 185 // 186 // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey 187 // and ed25519.PublicKey. Unsupported key types result in an error. 188 // 189 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY". 190 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) { 191 var publicKeyBytes []byte 192 var publicKeyAlgorithm pkix.AlgorithmIdentifier 193 var err error 194 195 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil { 196 return nil, err 197 } 198 // 生成PKIX公钥 199 pkixPk := pkixPublicKey{ 200 Algo: publicKeyAlgorithm, 201 BitString: asn1.BitString{ 202 Bytes: publicKeyBytes, 203 BitLength: 8 * len(publicKeyBytes), 204 }, 205 } 206 // PKIX公钥字节数组,用于x509证书的公钥部分。 207 ret, _ := asn1.Marshal(pkixPk) 208 return ret, nil 209 } 210 211 // These structures reflect the ASN.1 structure of X.509 certificates.: 212 213 type certificate struct { 214 Raw asn1.RawContent 215 TBSCertificate tbsCertificate 216 SignatureAlgorithm pkix.AlgorithmIdentifier 217 SignatureValue asn1.BitString 218 } 219 220 // 证书主体,签名内容 221 // tbs即"To be signed" 222 type tbsCertificate struct { 223 Raw asn1.RawContent 224 Version int `asn1:"optional,explicit,default:0,tag:0"` 225 SerialNumber *big.Int 226 SignatureAlgorithm pkix.AlgorithmIdentifier 227 Issuer asn1.RawValue 228 Validity validity 229 Subject asn1.RawValue 230 PublicKey publicKeyInfo 231 UniqueId asn1.BitString `asn1:"optional,tag:1"` 232 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"` 233 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"` 234 } 235 236 //goland:noinspection GoUnusedType 237 type dsaAlgorithmParameters struct { 238 P, Q, G *big.Int 239 } 240 241 type validity struct { 242 NotBefore, NotAfter time.Time 243 } 244 245 type publicKeyInfo struct { 246 Raw asn1.RawContent 247 Algorithm pkix.AlgorithmIdentifier 248 PublicKey asn1.BitString 249 } 250 251 // RFC 5280, 4.2.1.1 252 type authKeyId struct { 253 Id []byte `asn1:"optional,tag:0"` 254 } 255 256 // 初始化加载所有支持的散列组件 257 func init() { 258 RegisterHash(MD4, nil) 259 RegisterHash(MD5, md5.New) 260 RegisterHash(SHA1, sha1.New) 261 RegisterHash(SHA224, sha256.New224) 262 RegisterHash(SHA256, sha256.New) 263 RegisterHash(SHA384, sha512.New384) 264 RegisterHash(SHA512, sha512.New) 265 RegisterHash(MD5SHA1, nil) 266 // RegisterHash(RIPEMD160, ripemd160.New) 267 RegisterHash(SHA3_224, sha3.New224) 268 RegisterHash(SHA3_256, sha3.New256) 269 RegisterHash(SHA3_384, sha3.New384) 270 RegisterHash(SHA3_512, sha3.New512) 271 RegisterHash(SHA512_224, sha512.New512_224) 272 RegisterHash(SHA512_256, sha512.New512_256) 273 RegisterHash(SM3, sm3.New) 274 } 275 276 // SignatureAlgorithm 签名算法 277 type SignatureAlgorithm int 278 279 const ( 280 UnknownSignatureAlgorithm SignatureAlgorithm = iota 281 282 MD2WithRSA // Unsupported. 283 MD5WithRSA // Only supported for signing, not verification. 284 SHA1WithRSA 285 SHA256WithRSA 286 SHA384WithRSA 287 SHA512WithRSA 288 DSAWithSHA1 // Unsupported. 289 DSAWithSHA256 // Unsupported. 290 ECDSAWithSHA1 291 ECDSAWithSHA256 292 ECDSAWithSHA384 293 ECDSAWithSHA512 294 SHA256WithRSAPSS 295 SHA384WithRSAPSS 296 SHA512WithRSAPSS 297 PureEd25519 298 SM2WithSM3 // 签名算法添加国密算法: SM2WithSM3 299 ECDSAEXTWithSHA256 // ecdsa_ext 扩展的ECDSA签名算法(支持low-s处理) 300 ECDSAEXTWithSHA384 // ecdsa_ext 扩展的ECDSA签名算法(支持low-s处理) 301 ECDSAEXTWithSHA512 // ecdsa_ext 扩展的ECDSA签名算法(支持low-s处理) 302 ) 303 304 func (algo SignatureAlgorithm) IsECDSAEXT() bool { 305 switch algo { 306 case ECDSAEXTWithSHA256, ECDSAEXTWithSHA384, ECDSAEXTWithSHA512: 307 return true 308 default: 309 return false 310 } 311 } 312 313 func (algo SignatureAlgorithm) isRSAPSS() bool { 314 switch algo { 315 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS: 316 return true 317 default: 318 return false 319 } 320 } 321 322 func (algo SignatureAlgorithm) String() string { 323 for _, details := range signatureAlgorithmDetails { 324 if details.algo == algo { 325 return details.name 326 } 327 } 328 return strconv.Itoa(int(algo)) 329 } 330 331 // PublicKeyAlgorithm 公钥算法 332 type PublicKeyAlgorithm int 333 334 const ( 335 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota 336 RSA 337 DSA // Unsupported. 338 ECDSA 339 Ed25519 340 SM2 // 公钥算法添加SM2 341 ECDSAEXT // ecdsa_ext 扩展的ecdsa公钥算法 342 ) 343 344 var publicKeyAlgoName = [...]string{ 345 RSA: "RSA", 346 DSA: "DSA", 347 ECDSA: "ECDSA", 348 Ed25519: "Ed25519", 349 SM2: "SM2", // 公钥算法名称定义添加SM2 350 ECDSAEXT: "ECDSAEXT", // ecdsa_ext 扩展的ecdsa公钥算法 351 } 352 353 func (algo PublicKeyAlgorithm) String() string { 354 if 0 < algo && int(algo) < len(publicKeyAlgoName) { 355 return publicKeyAlgoName[algo] 356 } 357 return strconv.Itoa(int(algo)) 358 } 359 360 // OIDs for signature algorithms 361 // 362 // pkcs-1 OBJECT IDENTIFIER ::= { 363 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } 364 // 365 // 366 // RFC 3279 2.2.1 RSA Signature Algorithms 367 // 368 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 } 369 // 370 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 } 371 // 372 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 } 373 // 374 // dsaWithSha1 OBJECT IDENTIFIER ::= { 375 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 } 376 // 377 // RFC 3279 2.2.3 ECDSA Signature Algorithm 378 // 379 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= { 380 // iso(1) member-body(2) us(840) ansi-x962(10045) 381 // signatures(4) ecdsa-with-SHA1(1)} 382 // 383 // 384 // RFC 4055 5 PKCS #1 Version 1.5 385 // 386 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 } 387 // 388 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 } 389 // 390 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 } 391 // 392 // 393 // RFC 5758 3.1 DSA Signature Algorithms 394 // 395 // dsaWithSha256 OBJECT IDENTIFIER ::= { 396 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101) 397 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2} 398 // 399 // RFC 5758 3.2 ECDSA Signature Algorithm 400 // 401 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) 402 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 } 403 // 404 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) 405 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 } 406 // 407 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) 408 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 } 409 // 410 // 411 // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers 412 // 413 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 } 414 415 //goland:noinspection GoUnusedGlobalVariable 416 var ( 417 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2} 418 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4} 419 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5} 420 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11} 421 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12} 422 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13} 423 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10} 424 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3} 425 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2} 426 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1} 427 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2} 428 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3} 429 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4} 430 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112} 431 432 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1} 433 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2} 434 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3} 435 436 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8} 437 438 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA 439 // but it's specified by ISO. Microsoft's makecert.exe has been known 440 // to produce certificates with this OID. 441 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29} 442 443 // 国密相关算法标识定义,参考国密标准`GMT 0006-2012 密码应用标识规范.pdf` 444 oidSignatureSM2WithSM3 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 501} 445 // oidSM3 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 401, 1} 446 oidSM3 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 401} 447 448 //oidSignatureECDSAEXTWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 5, 3, 2} 449 //oidSignatureECDSAEXTWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 5, 3, 3} 450 //oidSignatureECDSAEXTWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 5, 3, 4} 451 ) 452 453 // 定义支持的签名算法细节 454 var signatureAlgorithmDetails = []struct { 455 algo SignatureAlgorithm 456 name string 457 oid asn1.ObjectIdentifier 458 pubKeyAlgo PublicKeyAlgorithm 459 hash Hash 460 opts crypto.SignerOpts 461 }{ 462 {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, Hash(0), Hash(0) /* no value for MD2 */}, 463 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, MD5, MD5}, 464 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, SHA1, SHA1}, 465 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, SHA1, SHA1}, 466 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, SHA256, SHA256}, 467 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, SHA384, SHA384}, 468 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, SHA512, SHA512}, 469 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, SHA256, &rsa.PSSOptions{ 470 SaltLength: rsa.PSSSaltLengthEqualsHash, 471 Hash: SHA256.HashFunc(), 472 }}, 473 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, SHA384, &rsa.PSSOptions{ 474 SaltLength: rsa.PSSSaltLengthEqualsHash, 475 Hash: SHA384.HashFunc(), 476 }}, 477 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, SHA512, &rsa.PSSOptions{ 478 SaltLength: rsa.PSSSaltLengthEqualsHash, 479 Hash: SHA512.HashFunc(), 480 }}, 481 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, SHA1, SHA1}, 482 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, SHA256, SHA256}, 483 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, SHA1, ecbase.CreateEcSignerOpts(SHA1.HashFunc(), false)}, 484 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, SHA256, ecbase.CreateEcSignerOpts(SHA256.HashFunc(), false)}, 485 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, SHA384, ecbase.CreateEcSignerOpts(SHA384.HashFunc(), false)}, 486 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, SHA512, ecbase.CreateEcSignerOpts(SHA512.HashFunc(), false)}, 487 {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, Hash(0), Hash(0) /* no pre-hashing */}, 488 // 添加SM2相关签名算法定义, sm2签名算法既可以在内部做散列,也可以在外部做散列,但gmx509固定为在sm2签名算法内部做ZA散列计算,这里的散列算法设置为Hash(0)。 489 {SM2WithSM3, "SM2-with-SM3", oidSignatureSM2WithSM3, SM2, Hash(0), sm2.DefaultSM2SignerOption()}, 490 // 添加ecdsa_ext扩展的ecdsa签名算法定义, 支持low-s处理 491 {ECDSAEXTWithSHA256, "ECDSA-EXT-SHA256", oidSignatureECDSAWithSHA256, ECDSAEXT, SHA256, ecbase.CreateEcSignerOpts(SHA256.HashFunc(), true)}, 492 {ECDSAEXTWithSHA384, "ECDSA-EXT-SHA384", oidSignatureECDSAWithSHA384, ECDSAEXT, SHA384, ecbase.CreateEcSignerOpts(SHA384.HashFunc(), true)}, 493 {ECDSAEXTWithSHA512, "ECDSA-EXT-SHA512", oidSignatureECDSAWithSHA512, ECDSAEXT, SHA512, ecbase.CreateEcSignerOpts(SHA512.HashFunc(), true)}, 494 } 495 496 // hashToPSSParameters contains the DER encoded RSA PSS parameters for the 497 // SHA256, SHA384, and SHA512 hashes as defined in RFC 3447, Appendix A.2.3. 498 // The parameters contain the following values: 499 // * hashAlgorithm contains the associated hash identifier with NULL parameters 500 // * maskGenAlgorithm always contains the default mgf1SHA1 identifier 501 // * saltLength contains the length of the associated hash 502 // * trailerField always contains the default trailerFieldBC value 503 var hashToPSSParameters = map[Hash]asn1.RawValue{ 504 SHA256: {FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 162, 3, 2, 1, 32}}, 505 SHA384: {FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 162, 3, 2, 1, 48}}, 506 SHA512: {FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 162, 3, 2, 1, 64}}, 507 } 508 509 // pssParameters reflects the parameters in an AlgorithmIdentifier that 510 // specifies RSA PSS. See RFC 3447, Appendix A.2.3. 511 type pssParameters struct { 512 // The following three fields are not marked as 513 // optional because the default values specify SHA-1, 514 // which is no longer suitable for use in signatures. 515 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"` 516 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"` 517 SaltLength int `asn1:"explicit,tag:2"` 518 TrailerField int `asn1:"optional,explicit,tag:3,default:1"` 519 } 520 521 // 根据pkix.AlgorithmIdentifier获取签名算法 522 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm { 523 if ai.Algorithm.Equal(oidSignatureEd25519) { 524 // RFC 8410, Section 3 525 // > For all of the OIDs, the parameters MUST be absent. 526 if len(ai.Parameters.FullBytes) != 0 { 527 return UnknownSignatureAlgorithm 528 } 529 } 530 531 if !ai.Algorithm.Equal(oidSignatureRSAPSS) { 532 // 国密签名算法走该分支 533 for _, details := range signatureAlgorithmDetails { 534 // TODO ecdsa与ecdsa+ext共用相同的oid,这里取哪一个? 535 if ai.Algorithm.Equal(details.oid) { 536 return details.algo 537 } 538 } 539 return UnknownSignatureAlgorithm 540 } 541 542 // RSA PSS is special because it encodes important parameters 543 // in the Parameters. 544 545 var params pssParameters 546 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil { 547 return UnknownSignatureAlgorithm 548 } 549 550 var mgf1HashFunc pkix.AlgorithmIdentifier 551 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil { 552 return UnknownSignatureAlgorithm 553 } 554 555 // PSS is greatly overburdened with options. This code forces them into 556 // three buckets by requiring that the MGF1 hash function always match the 557 // message hash function (as recommended in RFC 3447, Section 8.1), that the 558 // salt length matches the hash length, and that the trailer field has the 559 // default value. 560 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) || 561 !params.MGF.Algorithm.Equal(oidMGF1) || 562 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) || 563 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) || 564 params.TrailerField != 1 { 565 return UnknownSignatureAlgorithm 566 } 567 568 switch { 569 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32: 570 return SHA256WithRSAPSS 571 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48: 572 return SHA384WithRSAPSS 573 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64: 574 return SHA512WithRSAPSS 575 } 576 577 return UnknownSignatureAlgorithm 578 } 579 580 // RFC 3279, 2.3 Public Key Algorithms 581 // 582 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840) 583 // rsadsi(113549) pkcs(1) 1 } 584 // 585 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 } 586 // 587 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840) 588 // x9-57(10040) x9cm(4) 1 } 589 // 590 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters 591 // 592 // id-ecPublicKey OBJECT IDENTIFIER ::= { 593 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 } 594 var ( 595 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1} 596 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1} 597 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1} 598 // 自定义ecdsa_ext算法标识,`1.3.6.1.4.1`是ISO分配给私人企业的节点,`60387`是向IANA申请到的企业ID(zhaochuninhefei),`1`是该企业在该节点下的子节点,`2`是该子节点下的ecdsa_ext算法标识 599 oidPublicKeyECDSAEXT = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 60387, 1, 2} 600 oidPublicKeyEd25519 = oidSignatureEd25519 601 // SM2算法标识 参考`GMT 0006-2012 密码应用标识规范.pdf`的`附录A 商用密码领域中的相关oID定义` 602 oidPublicKeySM2 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301} 603 // // 通过asn1.Marshal(asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301})计算得出 604 // sm2OidFullBytes = []byte{6, 8, 42, 129, 28, 207, 85, 1, 130, 45} 605 ) 606 607 // 根据OID获取公钥算法 608 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm { 609 switch { 610 case oid.Equal(oidPublicKeySM2): 611 return SM2 612 case oid.Equal(oidPublicKeyRSA): 613 return RSA 614 case oid.Equal(oidPublicKeyDSA): 615 return DSA 616 case oid.Equal(oidPublicKeyECDSA): 617 return ECDSA 618 case oid.Equal(oidPublicKeyECDSAEXT): 619 return ECDSAEXT 620 case oid.Equal(oidPublicKeyEd25519): 621 return Ed25519 622 } 623 return UnknownPublicKeyAlgorithm 624 } 625 626 // RFC 5480, 2.1.1.1. Named Curve 627 // 628 // secp224r1 OBJECT IDENTIFIER ::= { 629 // iso(1) identified-organization(3) certicom(132) curve(0) 33 } 630 // 631 // secp256r1 OBJECT IDENTIFIER ::= { 632 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) 633 // prime(1) 7 } 634 // 635 // secp384r1 OBJECT IDENTIFIER ::= { 636 // iso(1) identified-organization(3) certicom(132) curve(0) 34 } 637 // 638 // secp521r1 OBJECT IDENTIFIER ::= { 639 // iso(1) identified-organization(3) certicom(132) curve(0) 35 } 640 // 641 // NB: secp256r1 is equivalent to prime256v1 642 var ( 643 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33} 644 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7} 645 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34} 646 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35} 647 // SM2椭圆曲线参数标识 没有查到,用SM2算法标识代替 648 oidNamedCurveP256SM2 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301} 649 ) 650 651 // 根据oid获取对应的椭圆曲线参数 652 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve { 653 switch { 654 case oid.Equal(oidNamedCurveP256SM2): 655 return sm2.P256Sm2() 656 case oid.Equal(oidNamedCurveP224): 657 return elliptic.P224() 658 case oid.Equal(oidNamedCurveP256): 659 return elliptic.P256() 660 case oid.Equal(oidNamedCurveP384): 661 return elliptic.P384() 662 case oid.Equal(oidNamedCurveP521): 663 return elliptic.P521() 664 } 665 return nil 666 } 667 668 // 根据椭圆曲线参数获取对应的oid 669 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) { 670 switch curve { 671 case sm2.P256Sm2(): 672 return oidNamedCurveP256SM2, true 673 case elliptic.P224(): 674 return oidNamedCurveP224, true 675 case elliptic.P256(): 676 return oidNamedCurveP256, true 677 case elliptic.P384(): 678 return oidNamedCurveP384, true 679 case elliptic.P521(): 680 return oidNamedCurveP521, true 681 } 682 683 return nil, false 684 } 685 686 // KeyUsage 公钥用途,即证书用途。 687 // KeyUsage represents the set of actions that are valid for a given key. It's 688 // a bitmap of the KeyUsage* constants. 689 type KeyUsage int 690 691 const ( 692 KeyUsageDigitalSignature KeyUsage = 1 << iota // Digital Signature 693 KeyUsageContentCommitment // Non Repudiation 694 KeyUsageKeyEncipherment // Key Encipherment 695 KeyUsageDataEncipherment // Data Encipherment 696 KeyUsageKeyAgreement // Key Agreement 697 KeyUsageCertSign // Certificate Sign 698 KeyUsageCRLSign // CRL Sign 699 KeyUsageEncipherOnly // Encipher Only 700 KeyUsageDecipherOnly // Decipher Only 701 ) 702 703 // RFC 5280, 4.2.1.12 Extended Key Usage 704 // 705 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 } 706 // 707 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 } 708 // 709 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 } 710 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 } 711 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 } 712 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 } 713 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 } 714 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 } 715 var ( 716 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0} 717 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1} 718 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2} 719 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3} 720 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4} 721 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5} 722 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6} 723 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7} 724 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8} 725 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9} 726 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3} 727 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1} 728 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22} 729 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1} 730 ) 731 732 // ExtKeyUsage 公钥(证书)扩展用途 733 // ExtKeyUsage represents an extended set of actions that are valid for a given key. 734 // Each of the ExtKeyUsage* constants define a unique action. 735 type ExtKeyUsage int 736 737 const ( 738 ExtKeyUsageAny ExtKeyUsage = iota // Any Extended Key Usage 739 ExtKeyUsageServerAuth // TLS Web Server Authentication 740 ExtKeyUsageClientAuth // TLS Web Client Authentication 741 ExtKeyUsageCodeSigning // Code Signing 742 ExtKeyUsageEmailProtection // E-mail Protection 743 ExtKeyUsageIPSECEndSystem // IPSec End System 744 ExtKeyUsageIPSECTunnel // IPSec Tunnel 745 ExtKeyUsageIPSECUser // IPSec User 746 ExtKeyUsageTimeStamping // Time Stamping 747 ExtKeyUsageOCSPSigning // OCSP Signing 748 ExtKeyUsageMicrosoftServerGatedCrypto // Microsoft Server Gated Crypto 749 ExtKeyUsageNetscapeServerGatedCrypto // Netscape Server Gated Crypto 750 ExtKeyUsageMicrosoftCommercialCodeSigning 751 ExtKeyUsageMicrosoftKernelCodeSigning 752 ) 753 754 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID. 755 var extKeyUsageOIDs = []struct { 756 extKeyUsage ExtKeyUsage 757 oid asn1.ObjectIdentifier 758 }{ 759 {ExtKeyUsageAny, oidExtKeyUsageAny}, 760 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth}, 761 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth}, 762 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning}, 763 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection}, 764 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem}, 765 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel}, 766 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser}, 767 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping}, 768 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning}, 769 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto}, 770 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto}, 771 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning}, 772 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning}, 773 } 774 775 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) { 776 for _, pair := range extKeyUsageOIDs { 777 if oid.Equal(pair.oid) { 778 return pair.extKeyUsage, true 779 } 780 } 781 return 782 } 783 784 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) { 785 for _, pair := range extKeyUsageOIDs { 786 if eku == pair.extKeyUsage { 787 return pair.oid, true 788 } 789 } 790 return 791 } 792 793 // Certificate gmx509证书结构体 794 // A Certificate represents an X.509 certificate. 795 type Certificate struct { 796 // 完整的 ASN1 DER 证书字节数组(证书+签名算法+签名) 797 // Complete ASN.1 DER content (certificate, signature algorithm and signature). 798 Raw []byte 799 // 签名内容的原始 ASN.1 DER字节数组 800 // Certificate part of raw ASN.1 DER content. 801 RawTBSCertificate []byte 802 // SubjectPublicKeyInfo的DER字节数组 803 // DER encoded SubjectPublicKeyInfo. 804 RawSubjectPublicKeyInfo []byte 805 // 证书拥有者的DER字节数组 806 // DER encoded Subject 807 RawSubject []byte 808 // 证书签署者的DER字节数组 809 // DER encoded Issuer 810 RawIssuer []byte 811 812 // 签名DER字节数组 813 Signature []byte 814 // 签名算法 815 SignatureAlgorithm SignatureAlgorithm 816 817 // 证书拥有者的公钥算法 818 PublicKeyAlgorithm PublicKeyAlgorithm 819 // 证书拥有者的公钥(证书的核心内容) 820 PublicKey interface{} 821 822 // 证书版本 823 Version int 824 // 证书序列号 825 SerialNumber *big.Int 826 // 证书签署者(提供私钥对RawTBSCertificate进行签名) 827 Issuer pkix.Name 828 // 证书拥有者(该证书的核心公钥的拥有者) 829 Subject pkix.Name 830 // 证书有效期间 831 // Validity bounds. 832 NotBefore, NotAfter time.Time 833 // 证书公钥的用途 834 KeyUsage KeyUsage 835 836 // Extensions contains raw X.509 extensions. When parsing certificates, 837 // this can be used to extract non-critical extensions that are not 838 // parsed by this package. When marshaling certificates, the Extensions 839 // field is ignored, see ExtraExtensions. 840 Extensions []pkix.Extension 841 842 // ExtraExtensions contains extensions to be copied, raw, into any 843 // marshaled certificates. Values override any extensions that would 844 // otherwise be produced based on the other fields. The ExtraExtensions 845 // field is not populated when parsing certificates, see Extensions. 846 ExtraExtensions []pkix.Extension 847 848 // UnhandledCriticalExtensions contains a list of extension IDs that 849 // were not (fully) processed when parsing. Verify will fail if this 850 // slice is non-empty, unless verification is delegated to an OS 851 // library which understands all the critical extensions. 852 // 853 // Users can access these extensions using Extensions and can remove 854 // elements from this slice if they believe that they have been 855 // handled. 856 UnhandledCriticalExtensions []asn1.ObjectIdentifier 857 858 // 公钥扩展用途 859 // Sequence of extended key usages. 860 ExtKeyUsage []ExtKeyUsage 861 // 未知的公钥扩展用途 862 // Encountered extended key usages unknown to this package. 863 UnknownExtKeyUsage []asn1.ObjectIdentifier 864 865 // 基础约束是否有效,控制 IsCA 与 MaxPathLen 是否有效 866 // BasicConstraintsValid indicates whether IsCA, MaxPathLen, 867 // and MaxPathLenZero are valid. 868 BasicConstraintsValid bool 869 // 是否CA证书 870 // IsCA为false时,表示该证书不是CA证书,MaxPathLen无效。 871 // IsCA为true时,表示该证书是CA证书,此时MaxPathLen表示该证书所属证书信任链中的中间CA证书的数量上限。 872 IsCA bool 873 // MaxPathLen and MaxPathLenZero indicate the presence and 874 // value of the BasicConstraints' "pathLenConstraint". 875 // 876 // When parsing a certificate, a positive non-zero MaxPathLen 877 // means that the field was specified, -1 means it was unset, 878 // and MaxPathLenZero being true mean that the field was 879 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false 880 // should be treated equivalent to -1 (unset). 881 // 882 // When generating a certificate, an unset pathLenConstraint 883 // can be requested with either MaxPathLen == -1 or using the 884 // zero value for both MaxPathLen and MaxPathLenZero. 885 MaxPathLen int 886 // MaxPathLenZero indicates that BasicConstraintsValid==true 887 // and MaxPathLen==0 should be interpreted as an actual 888 // maximum path length of zero. Otherwise, that combination is 889 // interpreted as MaxPathLen not being set. 890 MaxPathLenZero bool 891 892 // 证书拥有者密钥ID 893 // 以sm2公钥为例,计算方式为 将椭圆曲线上的公钥座标转换为字节数组再做sm3散列 894 SubjectKeyId []byte 895 // 证书签署者密钥ID(自签名时,AuthorityKeyId就是自己的SubjectKeyId;由父证书签名时,就是父证书的SubjectKeyId) 896 AuthorityKeyId []byte 897 898 // RFC 5280, 4.2.2.1 (Authority Information Access) 899 OCSPServer []string 900 IssuingCertificateURL []string 901 902 // Subject Alternate Name values. (Note that these values may not be valid 903 // if invalid values were contained within a parsed certificate. For 904 // example, an element of DNSNames may not be a valid DNS domain name.) 905 // go1.15开始废弃CommonName,使用SAN扩展信息。 906 // SAN扩展信息由下面四个字段组成。 907 DNSNames []string 908 EmailAddresses []string 909 IPAddresses []net.IP 910 URIs []*url.URL 911 912 // Name constraints 913 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical. 914 PermittedDNSDomains []string 915 ExcludedDNSDomains []string 916 PermittedIPRanges []*net.IPNet 917 ExcludedIPRanges []*net.IPNet 918 PermittedEmailAddresses []string 919 ExcludedEmailAddresses []string 920 PermittedURIDomains []string 921 ExcludedURIDomains []string 922 923 // CRL Distribution Points 924 CRLDistributionPoints []string 925 926 PolicyIdentifiers []asn1.ObjectIdentifier 927 } 928 929 // ErrUnsupportedAlgorithm results from attempting to perform an operation that 930 // involves algorithms that are not currently implemented. 931 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented") 932 933 // An InsecureAlgorithmError 934 type InsecureAlgorithmError SignatureAlgorithm 935 936 func (e InsecureAlgorithmError) Error() string { 937 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e)) 938 } 939 940 // ConstraintViolationError results when a requested usage is not permitted by 941 // a certificate. For example: checking a signature when the public key isn't a 942 // certificate signing key. 943 type ConstraintViolationError struct{} 944 945 func (ConstraintViolationError) Error() string { 946 return "x509: invalid signature: parent certificate cannot sign this kind of certificate" 947 } 948 949 func (c *Certificate) Equal(other *Certificate) bool { 950 if c == nil || other == nil { 951 return c == other 952 } 953 return bytes.Equal(c.Raw, other.Raw) 954 } 955 956 func (c *Certificate) hasSANExtension() bool { 957 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions) 958 } 959 960 // CheckSignatureFrom 检查对c做的签名是否是父证书拥有者的有效签名(使用父证书中的公钥验签) 961 // CheckSignatureFrom verifies that the signature on c is a valid signature 962 // from parent. 963 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error { 964 // RFC 5280, 4.2.1.9: 965 // "If the basic constraints extension is not present in a version 3 966 // certificate, or the extension is present but the cA boolean is not 967 // asserted, then the certified public key MUST NOT be used to verify 968 // certificate signatures." 969 if parent.Version == 3 && !parent.BasicConstraintsValid || 970 parent.BasicConstraintsValid && !parent.IsCA { 971 return ConstraintViolationError{} 972 } 973 974 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 { 975 return ConstraintViolationError{} 976 } 977 978 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm { 979 return ErrUnsupportedAlgorithm 980 } 981 982 // TODO(agl): don't ignore the path length constraint. 983 984 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature) 985 } 986 987 // CheckSignature 使用c的公钥检查签名是否有效 988 // - algo : 签名算法 989 // - signed : 签名内容 990 // - signature : 签名DER字节数组 991 // 992 // CheckSignature verifies that signature is a valid signature over signed from 993 // c's public key. 994 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error { 995 return checkSignature(algo, signed, signature, c.PublicKey) 996 } 997 998 func (c *Certificate) hasNameConstraints() bool { 999 return oidInExtensions(oidExtensionNameConstraints, c.Extensions) 1000 } 1001 1002 func (c *Certificate) getSANExtension() []byte { 1003 for _, e := range c.Extensions { 1004 if e.Id.Equal(oidExtensionSubjectAltName) { 1005 return e.Value 1006 } 1007 } 1008 return nil 1009 } 1010 1011 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error { 1012 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey) 1013 } 1014 1015 // checkSignature检查签名是否有效 1016 // algo : 签名算法 1017 // signed : 签名内容 1018 // signature : 签名DER字节数组 1019 // publicKey : 签名者公钥 1020 // 1021 // CheckSignature verifies that signature is a valid signature over signed from 1022 // a crypto.PublicKey. 1023 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) { 1024 var hashType Hash 1025 var pubKeyAlgo PublicKeyAlgorithm 1026 var opts crypto.SignerOpts 1027 1028 for _, details := range signatureAlgorithmDetails { 1029 if details.algo == algo { 1030 hashType = details.hash 1031 pubKeyAlgo = details.pubKeyAlgo 1032 opts = details.opts 1033 break 1034 } 1035 } 1036 1037 // 关于ecdsa_ext的特殊处理 1038 if pubKeyAlgo == ECDSAEXT { 1039 if pubKey, ok := publicKey.(*ecdsa.PublicKey); ok { 1040 publicKey = ecdsa_ext.ConvPubKeyFromOrigin(pubKey) 1041 } 1042 } 1043 1044 switch hashType { 1045 case Hash(0): 1046 // ed25519与sm2不需要对消息做摘要计算 1047 if pubKeyAlgo != Ed25519 && pubKeyAlgo != SM2 { 1048 return ErrUnsupportedAlgorithm 1049 } 1050 case MD5: 1051 return InsecureAlgorithmError(algo) 1052 default: 1053 if !hashType.Available() { 1054 return ErrUnsupportedAlgorithm 1055 } 1056 h := hashType.New() 1057 h.Write(signed) 1058 signed = h.Sum(nil) 1059 } 1060 1061 switch pub := publicKey.(type) { 1062 case *sm2.PublicKey: 1063 if pubKeyAlgo != SM2 { 1064 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub) 1065 } 1066 if sm2Opts, ok := opts.(*sm2.SM2SignerOption); ok { 1067 _, err = pub.EcVerify(signed, signature, sm2Opts) 1068 if err != nil { 1069 zclog.ErrorStack("sm2 checkSignature 失败, 调用栈如下:") 1070 return errors.New("x509: SM2 verification failure") 1071 } 1072 } else { 1073 return errors.New("x509: 内建签名算法列表中sm2的opts类型不正确") 1074 } 1075 return nil 1076 case *rsa.PublicKey: 1077 if pubKeyAlgo != RSA { 1078 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub) 1079 } 1080 if algo.isRSAPSS() { 1081 return rsa.VerifyPSS(pub, hashType.HashFunc(), signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash}) 1082 } else { 1083 return rsa.VerifyPKCS1v15(pub, hashType.HashFunc(), signed, signature) 1084 } 1085 case *ecdsa.PublicKey: 1086 if pubKeyAlgo != ECDSA && pubKeyAlgo != ECDSAEXT { 1087 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub) 1088 } 1089 if ecOpts, ok := opts.(ecbase.EcSignerOpts); ok { 1090 if ecOpts.NeedLowS() { 1091 // 检查签名s值是否low-s 1092 isLow, err := ecdsa_ext.IsSigLowS(pub, signature) 1093 if err != nil { 1094 return err 1095 } 1096 if !isLow { 1097 return errors.New("ecdsa验签失败, 签名s值不是low-s值") 1098 } 1099 } 1100 if !ecdsa.VerifyASN1(pub, signed, signature) { 1101 zclog.ErrorStack("ecdsa checkSignature 失败, 调用栈如下:") 1102 zclog.Errorf("x509: ECDSA verification failure, 公钥SKI: %s, 签名主体: %s, 签名: %s", CreateEllipticSKI(pub.Curve, pub.X, pub.Y), hex.EncodeToString(signed), hex.EncodeToString(signature)) 1103 return errors.New("x509: ECDSA verification failure") 1104 } 1105 } else { 1106 return errors.New("x509: 内建签名算法列表中ecdsa的opts类型不正确") 1107 } 1108 return nil 1109 case *ecdsa_ext.PublicKey: 1110 if pubKeyAlgo != ECDSA && pubKeyAlgo != ECDSAEXT { 1111 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub) 1112 } 1113 if ecOpts, ok := opts.(ecbase.EcSignerOpts); ok { 1114 _, err = pub.EcVerify(signed, signature, ecOpts) 1115 if err != nil { 1116 zclog.ErrorStack("ecdsa_ext checkSignature 失败, 调用栈如下:") 1117 zclog.Errorf("x509: ECDSAEXT verification failure, 公钥SKI: %s, 签名主体: %s, 签名: %s", CreateEllipticSKI(pub.Curve, pub.X, pub.Y), hex.EncodeToString(signed), hex.EncodeToString(signature)) 1118 return fmt.Errorf("x509: ECDSAEXT verification failure: %s", err.Error()) 1119 } 1120 } else { 1121 return errors.New("x509: 内建签名算法列表中ecdsa的opts类型不正确") 1122 } 1123 return nil 1124 case ed25519.PublicKey: 1125 if pubKeyAlgo != Ed25519 { 1126 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub) 1127 } 1128 if !ed25519.Verify(pub, signed, signature) { 1129 return errors.New("x509: Ed25519 verification failure") 1130 } 1131 return nil 1132 } 1133 return ErrUnsupportedAlgorithm 1134 } 1135 1136 // CheckCRLSignature 检查证书撤销列表CRL是否由c签名。 1137 // CheckCRLSignature checks that the signature in crl is from c. 1138 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error { 1139 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm) 1140 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign()) 1141 } 1142 1143 type UnhandledCriticalExtension struct{} 1144 1145 func (h UnhandledCriticalExtension) Error() string { 1146 return "x509: unhandled critical extension" 1147 } 1148 1149 type basicConstraints struct { 1150 IsCA bool `asn1:"optional"` 1151 MaxPathLen int `asn1:"optional,default:-1"` 1152 } 1153 1154 // RFC 5280 4.2.1.4 1155 type policyInformation struct { 1156 Policy asn1.ObjectIdentifier 1157 // policyQualifiers omitted 1158 } 1159 1160 const ( 1161 nameTypeEmail = 1 1162 nameTypeDNS = 2 1163 nameTypeURI = 6 1164 nameTypeIP = 7 1165 ) 1166 1167 // RFC 5280, 4.2.2.1 1168 type authorityInfoAccess struct { 1169 Method asn1.ObjectIdentifier 1170 Location asn1.RawValue 1171 } 1172 1173 // RFC 5280, 4.2.1.14 1174 type distributionPoint struct { 1175 DistributionPoint distributionPointName `asn1:"optional,tag:0"` 1176 Reason asn1.BitString `asn1:"optional,tag:1"` 1177 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"` 1178 } 1179 1180 type distributionPointName struct { 1181 FullName []asn1.RawValue `asn1:"optional,tag:0"` 1182 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"` 1183 } 1184 1185 func reverseBitsInAByte(in byte) byte { 1186 b1 := in>>4 | in<<4 1187 b2 := b1>>2&0x33 | b1<<2&0xcc 1188 b3 := b2>>1&0x55 | b2<<1&0xaa 1189 return b3 1190 } 1191 1192 // asn1BitLength returns the bit-length of bitString by considering the 1193 // most-significant bit in a byte to be the "first" bit. This convention 1194 // matches ASN.1, but differs from almost everything else. 1195 func asn1BitLength(bitString []byte) int { 1196 bitLen := len(bitString) * 8 1197 1198 for i := range bitString { 1199 b := bitString[len(bitString)-i-1] 1200 1201 for bit := uint(0); bit < 8; bit++ { 1202 if (b>>bit)&1 == 1 { 1203 return bitLen 1204 } 1205 bitLen-- 1206 } 1207 } 1208 1209 return 0 1210 } 1211 1212 // x509证书扩展信息oid定义 1213 var ( 1214 oidExtensionSubjectKeyId = []int{2, 5, 29, 14} 1215 oidExtensionKeyUsage = []int{2, 5, 29, 15} 1216 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37} 1217 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35} 1218 oidExtensionBasicConstraints = []int{2, 5, 29, 19} 1219 oidExtensionSubjectAltName = []int{2, 5, 29, 17} 1220 oidExtensionCertificatePolicies = []int{2, 5, 29, 32} 1221 oidExtensionNameConstraints = []int{2, 5, 29, 30} 1222 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31} 1223 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1} 1224 oidExtensionCRLNumber = []int{2, 5, 29, 20} 1225 1226 // 扩展签名算法OID,`1.3.6.1.4.1`是ISO分配给私人企业的节点,`60387`是向IANA申请到的企业ID(zhaochuninhefei),`1`是该企业下的子节点,`1`是该子节点下的扩展签名算法OID 1227 oidExtensionSignatureAlgorithm = []int{1, 3, 6, 1, 4, 1, 60387, 1, 1} 1228 ) 1229 1230 var ( 1231 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1} 1232 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2} 1233 ) 1234 1235 // oidNotInExtensions reports whether an extension with the given oid exists in 1236 // extensions. 1237 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool { 1238 for _, e := range extensions { 1239 if e.Id.Equal(oid) { 1240 return true 1241 } 1242 } 1243 return false 1244 } 1245 1246 // go1.15开始废弃CommonName,改为使用SAN(Subject Alternative Name)扩展。 1247 // marshalSANs marshals a list of addresses into a the contents of an X.509 1248 // SubjectAlternativeName extension. 1249 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) { 1250 var rawValues []asn1.RawValue 1251 for _, name := range dnsNames { 1252 if err := isIA5String(name); err != nil { 1253 return nil, err 1254 } 1255 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)}) 1256 } 1257 for _, email := range emailAddresses { 1258 if err := isIA5String(email); err != nil { 1259 return nil, err 1260 } 1261 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)}) 1262 } 1263 for _, rawIP := range ipAddresses { 1264 // If possible, we always want to encode IPv4 addresses in 4 bytes. 1265 ip := rawIP.To4() 1266 if ip == nil { 1267 ip = rawIP 1268 } 1269 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip}) 1270 } 1271 for _, uri := range uris { 1272 uriStr := uri.String() 1273 if err := isIA5String(uriStr); err != nil { 1274 return nil, err 1275 } 1276 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)}) 1277 } 1278 return asn1.Marshal(rawValues) 1279 } 1280 1281 func isIA5String(s string) error { 1282 for _, r := range s { 1283 // Per RFC5280 "IA5String is limited to the set of ASCII characters" 1284 if r > unicode.MaxASCII { 1285 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s) 1286 } 1287 } 1288 1289 return nil 1290 } 1291 1292 // 构建证书扩展信息 1293 func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) { 1294 // 扩展信息最大数量增加到11, 放置gmx509定义的签名算法 1295 ret = make([]pkix.Extension, 11 /* maximum number of elements. */) 1296 n := 0 1297 1298 // 添加KeyUsage 1299 if template.KeyUsage != 0 && 1300 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) { 1301 ret[n], err = marshalKeyUsage(template.KeyUsage) 1302 if err != nil { 1303 return nil, err 1304 } 1305 n++ 1306 } 1307 1308 // 添加ExtKeyUsage 1309 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) && 1310 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) { 1311 ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage) 1312 if err != nil { 1313 return nil, err 1314 } 1315 n++ 1316 } 1317 1318 // 添加BasicConstraints 1319 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) { 1320 ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero) 1321 if err != nil { 1322 return nil, err 1323 } 1324 n++ 1325 } 1326 1327 // 添加subjectKeyId 1328 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) { 1329 ret[n].Id = oidExtensionSubjectKeyId 1330 ret[n].Value, err = asn1.Marshal(subjectKeyId) 1331 if err != nil { 1332 return 1333 } 1334 n++ 1335 } 1336 1337 // 添加authorityKeyId 1338 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) { 1339 ret[n].Id = oidExtensionAuthorityKeyId 1340 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId}) 1341 if err != nil { 1342 return 1343 } 1344 n++ 1345 } 1346 1347 // 添加authorityInfoAccess 1348 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) && 1349 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) { 1350 ret[n].Id = oidExtensionAuthorityInfoAccess 1351 var aiaValues []authorityInfoAccess 1352 for _, name := range template.OCSPServer { 1353 aiaValues = append(aiaValues, authorityInfoAccess{ 1354 Method: oidAuthorityInfoAccessOcsp, 1355 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, 1356 }) 1357 } 1358 for _, name := range template.IssuingCertificateURL { 1359 aiaValues = append(aiaValues, authorityInfoAccess{ 1360 Method: oidAuthorityInfoAccessIssuers, 1361 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, 1362 }) 1363 } 1364 ret[n].Value, err = asn1.Marshal(aiaValues) 1365 if err != nil { 1366 return 1367 } 1368 n++ 1369 } 1370 1371 // 添加SAN 1372 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) && 1373 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) { 1374 ret[n].Id = oidExtensionSubjectAltName 1375 // From RFC 5280, Section 4.2.1.6: 1376 // “If the subject field contains an empty sequence ... then 1377 // subjectAltName extension ... is marked as critical” 1378 ret[n].Critical = subjectIsEmpty 1379 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs) 1380 if err != nil { 1381 return 1382 } 1383 n++ 1384 } 1385 1386 // 添加PolicyIdentifiers 1387 if len(template.PolicyIdentifiers) > 0 && 1388 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) { 1389 ret[n], err = marshalCertificatePolicies(template.PolicyIdentifiers) 1390 if err != nil { 1391 return nil, err 1392 } 1393 n++ 1394 } 1395 1396 // 添加NameConstraints 1397 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 || 1398 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 || 1399 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 || 1400 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) && 1401 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) { 1402 ret[n].Id = oidExtensionNameConstraints 1403 ret[n].Critical = template.PermittedDNSDomainsCritical 1404 1405 ipAndMask := func(ipNet *net.IPNet) []byte { 1406 maskedIP := ipNet.IP.Mask(ipNet.Mask) 1407 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask)) 1408 ipAndMask = append(ipAndMask, maskedIP...) 1409 ipAndMask = append(ipAndMask, ipNet.Mask...) 1410 return ipAndMask 1411 } 1412 1413 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) { 1414 var b cryptobyte.Builder 1415 1416 for _, name := range dns { 1417 if err = isIA5String(name); err != nil { 1418 return nil, err 1419 } 1420 1421 b.AddASN1(cryptobyteasn1.SEQUENCE, func(b *cryptobyte.Builder) { 1422 b.AddASN1(cryptobyteasn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) { 1423 b.AddBytes([]byte(name)) 1424 }) 1425 }) 1426 } 1427 1428 for _, ipNet := range ips { 1429 b.AddASN1(cryptobyteasn1.SEQUENCE, func(b *cryptobyte.Builder) { 1430 b.AddASN1(cryptobyteasn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) { 1431 b.AddBytes(ipAndMask(ipNet)) 1432 }) 1433 }) 1434 } 1435 1436 for _, email := range emails { 1437 if err = isIA5String(email); err != nil { 1438 return nil, err 1439 } 1440 1441 b.AddASN1(cryptobyteasn1.SEQUENCE, func(b *cryptobyte.Builder) { 1442 b.AddASN1(cryptobyteasn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) { 1443 b.AddBytes([]byte(email)) 1444 }) 1445 }) 1446 } 1447 1448 for _, uriDomain := range uriDomains { 1449 if err = isIA5String(uriDomain); err != nil { 1450 return nil, err 1451 } 1452 1453 b.AddASN1(cryptobyteasn1.SEQUENCE, func(b *cryptobyte.Builder) { 1454 b.AddASN1(cryptobyteasn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) { 1455 b.AddBytes([]byte(uriDomain)) 1456 }) 1457 }) 1458 } 1459 1460 return b.Bytes() 1461 } 1462 1463 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains) 1464 if err != nil { 1465 return nil, err 1466 } 1467 1468 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains) 1469 if err != nil { 1470 return nil, err 1471 } 1472 1473 var b cryptobyte.Builder 1474 b.AddASN1(cryptobyteasn1.SEQUENCE, func(b *cryptobyte.Builder) { 1475 if len(permitted) > 0 { 1476 b.AddASN1(cryptobyteasn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) { 1477 b.AddBytes(permitted) 1478 }) 1479 } 1480 1481 if len(excluded) > 0 { 1482 b.AddASN1(cryptobyteasn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) { 1483 b.AddBytes(excluded) 1484 }) 1485 } 1486 }) 1487 1488 ret[n].Value, err = b.Bytes() 1489 if err != nil { 1490 return nil, err 1491 } 1492 n++ 1493 } 1494 1495 // 添加CRLDistributionPoints 1496 if len(template.CRLDistributionPoints) > 0 && 1497 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) { 1498 ret[n].Id = oidExtensionCRLDistributionPoints 1499 1500 var crlDp []distributionPoint 1501 for _, name := range template.CRLDistributionPoints { 1502 dp := distributionPoint{ 1503 DistributionPoint: distributionPointName{ 1504 FullName: []asn1.RawValue{ 1505 {Tag: 6, Class: 2, Bytes: []byte(name)}, 1506 }, 1507 }, 1508 } 1509 crlDp = append(crlDp, dp) 1510 } 1511 1512 ret[n].Value, err = asn1.Marshal(crlDp) 1513 if err != nil { 1514 return 1515 } 1516 n++ 1517 } 1518 1519 // Adding another extension here? Remember to update the maximum number 1520 // of elements in the make() at the top of the function and the list of 1521 // template fields used in CreateCertificate documentation. 1522 1523 // TODO 添加gmx509的签名算法 SignatureAlgorithm 1524 if template.SignatureAlgorithm > 0 && !oidInExtensions(oidExtensionSignatureAlgorithm, template.ExtraExtensions) { 1525 zclog.Debugf("向x509证书写入扩展签名算法: %s", template.SignatureAlgorithm.String()) 1526 ret[n] = marshalSignatureAlgorithm(template.SignatureAlgorithm) 1527 n++ 1528 } 1529 1530 return append(ret[:n], template.ExtraExtensions...), nil 1531 } 1532 1533 func marshalSignatureAlgorithm(signAlg SignatureAlgorithm) pkix.Extension { 1534 val := make([]byte, 4) 1535 binary.BigEndian.PutUint32(val, uint32(signAlg)) 1536 ext := pkix.Extension{ 1537 Id: oidExtensionSignatureAlgorithm, 1538 Critical: false, 1539 Value: val, 1540 } 1541 return ext 1542 } 1543 1544 func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) { 1545 ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true} 1546 1547 var a [2]byte 1548 a[0] = reverseBitsInAByte(byte(ku)) 1549 a[1] = reverseBitsInAByte(byte(ku >> 8)) 1550 1551 l := 1 1552 if a[1] != 0 { 1553 l = 2 1554 } 1555 1556 bitString := a[:l] 1557 var err error 1558 ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)}) 1559 if err != nil { 1560 return ext, err 1561 } 1562 return ext, nil 1563 } 1564 1565 func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) { 1566 ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage} 1567 1568 oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages)) 1569 for i, u := range extUsages { 1570 if oid, ok := oidFromExtKeyUsage(u); ok { 1571 oids[i] = oid 1572 } else { 1573 return ext, errors.New("x509: unknown extended key usage") 1574 } 1575 } 1576 1577 copy(oids[len(extUsages):], unknownUsages) 1578 1579 var err error 1580 ext.Value, err = asn1.Marshal(oids) 1581 if err != nil { 1582 return ext, err 1583 } 1584 return ext, nil 1585 } 1586 1587 func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) { 1588 ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true} 1589 // Leaving MaxPathLen as zero indicates that no maximum path 1590 // length is desired, unless MaxPathLenZero is set. A value of 1591 // -1 causes encoding/asn1 to omit the value as desired. 1592 if maxPathLen == 0 && !maxPathLenZero { 1593 maxPathLen = -1 1594 } 1595 var err error 1596 ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen}) 1597 if err != nil { 1598 return ext, nil 1599 } 1600 return ext, nil 1601 } 1602 1603 func marshalCertificatePolicies(policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) { 1604 ext := pkix.Extension{Id: oidExtensionCertificatePolicies} 1605 policies := make([]policyInformation, len(policyIdentifiers)) 1606 for i, policy := range policyIdentifiers { 1607 policies[i].Policy = policy 1608 } 1609 var err error 1610 ext.Value, err = asn1.Marshal(policies) 1611 if err != nil { 1612 return ext, err 1613 } 1614 return ext, nil 1615 } 1616 1617 func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error) { 1618 var ret []pkix.Extension 1619 1620 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) && 1621 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) { 1622 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs) 1623 if err != nil { 1624 return nil, err 1625 } 1626 1627 ret = append(ret, pkix.Extension{ 1628 Id: oidExtensionSubjectAltName, 1629 Value: sanBytes, 1630 }) 1631 } 1632 1633 // 添加 oidExtensionSignatureAlgorithm 1634 if template.SignatureAlgorithm > 0 && !oidInExtensions(oidExtensionSignatureAlgorithm, template.ExtraExtensions) { 1635 ret = append(ret, marshalSignatureAlgorithm(template.SignatureAlgorithm)) 1636 } 1637 1638 return append(ret, template.ExtraExtensions...), nil 1639 } 1640 1641 // 获取证书主题subject(证书拥有者)的字节数组 1642 func subjectBytes(cert *Certificate) ([]byte, error) { 1643 if len(cert.RawSubject) > 0 { 1644 return cert.RawSubject, nil 1645 } 1646 1647 return asn1.Marshal(cert.Subject.ToRDNSequence()) 1648 } 1649 1650 // signingParamsForPublicKey 根据传入的公钥与签名算法获取签名参数(签名算法、散列算法与签名算法参数) 1651 // 根据传入的公钥获取默认的签名参数,再根据传入的requestedSigAlgo从内建定义的签名算法列表中检查公钥类型是否匹配,并获取定义好的签名参数,覆盖之前的默认值。 1652 // 当requestedSigAlgo传入0时,即只根据公钥获取默认的签名参数。 1653 // 注意公钥必须是签署者使用的私钥对应的公钥,并不是证书拥有者的公钥。 1654 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (signOpts crypto.SignerOpts, hashFunc Hash, sigAlgo pkix.AlgorithmIdentifier, err error) { 1655 var pubType PublicKeyAlgorithm 1656 1657 // 根据pub的公钥类型选择签名算法参数的默认值 1658 switch pub := pub.(type) { 1659 case *sm2.PublicKey: 1660 pubType = SM2 1661 // 检查曲线是否是sm2曲线 1662 switch pub.Curve { 1663 case sm2.P256Sm2(): 1664 // 摘要算法 1665 hashFunc = Hash(0) 1666 // 签名算法 1667 sigAlgo.Algorithm = oidSignatureSM2WithSM3 1668 // 签名参数 sm2默认做ZA混合散列,不需要low-s处理 1669 signOpts = sm2.DefaultSM2SignerOption() 1670 default: 1671 err = errors.New("x509: unknown SM2 curve") 1672 } 1673 // 公钥是sm2时,只有一种签名算法和散列算法可以选择,这里其实可以直接返回。 1674 // 但为了扩展性以及对内建签名算法列表的检查,还是在后续做一次根据requestedSigAlgo的算法匹配检查。 1675 case *rsa.PublicKey: 1676 pubType = RSA 1677 // 公钥是rsa时并不能确定具体的签名算法与散列算法,这里先准备默认值 1678 // 传入的requestedSigAlgo非0时,后续会根据签名算法覆盖具体的签名算法与散列算法 1679 hashFunc = SHA256 1680 sigAlgo.Algorithm = oidSignatureSHA256WithRSA 1681 sigAlgo.Parameters = asn1.NullRawValue 1682 signOpts = SHA256 1683 case *ecdsa.PublicKey: 1684 pubType = ECDSA 1685 // 公钥是ecdsa时并不能确定具体的签名算法与散列算法,这里先根据曲线准备默认值 1686 // 传入的requestedSigAlgo非0时,后续会根据签名算法覆盖具体的签名算法与散列算法 1687 switch pub.Curve { 1688 case elliptic.P224(), elliptic.P256(): 1689 hashFunc = SHA256 1690 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256 1691 case elliptic.P384(): 1692 hashFunc = SHA384 1693 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384 1694 case elliptic.P521(): 1695 hashFunc = SHA512 1696 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512 1697 default: 1698 err = errors.New("x509: unknown elliptic curve") 1699 } 1700 // ecdsa签名默认不做low-s处理 1701 signOpts = ecbase.CreateEcSignerOpts(crypto.Hash(hashFunc), false) 1702 case *ecdsa_ext.PublicKey: 1703 pubType = ECDSAEXT 1704 // 公钥是ecdsa时并不能确定具体的签名算法与散列算法,这里先根据曲线准备默认值 1705 // 传入的requestedSigAlgo非0时,后续会根据签名算法覆盖具体的签名算法与散列算法 1706 switch pub.Curve { 1707 case elliptic.P224(), elliptic.P256(): 1708 hashFunc = SHA256 1709 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256 1710 case elliptic.P384(): 1711 hashFunc = SHA384 1712 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384 1713 case elliptic.P521(): 1714 hashFunc = SHA512 1715 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512 1716 default: 1717 err = errors.New("x509: unknown elliptic curve") 1718 } 1719 // ecdsa_ext签名默认做low-s处理 1720 signOpts = ecbase.CreateEcSignerOpts(crypto.Hash(hashFunc), true) 1721 1722 case ed25519.PublicKey: 1723 pubType = Ed25519 1724 sigAlgo.Algorithm = oidSignatureEd25519 1725 // ed25519不需要事先散列消息 1726 hashFunc = Hash(0) 1727 signOpts = hashFunc 1728 // ed25519与sm2一样,其实到这里已经可以直接返回了。 1729 // 但为了扩展性以及对内建签名算法列表的检查,还是在后续做一次根据requestedSigAlgo的算法匹配检查。 1730 1731 default: 1732 err = errors.New("x509: only SM2, RSA, ECDSA and Ed25519 keys supported") 1733 } 1734 1735 if err != nil { 1736 // 公钥获取参数失败时直接返回错误 1737 return signOpts, hashFunc, sigAlgo, err 1738 } 1739 if requestedSigAlgo == 0 { 1740 // 如果请求签名算法requestedSigAlgo为0,则直接返回公钥获取到的默认的签名参数 1741 return signOpts, hashFunc, sigAlgo, err 1742 } 1743 1744 // 根据请求签名算法requestedSigAlgo匹配签名算法 1745 found := false 1746 for _, details := range signatureAlgorithmDetails { 1747 // 在内建的signatureAlgorithmDetails中匹配参数requestedSigAlgo 1748 if details.algo == requestedSigAlgo { 1749 // 检查匹配到的算法定义是否与传入的公钥类型匹配 1750 if details.pubKeyAlgo != pubType { 1751 err = errors.New("x509: requested SignatureAlgorithm does not match private key type") 1752 return 1753 } 1754 // 根据匹配到的算法定义覆盖签名算法与散列算法 1755 sigAlgo.Algorithm, hashFunc, signOpts = details.oid, details.hash, details.opts 1756 // hashFunc定义为0时检查是不是Ed25519或SM2,只有这两个签名算法不需要事先散列 1757 if hashFunc == 0 && pubType != Ed25519 && pubType != SM2 { 1758 err = errors.New("x509: cannot sign with hash function requested") 1759 return 1760 } 1761 // RSAPSS系列算法的特殊处理 1762 if requestedSigAlgo.isRSAPSS() { 1763 sigAlgo.Parameters = hashToPSSParameters[hashFunc] 1764 } 1765 found = true 1766 break 1767 } 1768 } 1769 1770 if !found { 1771 err = errors.New("x509: unknown SignatureAlgorithm") 1772 } 1773 1774 return 1775 } 1776 1777 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is 1778 // just an empty SEQUENCE. 1779 var emptyASN1Subject = []byte{0x30, 0} 1780 1781 // CreateCertificate 根据证书模板生成gmx509证书(v3)的DER字节数组 1782 // - template : 证书模板 1783 // - parent : 父证书(自签名时与template传入相同参数即可) 1784 // - pub : 证书拥有者的公钥 1785 // - priv : 签名者的私钥(有父证书的话,就是父证书拥有者的私钥) 1786 // 1787 // 当父证书中含有公钥时,必须确保签名者私钥中的公钥与其一致。 1788 // 1789 // CreateCertificate creates a new X.509 v3 certificate based on a template. 1790 // The following members of template are currently used: 1791 // 1792 // - AuthorityKeyId 1793 // - BasicConstraintsValid 1794 // - CRLDistributionPoints 1795 // - DNSNames 1796 // - EmailAddresses 1797 // - ExcludedDNSDomains 1798 // - ExcludedEmailAddresses 1799 // - ExcludedIPRanges 1800 // - ExcludedURIDomains 1801 // - ExtKeyUsage 1802 // - ExtraExtensions 1803 // - IPAddresses 1804 // - IsCA 1805 // - IssuingCertificateURL 1806 // - KeyUsage 1807 // - MaxPathLen 1808 // - MaxPathLenZero 1809 // - NotAfter 1810 // - NotBefore 1811 // - OCSPServer 1812 // - PermittedDNSDomains 1813 // - PermittedDNSDomainsCritical 1814 // - PermittedEmailAddresses 1815 // - PermittedIPRanges 1816 // - PermittedURIDomains 1817 // - PolicyIdentifiers 1818 // - SerialNumber 1819 // - SignatureAlgorithm 1820 // - Subject 1821 // - SubjectKeyId 1822 // - URIs 1823 // - UnknownExtKeyUsage 1824 // 1825 // The certificate is signed by parent. If parent is equal to template then the 1826 // certificate is self-signed. The parameter pub is the public key of the 1827 // certificate to be generated and priv is the private key of the signer. 1828 // 1829 // The returned slice is the certificate in DER encoding. 1830 // 1831 // The currently supported key types are *sm2.PublicKey, *rsa.PublicKey, *ecdsa.PublicKey and 1832 // ed25519.PublicKey. pub must be a supported key type, and priv must be a 1833 // crypto.Signer with a supported public key. 1834 // 1835 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any, 1836 // unless the resulting certificate is self-signed. Otherwise the value from 1837 // template will be used. 1838 // 1839 // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId 1840 // will be generated from the hash of the public key. 1841 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) ([]byte, error) { 1842 // 检查签名者私钥是否实现了`crypto.Signer`接口 1843 key, ok := priv.(crypto.Signer) 1844 if !ok { 1845 return nil, errors.New("x509: certificate private key does not implement crypto.Signer") 1846 } 1847 // 检查模板是否有SerialNumber 1848 if template.SerialNumber == nil { 1849 return nil, errors.New("x509: no SerialNumber given") 1850 } 1851 // 检查MaxPathLen,只有CA证书才允许设置MaxPathLen 1852 if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) { 1853 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen") 1854 } 1855 // 根据签名者的公钥以及证书模板的签名算法配置推导本次新证书签名中使用的散列算法与签名算法 1856 signOpts, hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm) 1857 if err != nil { 1858 return nil, err 1859 } 1860 // 将新证书拥有者的公钥转为证书公钥字节数组与证书公钥算法 (新证书的核心内容) 1861 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub) 1862 if err != nil { 1863 return nil, err 1864 } 1865 // 从父证书获取证书签署者字节数组 1866 asn1Issuer, err := subjectBytes(parent) 1867 if err != nil { 1868 return nil, err 1869 } 1870 // 从证书模板获取证书拥有者字节数组 1871 asn1Subject, err := subjectBytes(template) 1872 if err != nil { 1873 return nil, err 1874 } 1875 // 设置签署者密钥ID 1876 authorityKeyId := template.AuthorityKeyId 1877 // 非自签名且父证书的SubjectKeyId非空时,将父证书的 SubjectKeyId 设置为新证书的 AuthorityKeyId 1878 // 即新证书的签署者密钥ID就是父证书的拥有者密钥ID 1879 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 { 1880 authorityKeyId = parent.SubjectKeyId 1881 } 1882 // 设置拥有者密钥ID 1883 subjectKeyId := template.SubjectKeyId 1884 // 当证书模板没有设置拥有者密钥ID,且本证书为CA证书时,自行计算拥有者密钥ID 1885 if len(subjectKeyId) == 0 && template.IsCA { 1886 // SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2: 1887 // (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the 1888 // value of the BIT STRING subjectPublicKey (excluding the tag, 1889 // length, and number of unused bits). 1890 // 国密改造:改为sm3散列 1891 // h := sha1.Sum(publicKeyBytes) 1892 h := sm3.Sm3Sum(publicKeyBytes) 1893 subjectKeyId = h[:] 1894 } 1895 1896 // 检查签署者私钥是否匹配父证书中的公钥 1897 // Check that the signer's public key matches the private key, if available. 1898 type publicKey interface { 1899 Equal(crypto.PublicKey) bool 1900 } 1901 if privPub, ok := key.Public().(publicKey); !ok { 1902 return nil, errors.New("x509: internal error: supported public key does not implement Equal") 1903 } else if parent.PublicKey != nil && !privPub.Equal(parent.PublicKey) { 1904 return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey") 1905 } 1906 // 构建本证书的扩展信息 1907 extensions, err := buildCertExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId) 1908 if err != nil { 1909 return nil, err 1910 } 1911 // 构建证书主体,即签名的内容 1912 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes} 1913 c := tbsCertificate{ 1914 Version: 2, 1915 SerialNumber: template.SerialNumber, 1916 SignatureAlgorithm: signatureAlgorithm, 1917 Issuer: asn1.RawValue{FullBytes: asn1Issuer}, 1918 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()}, 1919 Subject: asn1.RawValue{FullBytes: asn1Subject}, 1920 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey}, 1921 Extensions: extensions, 1922 } 1923 // 证书主体字节数组 1924 tbsCertContents, err := asn1.Marshal(c) 1925 if err != nil { 1926 return nil, err 1927 } 1928 c.Raw = tbsCertContents 1929 // 签名前对签名内容做一次散列 1930 signed := tbsCertContents 1931 // 签名算法为sm2withsm3时,在其内部做散列,对应的hashFunc为0 1932 if hashFunc != 0 { 1933 h := hashFunc.New() 1934 h.Write(signed) 1935 signed = h.Sum(nil) 1936 // TODO 打印散列算法 1937 zclog.Debugf("x509.CreateCertificate 对签名内容做散列的算法是: %s", hashFunc.String()) 1938 } 1939 //// 签名需要将散列函数作为signerOpts传入 1940 //var signerOpts crypto.SignerOpts = hashFunc 1941 //// rsa的特殊处理 1942 //if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() { 1943 // signerOpts = &rsa.PSSOptions{ 1944 // SaltLength: rsa.PSSSaltLengthEqualsHash, 1945 // Hash: hashFunc.HashFunc(), 1946 // } 1947 //} 1948 // 签名 1949 var signature []byte 1950 signature, err = key.Sign(rand, signed, signOpts) 1951 if err != nil { 1952 return nil, err 1953 } 1954 // ecdsa签名做low-s处理 1955 if ecSignOpts, ok := signOpts.(ecbase.EcSignerOpts); ok { 1956 if ecSignOpts.NeedLowS() { 1957 // 对于ecdsa签名算法,如果指定了要做 low-s处理,那么这里需要针对使用`*ecdsa.PrivateKey`的场景做补丁处理。 1958 // 而如果使用的是`*ecdsa_ext.PrivateKey`,其内部已经根据EcSignerOpts参数做过low-s了,这里不需要额外再做一次。 1959 if ecdsaPriv, ok := key.(*ecdsa.PrivateKey); ok { 1960 zclog.Debugln("x509证书签署后尝试low-s处理") 1961 doLow := false 1962 doLow, signature, err = ecdsa_ext.SignatureToLowS(&ecdsaPriv.PublicKey, signature) 1963 if err != nil { 1964 return nil, err 1965 } 1966 if doLow { 1967 zclog.Debugln("x509证书签署后完成low-s处理") 1968 } 1969 } 1970 } 1971 } 1972 zclog.Debugf("x509签名结果, 签名内容: %s, 签名: %s", hex.EncodeToString(signed), hex.EncodeToString(signature)) 1973 // 构建证书(证书主体 + 签名算法 + 签名),并转为字节数组 1974 signedCert, err := asn1.Marshal(certificate{ 1975 nil, 1976 c, 1977 signatureAlgorithm, 1978 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 1979 }) 1980 if err != nil { 1981 return nil, err 1982 } 1983 1984 // Check the signature to ensure the crypto.Signer behaved correctly. 1985 // We skip this check if the signature algorithm is MD5WithRSA as we 1986 // only support this algorithm for signing, and not verification. 1987 if sigAlg := getSignatureAlgorithmFromAI(signatureAlgorithm); sigAlg != MD5WithRSA { 1988 // 检查签名是否正确,注意此时使用签署者的公钥来验签 1989 if err := checkSignature(sigAlg, c.Raw, signature, key.Public()); err != nil { 1990 return nil, fmt.Errorf("x509: signature over certificate returned by signer is invalid: %w", err) 1991 } 1992 } 1993 1994 return signedCert, nil 1995 } 1996 1997 // CRL 证书吊销列表(Certificate Revocation List) 相关操作 1998 1999 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded 2000 // CRL. 2001 var pemCRLPrefix = []byte("-----BEGIN X509 CRL") 2002 2003 // pemType is the type of a PEM encoded CRL. 2004 var pemType = "X509 CRL" 2005 2006 // ParseCRL 将给定的字节数组(PEM/DER)转为CRL。 2007 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM 2008 // encoded CRLs will appear where they should be DER encoded, so this function 2009 // will transparently handle PEM encoding as long as there isn't any leading 2010 // garbage. 2011 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) { 2012 if bytes.HasPrefix(crlBytes, pemCRLPrefix) { 2013 block, _ := pem.Decode(crlBytes) 2014 if block != nil && block.Type == pemType { 2015 crlBytes = block.Bytes 2016 } 2017 } 2018 return ParseDERCRL(crlBytes) 2019 } 2020 2021 // ParseDERCRL 将DER字节数组转为CRL。 2022 // ParseDERCRL parses a DER encoded CRL from the given bytes. 2023 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) { 2024 certList := new(pkix.CertificateList) 2025 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil { 2026 return nil, err 2027 } else if len(rest) != 0 { 2028 return nil, errors.New("x509: trailing data after CRL") 2029 } 2030 return certList, nil 2031 } 2032 2033 // CreateCRL 创建一个CRL 2034 // - priv : 撤销证书列表的签署者私钥, 如果是ecdsa私钥,那么这里并不支持low-s处理,验签时对应也不需要low-s检查。 2035 // - revokedCerts : 撤销证书列表 2036 // 2037 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that 2038 // contains the given list of revoked certificates. 2039 // 2040 // Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL. 2041 // To generate a standards compliant CRL, use CreateRevocationList instead. 2042 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) { 2043 key, ok := priv.(crypto.Signer) 2044 if !ok { 2045 return nil, errors.New("x509: certificate private key does not implement crypto.Signer") 2046 } 2047 // 使用签署者的公钥获取签名参数: 散列函数与签名算法 2048 signOpts, hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0) 2049 if err != nil { 2050 return nil, err 2051 } 2052 2053 // Force revocation times to UTC per RFC 5280. 2054 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts)) 2055 for i, rc := range revokedCerts { 2056 rc.RevocationTime = rc.RevocationTime.UTC() 2057 revokedCertsUTC[i] = rc 2058 } 2059 2060 tbsCertList := pkix.TBSCertificateList{ 2061 Version: 1, 2062 Signature: signatureAlgorithm, 2063 Issuer: c.Subject.ToRDNSequence(), 2064 ThisUpdate: now.UTC(), 2065 NextUpdate: expiry.UTC(), 2066 RevokedCertificates: revokedCertsUTC, 2067 } 2068 2069 // Authority Key Id 2070 if len(c.SubjectKeyId) > 0 { 2071 var aki pkix.Extension 2072 aki.Id = oidExtensionAuthorityKeyId 2073 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId}) 2074 if err != nil { 2075 return 2076 } 2077 tbsCertList.Extensions = append(tbsCertList.Extensions, aki) 2078 } 2079 2080 tbsCertListContents, err := asn1.Marshal(tbsCertList) 2081 if err != nil { 2082 return 2083 } 2084 2085 signed := tbsCertListContents 2086 if hashFunc != 0 { 2087 h := hashFunc.New() 2088 h.Write(signed) 2089 signed = h.Sum(nil) 2090 } 2091 2092 var signature []byte 2093 signature, err = key.Sign(rand, signed, signOpts) 2094 if err != nil { 2095 return 2096 } 2097 //// ecdsa签名做low-s处理 2098 //if ecSignOpts, ok := signOpts.(ecbase.EcSignerOpts); ok { 2099 // if ecSignOpts.NeedLowS() { 2100 // // 对于ecdsa签名算法,如果指定了要做 low-s处理,那么这里需要针对使用`*ecdsa.PrivateKey`的场景做补丁处理。 2101 // // 而如果使用的是`*ecdsa_ext.PrivateKey`,其内部已经根据EcSignerOpts参数做过low-s了,这里不需要额外再做一次。 2102 // if ecdsaPriv, ok := key.(*ecdsa.PrivateKey); ok { 2103 // zclog.Debugln("x509证书签署后尝试low-s处理") 2104 // doLow := false 2105 // doLow, signature, err = ecdsa_ext.SignatureToLowS(&ecdsaPriv.PublicKey, signature) 2106 // if err != nil { 2107 // return nil, err 2108 // } 2109 // if doLow { 2110 // zclog.Debugln("x509证书签署后完成low-s处理") 2111 // } 2112 // } 2113 // } 2114 //} 2115 2116 return asn1.Marshal(pkix.CertificateList{ 2117 TBSCertList: tbsCertList, 2118 SignatureAlgorithm: signatureAlgorithm, 2119 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 2120 }) 2121 } 2122 2123 // CertificateRequest 证书申请 2124 // CertificateRequest represents a PKCS #10, certificate signature request. 2125 type CertificateRequest struct { 2126 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature). 2127 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content. 2128 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo. 2129 RawSubject []byte // DER encoded Subject. 2130 2131 Version int 2132 Signature []byte 2133 SignatureAlgorithm SignatureAlgorithm 2134 2135 PublicKeyAlgorithm PublicKeyAlgorithm 2136 PublicKey interface{} 2137 2138 Subject pkix.Name 2139 2140 // Attributes contains the CSR attributes that can parse as 2141 // pkix.AttributeTypeAndValueSET. 2142 // 2143 // Deprecated: Use Extensions and ExtraExtensions instead for parsing and 2144 // generating the requestedExtensions attribute. 2145 Attributes []pkix.AttributeTypeAndValueSET 2146 2147 // Extensions contains all requested extensions, in raw form. When parsing 2148 // CSRs, this can be used to extract extensions that are not parsed by this 2149 // package. 2150 Extensions []pkix.Extension 2151 2152 // ExtraExtensions contains extensions to be copied, raw, into any CSR 2153 // marshaled by CreateCertificateRequest. Values override any extensions 2154 // that would otherwise be produced based on the other fields but are 2155 // overridden by any extensions specified in Attributes. 2156 // 2157 // The ExtraExtensions field is not populated by ParseCertificateRequest, 2158 // see Extensions instead. 2159 ExtraExtensions []pkix.Extension 2160 2161 // Subject Alternate Name values. 2162 // go1.15开始废弃CommonName,使用SAN扩展信息。 2163 // SAN扩展信息由下面四个字段组成。 2164 DNSNames []string 2165 EmailAddresses []string 2166 IPAddresses []net.IP 2167 URIs []*url.URL 2168 } 2169 2170 // These structures reflect the ASN.1 structure of X.509 certificate 2171 // signature requests (see RFC 2986): 2172 2173 type tbsCertificateRequest struct { 2174 Raw asn1.RawContent 2175 Version int 2176 Subject asn1.RawValue 2177 PublicKey publicKeyInfo 2178 RawAttributes []asn1.RawValue `asn1:"tag:0"` 2179 } 2180 2181 type certificateRequest struct { 2182 Raw asn1.RawContent 2183 TBSCSR tbsCertificateRequest 2184 SignatureAlgorithm pkix.AlgorithmIdentifier 2185 SignatureValue asn1.BitString 2186 } 2187 2188 // oidExtensionRequest is a PKCS #9 OBJECT IDENTIFIER that indicates requested 2189 // extensions in a CSR. 2190 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14} 2191 2192 // newRawAttributes converts AttributeTypeAndValueSETs from a template 2193 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes. 2194 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) { 2195 var rawAttributes []asn1.RawValue 2196 b, err := asn1.Marshal(attributes) 2197 if err != nil { 2198 return nil, err 2199 } 2200 rest, err := asn1.Unmarshal(b, &rawAttributes) 2201 if err != nil { 2202 return nil, err 2203 } 2204 if len(rest) != 0 { 2205 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes") 2206 } 2207 return rawAttributes, nil 2208 } 2209 2210 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs. 2211 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET { 2212 var attributes []pkix.AttributeTypeAndValueSET 2213 for _, rawAttr := range rawAttributes { 2214 var attr pkix.AttributeTypeAndValueSET 2215 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr) 2216 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET 2217 // (i.e.: challengePassword or unstructuredName). 2218 if err == nil && len(rest) == 0 { 2219 attributes = append(attributes, attr) 2220 } 2221 } 2222 return attributes 2223 } 2224 2225 // parseCSRExtensions parses the attributes from a CSR and extracts any 2226 // requested extensions. 2227 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) { 2228 // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1. 2229 type pkcs10Attribute struct { 2230 Id asn1.ObjectIdentifier 2231 Values []asn1.RawValue `asn1:"set"` 2232 } 2233 2234 var ret []pkix.Extension 2235 for _, rawAttr := range rawAttributes { 2236 var attr pkcs10Attribute 2237 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 { 2238 // Ignore attributes that don't parse. 2239 continue 2240 } 2241 2242 if !attr.Id.Equal(oidExtensionRequest) { 2243 continue 2244 } 2245 2246 var extensions []pkix.Extension 2247 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil { 2248 return nil, err 2249 } 2250 ret = append(ret, extensions...) 2251 } 2252 2253 return ret, nil 2254 } 2255 2256 // CreateCertificateRequest 基于证书申请模板生成一个新的证书申请。 2257 // 注意,证书申请内部的公钥信息就是签名者的公钥,即,证书申请是申请者自签名的。 2258 // - rand : 随机数获取用 2259 // - template : 证书申请模板 2260 // - priv : 申请者私钥 2261 // 2262 // CreateCertificateRequest creates a new certificate request based on a 2263 // template. The following members of template are used: 2264 // 2265 // - SignatureAlgorithm 2266 // - Subject 2267 // - DNSNames 2268 // - EmailAddresses 2269 // - IPAddresses 2270 // - URIs 2271 // - ExtraExtensions 2272 // - Attributes (deprecated) 2273 // 2274 // priv is the private key to sign the CSR with, and the corresponding public 2275 // key will be included in the CSR. It must implement crypto.Signer and its 2276 // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a 2277 // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or 2278 // ed25519.PrivateKey satisfies this.) 2279 // 2280 // The returned slice is the certificate request in DER encoding. 2281 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) { 2282 key, ok := priv.(crypto.Signer) 2283 if !ok { 2284 return nil, errors.New("x509: certificate private key does not implement crypto.Signer") 2285 } 2286 // 根据申请者的公钥与模板的签名算法获取散列函数与签名算法 2287 var signOpts crypto.SignerOpts 2288 var hashFunc Hash 2289 var sigAlgo pkix.AlgorithmIdentifier 2290 signOpts, hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm) 2291 if err != nil { 2292 return nil, err 2293 } 2294 // 根据申请者的公钥生成证书申请的核心内容:公钥字节数组与公钥算法 2295 var publicKeyBytes []byte 2296 var publicKeyAlgorithm pkix.AlgorithmIdentifier 2297 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public()) 2298 if err != nil { 2299 return nil, err 2300 } 2301 // 构建证书申请扩展内容 2302 extensions, err := buildCSRExtensions(template) 2303 if err != nil { 2304 return nil, err 2305 } 2306 // Make a copy of template.Attributes because we may alter it below. 2307 //goland:noinspection GoDeprecation 2308 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes)) 2309 //goland:noinspection GoDeprecation 2310 for _, attr := range template.Attributes { 2311 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value)) 2312 copy(values, attr.Value) 2313 attributes = append(attributes, pkix.AttributeTypeAndValueSET{ 2314 Type: attr.Type, 2315 Value: values, 2316 }) 2317 } 2318 extensionsAppended := false 2319 if len(extensions) > 0 { 2320 // Append the extensions to an existing attribute if possible. 2321 for _, atvSet := range attributes { 2322 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 { 2323 continue 2324 } 2325 // specifiedExtensions contains all the extensions that we 2326 // found specified via template.Attributes. 2327 specifiedExtensions := make(map[string]bool) 2328 for _, atvs := range atvSet.Value { 2329 for _, atv := range atvs { 2330 specifiedExtensions[atv.Type.String()] = true 2331 } 2332 } 2333 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions)) 2334 newValue = append(newValue, atvSet.Value[0]...) 2335 for _, e := range extensions { 2336 if specifiedExtensions[e.Id.String()] { 2337 // Attributes already contained a value for 2338 // this extension and it takes priority. 2339 continue 2340 } 2341 newValue = append(newValue, pkix.AttributeTypeAndValue{ 2342 // There is no place for the critical 2343 // flag in an AttributeTypeAndValue. 2344 Type: e.Id, 2345 Value: e.Value, 2346 }) 2347 } 2348 atvSet.Value[0] = newValue 2349 extensionsAppended = true 2350 break 2351 } 2352 } 2353 rawAttributes, err := newRawAttributes(attributes) 2354 if err != nil { 2355 return 2356 } 2357 // If not included in attributes, add a new attribute for the 2358 // extensions. 2359 if len(extensions) > 0 && !extensionsAppended { 2360 attr := struct { 2361 Type asn1.ObjectIdentifier 2362 Value [][]pkix.Extension `asn1:"set"` 2363 }{ 2364 Type: oidExtensionRequest, 2365 Value: [][]pkix.Extension{extensions}, 2366 } 2367 b, err := asn1.Marshal(attr) 2368 if err != nil { 2369 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error()) 2370 } 2371 var rawValue asn1.RawValue 2372 if _, err := asn1.Unmarshal(b, &rawValue); err != nil { 2373 return nil, err 2374 } 2375 rawAttributes = append(rawAttributes, rawValue) 2376 } 2377 // 证书申请者信息 2378 asn1Subject := template.RawSubject 2379 if len(asn1Subject) == 0 { 2380 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence()) 2381 if err != nil { 2382 return nil, err 2383 } 2384 } 2385 // 签名内容 2386 tbsCSR := tbsCertificateRequest{ 2387 Version: 0, // PKCS #10, RFC 2986 2388 Subject: asn1.RawValue{FullBytes: asn1Subject}, 2389 PublicKey: publicKeyInfo{ 2390 Algorithm: publicKeyAlgorithm, 2391 PublicKey: asn1.BitString{ 2392 Bytes: publicKeyBytes, 2393 BitLength: len(publicKeyBytes) * 8, 2394 }, 2395 }, 2396 RawAttributes: rawAttributes, 2397 } 2398 tbsCSRContents, err := asn1.Marshal(tbsCSR) 2399 if err != nil { 2400 return 2401 } 2402 tbsCSR.Raw = tbsCSRContents 2403 // 签名内容进行一次散列 2404 signed := tbsCSRContents 2405 if hashFunc != 0 { 2406 h := hashFunc.New() 2407 h.Write(signed) 2408 signed = h.Sum(nil) 2409 } 2410 // 签名,注意,证书申请都是申请者自签名。 2411 var signature []byte 2412 signature, err = key.Sign(rand, signed, signOpts) 2413 if err != nil { 2414 return 2415 } 2416 // ecdsa签名做low-s处理 2417 if ecSignOpts, ok := signOpts.(ecbase.EcSignerOpts); ok { 2418 if ecSignOpts.NeedLowS() { 2419 // 对于ecdsa签名算法,如果指定了要做 low-s处理,那么这里需要针对使用`*ecdsa.PrivateKey`的场景做补丁处理。 2420 // 而如果使用的是`*ecdsa_ext.PrivateKey`,其内部已经根据EcSignerOpts参数做过low-s了,这里不需要额外再做一次。 2421 if ecdsaPriv, ok := key.(*ecdsa.PrivateKey); ok { 2422 zclog.Debugln("x509证书签署后尝试low-s处理") 2423 doLow := false 2424 doLow, signature, err = ecdsa_ext.SignatureToLowS(&ecdsaPriv.PublicKey, signature) 2425 if err != nil { 2426 return nil, err 2427 } 2428 if doLow { 2429 zclog.Debugln("x509证书签署后完成low-s处理") 2430 } 2431 } 2432 } 2433 } 2434 // 返回证书申请DER字节数组 2435 return asn1.Marshal(certificateRequest{ 2436 TBSCSR: tbsCSR, 2437 SignatureAlgorithm: sigAlgo, 2438 SignatureValue: asn1.BitString{ 2439 Bytes: signature, 2440 BitLength: len(signature) * 8, 2441 }, 2442 }) 2443 } 2444 2445 // ParseCertificateRequest 将DER字节数组转为单个证书申请。 2446 // ParseCertificateRequest parses a single certificate request from the 2447 // given ASN.1 DER data. 2448 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) { 2449 var csr certificateRequest 2450 2451 rest, err := asn1.Unmarshal(asn1Data, &csr) 2452 if err != nil { 2453 return nil, err 2454 } else if len(rest) != 0 { 2455 return nil, asn1.SyntaxError{Msg: "trailing data"} 2456 } 2457 2458 return parseCertificateRequest(&csr) 2459 } 2460 2461 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) { 2462 //goland:noinspection GoDeprecation 2463 out := &CertificateRequest{ 2464 Raw: in.Raw, 2465 RawTBSCertificateRequest: in.TBSCSR.Raw, 2466 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw, 2467 RawSubject: in.TBSCSR.Subject.FullBytes, 2468 2469 Signature: in.SignatureValue.RightAlign(), 2470 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm), 2471 2472 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm), 2473 2474 Version: in.TBSCSR.Version, 2475 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes), 2476 } 2477 2478 var err error 2479 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey) 2480 if err != nil { 2481 return nil, err 2482 } 2483 2484 var subject pkix.RDNSequence 2485 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil { 2486 return nil, err 2487 } else if len(rest) != 0 { 2488 return nil, errors.New("x509: trailing data after X.509 Subject") 2489 } 2490 2491 out.Subject.FillFromRDNSequence(&subject) 2492 2493 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil { 2494 return nil, err 2495 } 2496 2497 for _, extension := range out.Extensions { 2498 switch { 2499 case extension.Id.Equal(oidExtensionSubjectAltName): 2500 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value) 2501 if err != nil { 2502 return nil, err 2503 } 2504 case extension.Id.Equal(oidExtensionSignatureAlgorithm): 2505 // SignatureAlgorithm反序列化操作 2506 signAlg := SignatureAlgorithm(binary.BigEndian.Uint32(extension.Value)) 2507 if signAlg > 0 { 2508 out.SignatureAlgorithm = signAlg 2509 } 2510 } 2511 } 2512 2513 return out, nil 2514 } 2515 2516 // CheckSignature 检查证书申请c的签名是否有效 2517 // CheckSignature reports whether the signature on c is valid. 2518 func (c *CertificateRequest) CheckSignature() error { 2519 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey) 2520 } 2521 2522 // ToX509Certificate gmx509转x509 2523 func (c *Certificate) ToX509Certificate() *x509.Certificate { 2524 x509cert := &x509.Certificate{ 2525 Raw: c.Raw, 2526 RawTBSCertificate: c.RawTBSCertificate, 2527 RawSubjectPublicKeyInfo: c.RawSubjectPublicKeyInfo, 2528 RawSubject: c.RawSubject, 2529 RawIssuer: c.RawIssuer, 2530 Signature: c.Signature, 2531 SignatureAlgorithm: x509.SignatureAlgorithm(c.SignatureAlgorithm), 2532 PublicKeyAlgorithm: x509.PublicKeyAlgorithm(c.PublicKeyAlgorithm), 2533 PublicKey: c.PublicKey, 2534 Version: c.Version, 2535 SerialNumber: c.SerialNumber, 2536 Issuer: c.Issuer, 2537 Subject: c.Subject, 2538 NotBefore: c.NotBefore, 2539 NotAfter: c.NotAfter, 2540 KeyUsage: x509.KeyUsage(c.KeyUsage), 2541 Extensions: c.Extensions, 2542 ExtraExtensions: c.ExtraExtensions, 2543 UnhandledCriticalExtensions: c.UnhandledCriticalExtensions, 2544 // ExtKeyUsage: []x509.ExtKeyUsage(c.ExtKeyUsage) , 2545 UnknownExtKeyUsage: c.UnknownExtKeyUsage, 2546 BasicConstraintsValid: c.BasicConstraintsValid, 2547 IsCA: c.IsCA, 2548 MaxPathLen: c.MaxPathLen, 2549 // MaxPathLenZero indicates that BasicConstraintsValid==true and 2550 // MaxPathLen==0 should be interpreted as an actual maximum path length 2551 // of zero. Otherwise, that combination is interpreted as MaxPathLen 2552 // not being set. 2553 MaxPathLenZero: c.MaxPathLenZero, 2554 SubjectKeyId: c.SubjectKeyId, 2555 AuthorityKeyId: c.AuthorityKeyId, 2556 // RFC 5280, 4.2.2.1 (Authority Information Access) 2557 OCSPServer: c.OCSPServer, 2558 IssuingCertificateURL: c.IssuingCertificateURL, 2559 // Subject Alternate Name values 2560 DNSNames: c.DNSNames, 2561 EmailAddresses: c.EmailAddresses, 2562 IPAddresses: c.IPAddresses, 2563 URIs: c.URIs, 2564 // Name constraints 2565 PermittedDNSDomainsCritical: c.PermittedDNSDomainsCritical, 2566 PermittedDNSDomains: c.PermittedDNSDomains, 2567 ExcludedDNSDomains: c.ExcludedDNSDomains, 2568 PermittedIPRanges: c.PermittedIPRanges, 2569 ExcludedIPRanges: c.ExcludedIPRanges, 2570 PermittedEmailAddresses: c.PermittedEmailAddresses, 2571 ExcludedEmailAddresses: c.ExcludedEmailAddresses, 2572 PermittedURIDomains: c.PermittedURIDomains, 2573 ExcludedURIDomains: c.ExcludedURIDomains, 2574 // CRL Distribution Points 2575 CRLDistributionPoints: c.CRLDistributionPoints, 2576 PolicyIdentifiers: c.PolicyIdentifiers, 2577 } 2578 2579 for _, val := range c.ExtKeyUsage { 2580 x509cert.ExtKeyUsage = append(x509cert.ExtKeyUsage, x509.ExtKeyUsage(val)) 2581 } 2582 2583 return x509cert 2584 } 2585 2586 // FromX509Certificate x509转gmx509 2587 func (c *Certificate) FromX509Certificate(x509Cert *x509.Certificate) { 2588 c.Raw = x509Cert.Raw 2589 c.RawTBSCertificate = x509Cert.RawTBSCertificate 2590 c.RawSubjectPublicKeyInfo = x509Cert.RawSubjectPublicKeyInfo 2591 c.RawSubject = x509Cert.RawSubject 2592 c.RawIssuer = x509Cert.RawIssuer 2593 c.Signature = x509Cert.Signature 2594 c.SignatureAlgorithm = SM2WithSM3 2595 c.PublicKeyAlgorithm = PublicKeyAlgorithm(x509Cert.PublicKeyAlgorithm) 2596 c.PublicKey = x509Cert.PublicKey 2597 c.Version = x509Cert.Version 2598 c.SerialNumber = x509Cert.SerialNumber 2599 c.Issuer = x509Cert.Issuer 2600 c.Subject = x509Cert.Subject 2601 c.NotBefore = x509Cert.NotBefore 2602 c.NotAfter = x509Cert.NotAfter 2603 c.KeyUsage = KeyUsage(x509Cert.KeyUsage) 2604 c.Extensions = x509Cert.Extensions 2605 c.ExtraExtensions = x509Cert.ExtraExtensions 2606 c.UnhandledCriticalExtensions = x509Cert.UnhandledCriticalExtensions 2607 c.UnknownExtKeyUsage = x509Cert.UnknownExtKeyUsage 2608 c.BasicConstraintsValid = x509Cert.BasicConstraintsValid 2609 c.IsCA = x509Cert.IsCA 2610 c.MaxPathLen = x509Cert.MaxPathLen 2611 c.MaxPathLenZero = x509Cert.MaxPathLenZero 2612 c.SubjectKeyId = x509Cert.SubjectKeyId 2613 c.AuthorityKeyId = x509Cert.AuthorityKeyId 2614 c.OCSPServer = x509Cert.OCSPServer 2615 c.IssuingCertificateURL = x509Cert.IssuingCertificateURL 2616 c.DNSNames = x509Cert.DNSNames 2617 c.EmailAddresses = x509Cert.EmailAddresses 2618 c.IPAddresses = x509Cert.IPAddresses 2619 c.URIs = x509Cert.URIs 2620 c.PermittedDNSDomainsCritical = x509Cert.PermittedDNSDomainsCritical 2621 c.PermittedDNSDomains = x509Cert.PermittedDNSDomains 2622 c.ExcludedDNSDomains = x509Cert.ExcludedDNSDomains 2623 c.PermittedIPRanges = x509Cert.PermittedIPRanges 2624 c.ExcludedIPRanges = x509Cert.ExcludedIPRanges 2625 c.PermittedEmailAddresses = x509Cert.PermittedEmailAddresses 2626 c.ExcludedEmailAddresses = x509Cert.ExcludedEmailAddresses 2627 c.PermittedURIDomains = x509Cert.PermittedURIDomains 2628 c.ExcludedURIDomains = x509Cert.ExcludedURIDomains 2629 c.CRLDistributionPoints = x509Cert.CRLDistributionPoints 2630 c.PolicyIdentifiers = x509Cert.PolicyIdentifiers 2631 for _, val := range x509Cert.ExtKeyUsage { 2632 c.ExtKeyUsage = append(c.ExtKeyUsage, ExtKeyUsage(val)) 2633 } 2634 } 2635 2636 // RevocationList contains the fields used to create an X.509 v2 Certificate 2637 // Revocation list with CreateRevocationList. 2638 type RevocationList struct { 2639 // SignatureAlgorithm is used to determine the signature algorithm to be 2640 // used when signing the CRL. If 0 the default algorithm for the signing 2641 // key will be used. 2642 SignatureAlgorithm SignatureAlgorithm 2643 2644 // RevokedCertificates is used to populate the revokedCertificates 2645 // sequence in the CRL, it may be empty. RevokedCertificates may be nil, 2646 // in which case an empty CRL will be created. 2647 RevokedCertificates []pkix.RevokedCertificate 2648 2649 // Number is used to populate the X.509 v2 cRLNumber extension in the CRL, 2650 // which should be a monotonically increasing sequence number for a given 2651 // CRL scope and CRL issuer. 2652 Number *big.Int 2653 // ThisUpdate is used to populate the thisUpdate field in the CRL, which 2654 // indicates the issuance date of the CRL. 2655 ThisUpdate time.Time 2656 // NextUpdate is used to populate the nextUpdate field in the CRL, which 2657 // indicates the date by which the next CRL will be issued. NextUpdate 2658 // must be greater than ThisUpdate. 2659 NextUpdate time.Time 2660 // ExtraExtensions contains any additional extensions to add directly to 2661 // the CRL. 2662 ExtraExtensions []pkix.Extension 2663 } 2664 2665 // CreateRevocationList 创建x509 v2版本的证书撤销列表 2666 // 注意,私钥是ecdsa类型时,不支持low-s处理。 2667 // 2668 // creates a new X.509 v2 Certificate Revocation List, 2669 // according to RFC 5280, based on template. 2670 // 2671 // The CRL is signed by priv which should be the private key associated with 2672 // the public key in the issuer certificate. 2673 // 2674 // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in 2675 // order to use it as a CRL issuer. 2676 // 2677 // The issuer distinguished name CRL field and authority key identifier 2678 // extension are populated using the issuer certificate. issuer must have 2679 // SubjectKeyId set. 2680 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) { 2681 if template == nil { 2682 return nil, errors.New("x509: template can not be nil") 2683 } 2684 if issuer == nil { 2685 return nil, errors.New("x509: issuer can not be nil") 2686 } 2687 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 { 2688 return nil, errors.New("x509: issuer must have the crlSign key usage bit set") 2689 } 2690 if len(issuer.SubjectKeyId) == 0 { 2691 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier") 2692 } 2693 if template.NextUpdate.Before(template.ThisUpdate) { 2694 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate") 2695 } 2696 if template.Number == nil { 2697 return nil, errors.New("x509: template contains nil Number field") 2698 } 2699 2700 signOpts, hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm) 2701 if err != nil { 2702 return nil, err 2703 } 2704 2705 // Force revocation times to UTC per RFC 5280. 2706 revokedCertsUTC := make([]pkix.RevokedCertificate, len(template.RevokedCertificates)) 2707 for i, rc := range template.RevokedCertificates { 2708 rc.RevocationTime = rc.RevocationTime.UTC() 2709 revokedCertsUTC[i] = rc 2710 } 2711 2712 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId}) 2713 if err != nil { 2714 return nil, err 2715 } 2716 crlNum, err := asn1.Marshal(template.Number) 2717 if err != nil { 2718 return nil, err 2719 } 2720 2721 tbsCertList := pkix.TBSCertificateList{ 2722 Version: 1, // v2 2723 Signature: signatureAlgorithm, 2724 Issuer: issuer.Subject.ToRDNSequence(), 2725 ThisUpdate: template.ThisUpdate.UTC(), 2726 NextUpdate: template.NextUpdate.UTC(), 2727 Extensions: []pkix.Extension{ 2728 { 2729 Id: oidExtensionAuthorityKeyId, 2730 Value: aki, 2731 }, 2732 { 2733 Id: oidExtensionCRLNumber, 2734 Value: crlNum, 2735 }, 2736 }, 2737 } 2738 if len(revokedCertsUTC) > 0 { 2739 tbsCertList.RevokedCertificates = revokedCertsUTC 2740 } 2741 2742 //// 添加oidExtensionSignatureAlgorithm 2743 //if template.SignatureAlgorithm > 0 && !oidInExtensions(oidExtensionSignatureAlgorithm, template.ExtraExtensions) { 2744 // tbsCertList.Extensions = append(tbsCertList.Extensions, marshalSignatureAlgorithm(template.SignatureAlgorithm)) 2745 //} 2746 2747 if len(template.ExtraExtensions) > 0 { 2748 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...) 2749 } 2750 2751 tbsCertListContents, err := asn1.Marshal(tbsCertList) 2752 if err != nil { 2753 return nil, err 2754 } 2755 2756 input := tbsCertListContents 2757 if hashFunc != 0 { 2758 h := hashFunc.New() 2759 h.Write(tbsCertListContents) 2760 input = h.Sum(nil) 2761 } 2762 //var signerOpts crypto.SignerOpts = hashFunc 2763 //if template.SignatureAlgorithm.isRSAPSS() { 2764 // signerOpts = &rsa.PSSOptions{ 2765 // SaltLength: rsa.PSSSaltLengthEqualsHash, 2766 // Hash: hashFunc.HashFunc(), 2767 // } 2768 //} 2769 2770 signature, err := priv.Sign(rand, input, signOpts) 2771 if err != nil { 2772 return nil, err 2773 } 2774 //// ecdsa签名做low-s处理 2775 //if ecSignOpts, ok := signOpts.(ecbase.EcSignerOpts); ok { 2776 // if ecSignOpts.NeedLowS() { 2777 // // 对于ecdsa签名算法,如果指定了要做 low-s处理,那么这里需要针对使用`*ecdsa.PrivateKey`的场景做补丁处理。 2778 // // 而如果使用的是`*ecdsa_ext.PrivateKey`,其内部已经根据EcSignerOpts参数做过low-s了,这里不需要额外再做一次。 2779 // if ecdsaPriv, ok := priv.(*ecdsa.PrivateKey); ok { 2780 // zclog.Debugln("x509证书签署后尝试low-s处理") 2781 // doLow := false 2782 // doLow, signature, err = ecdsa_ext.SignatureToLowS(&ecdsaPriv.PublicKey, signature) 2783 // if err != nil { 2784 // return nil, err 2785 // } 2786 // if doLow { 2787 // zclog.Debugln("x509证书签署后完成low-s处理") 2788 // } 2789 // } 2790 // } 2791 //} 2792 2793 return asn1.Marshal(pkix.CertificateList{ 2794 TBSCertList: tbsCertList, 2795 SignatureAlgorithm: signatureAlgorithm, 2796 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 2797 }) 2798 }