6 Star 47 Fork 27

Hyperledger/fabric

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
key.go 2.50 KB
一键复制 编辑 原始数据 按行查看 历史
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package accesscontrol
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"math/big"
"time"
)
type KeyGenFunc func() (*certKeyPair, error)
type certKeyPair struct {
keyBytes []byte
certBytes []byte
crypto.Signer
cert *x509.Certificate
}
func (p *certKeyPair) privKeyString() string {
return base64.StdEncoding.EncodeToString(p.keyBytes)
}
func (p *certKeyPair) pubKeyString() string {
return base64.StdEncoding.EncodeToString(p.certBytes)
}
func newPrivKey() (*ecdsa.PrivateKey, []byte, error) {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, err
}
privBytes, err := x509.MarshalECPrivateKey(privateKey)
if err != nil {
return nil, nil, err
}
return privateKey, privBytes, nil
}
func newCertTemplate() (x509.Certificate, error) {
sn, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
return x509.Certificate{}, err
}
return x509.Certificate{
NotBefore: time.Now().Add(time.Hour * (-24)),
NotAfter: time.Now().Add(time.Hour * 24),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
SerialNumber: sn,
}, nil
}
func newCertKeyPair(isCA bool, certSigner crypto.Signer, parent *x509.Certificate) (*certKeyPair, error) {
privateKey, privBytes, err := newPrivKey()
if err != nil {
return nil, err
}
template, err := newCertTemplate()
if err != nil {
return nil, err
}
if isCA {
template.NotAfter = time.Now().Add(time.Hour * 24 * 365 * 10)
template.IsCA = true
template.KeyUsage |= x509.KeyUsageCertSign | x509.KeyUsageCRLSign
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageAny}
template.BasicConstraintsValid = true
} else {
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
}
// If no parent cert, it's a self signed cert
if parent == nil || certSigner == nil {
parent = &template
certSigner = privateKey
}
rawBytes, err := x509.CreateCertificate(rand.Reader, &template, parent, &privateKey.PublicKey, certSigner)
if err != nil {
return nil, err
}
pubKey := encodePEM("CERTIFICATE", rawBytes)
block, _ := pem.Decode(pubKey)
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
privKey := encodePEM("EC PRIVATE KEY", privBytes)
return &certKeyPair{
Signer: privateKey,
keyBytes: privKey,
certBytes: pubKey,
cert: cert,
}, nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/hyperledger/fabric.git
git@gitee.com:hyperledger/fabric.git
hyperledger
fabric
fabric
v1.1.0-preview

搜索帮助