Commit f2a39b71 authored by pengjun's avatar pengjun Committed by vipwzw

cert合约linter告警整改

parent 28c0d009
......@@ -23,12 +23,19 @@ import (
var (
alog = log.New("module", "authority")
OrgName = "Chain33"
cpuNum = runtime.NumCPU()
// 默认证书组织名
OrgName = "Chain33"
// 全局证书校验器
Author = &Authority{}
// 是否开启全局校验开关
IsAuthEnable = false
)
// 证书校验器主要结构
type Authority struct {
// 证书文件路径
cryptoPath string
......@@ -44,16 +51,14 @@ type Authority struct {
HistoryCertCache *HistoryCertData
}
/** 历史变更记录 **/
// 历史变更记录
type HistoryCertData struct {
CryptoCfg *core.AuthConfig
CurHeight int64
NxtHeight int64
}
/**
初始化auth
*/
// 初始化auth
func (auth *Authority) Init(conf *ty.Authority) error {
if conf == nil || !conf.Enable {
return nil
......@@ -93,9 +98,7 @@ func (auth *Authority) Init(conf *ty.Authority) error {
return nil
}
/**
store数据转成authConfig数据
*/
// store数据转成authConfig数据
func newAuthConfig(store *types.HistoryCertStore) *core.AuthConfig {
ret := &core.AuthConfig{}
ret.RootCerts = make([][]byte, len(store.Rootcerts))
......@@ -116,9 +119,7 @@ func newAuthConfig(store *types.HistoryCertStore) *core.AuthConfig {
return ret
}
/**
从数据库中的记录数据恢复证书,用于证书回滚
*/
// 从数据库中的记录数据恢复证书,用于证书回滚
func (auth *Authority) ReloadCert(store *types.HistoryCertStore) error {
if !IsAuthEnable {
return nil
......@@ -147,9 +148,7 @@ func (auth *Authority) ReloadCert(store *types.HistoryCertStore) error {
return nil
}
/**
从新的authdir下的文件更新证书,用于证书更新
*/
// 从新的authdir下的文件更新证书,用于证书更新
func (auth *Authority) ReloadCertByHeght(currentHeight int64) error {
if !IsAuthEnable {
return nil
......@@ -178,9 +177,7 @@ func (auth *Authority) ReloadCertByHeght(currentHeight int64) error {
return nil
}
/**
并发校验证书
*/
// 并发校验证书
func (auth *Authority) ValidateCerts(task []*types.Signature) bool {
//FIXME 有并发校验的场景需要考虑竞争,暂时没有并发校验的场景
done := make(chan struct{})
......@@ -242,9 +239,7 @@ func (auth *Authority) task(done <-chan struct{}, taskes <-chan *types.Signature
}
}
/**
检验证书
*/
// 检验证书
func (auth *Authority) Validate(signature *types.Signature) error {
// 从proto中解码signature
cert, err := auth.validator.GetCertFromSignature(signature.Signature)
......@@ -270,9 +265,7 @@ func (auth *Authority) Validate(signature *types.Signature) error {
return nil
}
/**
历史数据转成store可存储的历史数据
*/
// 历史数据转成store可存储的历史数据
func (certdata *HistoryCertData) ToHistoryCertStore(store *types.HistoryCertStore) {
if store == nil {
alog.Error("Convert cert data to cert store failed")
......@@ -298,19 +291,21 @@ func (certdata *HistoryCertData) ToHistoryCertStore(store *types.HistoryCertStor
store.NxtHeight = certdata.NxtHeight
}
// 用户关联的证书私钥信息
type User struct {
Id string
ID string
Cert []byte
Key crypto.PrivKey
}
//userloader, SKD加载user使用
// userloader, SKD加载user使用
type UserLoader struct {
configPath string
userMap map[string]*User
signType int
}
// userloader初始化
func (loader *UserLoader) Init(configPath string, signType string) error {
loader.configPath = configPath
loader.userMap = make(map[string]*User)
......@@ -381,9 +376,10 @@ func (loader *UserLoader) genCryptoPriv(keyBytes []byte) (crypto.PrivKey, error)
return priv, nil
}
func (load *UserLoader) Get(userName string) (*User, error) {
// 根据用户名获取user结构
func (loader *UserLoader) Get(userName string) (*User, error) {
keyvalue := fmt.Sprintf("%s@%s-cert.pem", userName, OrgName)
user, ok := load.userMap[keyvalue]
user, ok := loader.userMap[keyvalue]
if !ok {
return nil, types.ErrInvalidParam
}
......
......@@ -55,7 +55,7 @@ var (
)
var USERNAME = "User"
var SIGNTYPE = ct.AUTH_SM2
var SIGNTYPE = ct.AuthSM2
func signtx(tx *types.Transaction, priv crypto.PrivKey, cert []byte) {
tx.Sign(int32(SIGNTYPE), priv)
......@@ -197,7 +197,7 @@ func TestChckSignWithNoneAuth(t *testing.T) {
TestCase04 不带证书,SM2签名验证
*/
func TestChckSignWithSm2(t *testing.T) {
sm2, err := crypto.New(types.GetSignName("cert", ct.AUTH_SM2))
sm2, err := crypto.New(types.GetSignName("cert", ct.AuthSM2))
assert.Nil(t, err)
privKeysm2, _ := sm2.PrivKeyFromBytes(privRaw)
tx15 := &types.Transaction{Execer: []byte("coins"),
......@@ -213,7 +213,7 @@ func TestChckSignWithSm2(t *testing.T) {
types.SetMinFee(0)
defer types.SetMinFee(prev)
tx15.Sign(ct.AUTH_SM2, privKeysm2)
tx15.Sign(ct.AuthSM2, privKeysm2)
if !tx15.CheckSign() {
t.Error("check signature failed")
return
......@@ -224,7 +224,7 @@ func TestChckSignWithSm2(t *testing.T) {
TestCase05 不带证书,secp256r1签名验证
*/
func TestChckSignWithEcdsa(t *testing.T) {
ecdsacrypto, _ := crypto.New(types.GetSignName("cert", ct.AUTH_ECDSA))
ecdsacrypto, _ := crypto.New(types.GetSignName("cert", ct.AuthECDSA))
privKeyecdsa, _ := ecdsacrypto.PrivKeyFromBytes(privRaw)
tx16 := &types.Transaction{Execer: []byte("coins"),
Payload: types.Encode(&cty.CoinsAction{Value: tr, Ty: cty.CoinsActionTransfer}),
......@@ -239,7 +239,7 @@ func TestChckSignWithEcdsa(t *testing.T) {
types.SetMinFee(0)
defer types.SetMinFee(prev)
tx16.Sign(ct.AUTH_ECDSA, privKeyecdsa)
tx16.Sign(ct.AuthECDSA, privKeyecdsa)
if !tx16.CheckSign() {
t.Error("check signature failed")
return
......
......@@ -44,8 +44,8 @@ type tbsCertificate struct {
Validity validity
Subject asn1.RawValue
PublicKey publicKeyInfo
UniqueId asn1.BitString `asn1:"optional,tag:1"`
SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
UniqueID asn1.BitString `asn1:"optional,tag:1"`
SubjectUniqueID asn1.BitString `asn1:"optional,tag:2"`
Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
}
......@@ -58,10 +58,10 @@ func isECDSASignedCert(cert *x509.Certificate) bool {
func sanitizeECDSASignedCert(cert *x509.Certificate, parentCert *x509.Certificate) (*x509.Certificate, error) {
if cert == nil {
return nil, errors.New("Certificate must be different from nil.")
return nil, errors.New("Certificate must be different from nil")
}
if parentCert == nil {
return nil, errors.New("Parent certificate must be different from nil.")
return nil, errors.New("Parent certificate must be different from nil")
}
expectedSig, err := signatureToLowS(parentCert.PublicKey.(*ecdsa.PublicKey), cert.Signature)
......@@ -109,6 +109,7 @@ func certFromX509Cert(cert *x509.Certificate) (certificate, error) {
return newCert, nil
}
// 将ECDSA的公钥转成SM2公钥
func ParseECDSAPubKey2SM2PubKey(key *ecdsa.PublicKey) *sm2.PublicKey {
sm2Key := &sm2.PublicKey{
key.Curve,
......
......@@ -54,6 +54,7 @@ const (
crlsfolder = "crls"
)
// 获取证书文件配置
func GetAuthConfig(dir string) (*AuthConfig, error) {
cacertDir := filepath.Join(dir, cacerts)
intermediatecertsDir := filepath.Join(dir, intermediatecerts)
......
......@@ -38,6 +38,7 @@ type ecdsaValidator struct {
CRL []*pkix.CertificateList
}
// 创建ecdsa校验器
func NewEcdsaValidator() Validator {
return &ecdsaValidator{}
}
......@@ -148,7 +149,7 @@ func (validator *ecdsaValidator) Validate(certByte []byte, pubKey []byte) error
}
if !bytes.Equal(pubKey, ecdsa_util.SerializePublicKey(certPubKey)) {
return fmt.Errorf("Invalid public key.")
return fmt.Errorf("Invalid public key")
}
cert, err = validator.sanitizeCert(cert)
......@@ -212,7 +213,7 @@ func (validator *ecdsaValidator) getValidationChain(cert *x509.Certificate, isIn
parentPosition = 0
}
if validator.certificationTreeInternalNodesMap[string(validationChain[parentPosition].Raw)] {
return nil, fmt.Errorf("Invalid validation chain. Parent certificate should be a leaf of the certification tree [%v].", cert.Raw)
return nil, fmt.Errorf("Invalid validation chain. Parent certificate should be a leaf of the certification tree [%v]", cert.Raw)
}
return validationChain, nil
}
......@@ -403,7 +404,7 @@ func (validator *ecdsaValidator) getValidityOptsForCert(cert *x509.Certificate)
return tempOpts
}
func (Validator *ecdsaValidator) GetCertFromSignature(signature []byte) ([]byte, error) {
func (validator *ecdsaValidator) GetCertFromSignature(signature []byte) ([]byte, error) {
cert, _, err := utils.DecodeCertFromSignature(signature)
if err != nil {
authLogger.Error(fmt.Sprintf("unmashal certificate from signature failed. %s", err.Error()))
......
......@@ -10,13 +10,14 @@ import (
ty "github.com/33cn/plugin/plugin/dapp/cert/types"
)
// 根据类型获取校验器
func GetLocalValidator(authConfig *AuthConfig, signType int) (Validator, error) {
var lclValidator Validator
var err error
if signType == ty.AUTH_ECDSA {
if signType == ty.AuthECDSA {
lclValidator = NewEcdsaValidator()
} else if signType == ty.AUTH_SM2 {
} else if signType == ty.AuthSM2 {
lclValidator = NewGmValidator()
} else {
return nil, ty.ErrUnknowAuthSignType
......
......@@ -33,6 +33,7 @@ type gmValidator struct {
CRL []*pkix.CertificateList
}
// 创建国密证书校验器
func NewGmValidator() Validator {
return &gmValidator{}
}
......@@ -90,7 +91,7 @@ func (validator *gmValidator) Validate(certByte []byte, pubKey []byte) error {
}
if !bytes.Equal(pubKey, sm2_util.SerializePublicKey(ParseECDSAPubKey2SM2PubKey(certPubKey))) {
return fmt.Errorf("Invalid public key.")
return fmt.Errorf("Invalid public key")
}
validationChain, err := validator.getCertificationChain(cert)
......@@ -150,7 +151,7 @@ func (validator *gmValidator) getValidationChain(cert *sm2.Certificate, isInterm
parentPosition = 0
}
if validator.certificationTreeInternalNodesMap[string(validationChain[parentPosition].Raw)] {
return nil, fmt.Errorf("Invalid validation chain. Parent certificate should be a leaf of the certification tree [%v].", cert.Raw)
return nil, fmt.Errorf("Invalid validation chain. Parent certificate should be a leaf of the certification tree [%v]", cert.Raw)
}
return validationChain, nil
}
......@@ -335,7 +336,7 @@ func (validator *gmValidator) getValidityOptsForCert(cert *sm2.Certificate) sm2.
return tempOpts
}
func (Validator *gmValidator) GetCertFromSignature(signature []byte) ([]byte, error) {
func (validator *gmValidator) GetCertFromSignature(signature []byte) ([]byte, error) {
// 从proto中解码signature
cert, _, err := utils.DecodeCertFromSignature(signature)
if err != nil {
......
......@@ -7,6 +7,7 @@ package core
type noneValidator struct {
}
// 创建none校验器
func NewNoneValidator() (Validator, error) {
return &noneValidator{}, nil
}
......@@ -19,6 +20,6 @@ func (validator *noneValidator) Validate(certByte []byte, pubKey []byte) error {
return nil
}
func (Validator *noneValidator) GetCertFromSignature(signature []byte) ([]byte, error) {
func (validator *noneValidator) GetCertFromSignature(signature []byte) ([]byte, error) {
return []byte(""), nil
}
......@@ -4,6 +4,7 @@
package core
// 证书校验器
type Validator interface {
Setup(config *AuthConfig) error
......@@ -12,6 +13,7 @@ type Validator interface {
GetCertFromSignature(signature []byte) ([]byte, error)
}
// 校验器配置
type AuthConfig struct {
RootCerts [][]byte
IntermediateCerts [][]byte
......
......@@ -17,12 +17,14 @@ import (
)
const (
// 默认CA名称
CANAME = "ca"
CONFIGFILENAME = "chain33.cryptogen.toml"
OUTPUTDIR = "./authdir/crypto"
ORGNAME = "Chain33"
)
// 证书生成工具配置
type Config struct {
Name []string
SignType string
......
......@@ -7,10 +7,12 @@ package csp
import "crypto"
const (
// ECDSA类型
ECDSAP256KeyGen = 1
SM2P256KygGen = 2
)
// 通用key接口
type Key interface {
Bytes() ([]byte, error)
SKI() []byte
......@@ -19,25 +21,30 @@ type Key interface {
PublicKey() (Key, error)
}
// 签名器参数接口
type SignerOpts interface {
crypto.SignerOpts
}
// 证书生成器接口
type CSP interface {
KeyGen(opts int) (k Key, err error)
Sign(k Key, digest []byte, opts SignerOpts) (signature []byte, err error)
}
// key存储接口
type KeyStore interface {
ReadOnly() bool
StoreKey(k Key) (err error)
}
// 签名器接口
type Signer interface {
Sign(k Key, digest []byte, opts SignerOpts) (signature []byte, err error)
}
// key生成器接口
type KeyGenerator interface {
KeyGen(opts int) (k Key, err error)
}
......@@ -11,6 +11,7 @@ import (
"github.com/pkg/errors"
)
// 创建新的证书生成结构
func New(keyStore KeyStore) (CSP, error) {
signers := make(map[reflect.Type]Signer)
signers[reflect.TypeOf(&ecdsaPrivateKey{})] = &ecdsaSigner{}
......@@ -58,10 +59,10 @@ func (csp *cspimpl) KeyGen(opts int) (k Key, err error) {
func (csp *cspimpl) Sign(k Key, digest []byte, opts SignerOpts) (signature []byte, err error) {
if k == nil {
return nil, errors.New("Invalid Key. It must not be nil.")
return nil, errors.New("Invalid Key. It must not be nil")
}
if len(digest) == 0 {
return nil, errors.New("Invalid digest. Cannot be empty.")
return nil, errors.New("Invalid digest. Cannot be empty")
}
keyType := reflect.TypeOf(k)
......
......@@ -32,10 +32,12 @@ func signECDSA(k *ecdsa.PrivateKey, digest []byte, opts SignerOpts) (signature [
return MarshalECDSASignature(r, s)
}
// ECDSA签名结构
type ECDSASignature struct {
R, S *big.Int
}
// 编码ECDSA类型签名
func MarshalECDSASignature(r, s *big.Int) ([]byte, error) {
return asn1.Marshal(ECDSASignature{r, s})
}
......
......@@ -18,7 +18,7 @@ type ecdsaPrivateKey struct {
}
func (k *ecdsaPrivateKey) Bytes() (raw []byte, err error) {
return nil, errors.New("Not supported.")
return nil, errors.New("Not supported")
}
func (k *ecdsaPrivateKey) SKI() (ski []byte) {
......
......@@ -22,6 +22,7 @@ import (
var logger = log.New("tools", "cryptogen")
// 创建key存储器
func NewFileBasedKeyStore(pwd []byte, path string, readOnly bool) (KeyStore, error) {
ks := &fileBasedKeyStore{}
return ks, ks.Init(pwd, path, readOnly)
......@@ -40,14 +41,14 @@ type fileBasedKeyStore struct {
func (ks *fileBasedKeyStore) Init(pwd []byte, path string, readOnly bool) error {
if len(path) == 0 {
return errors.New("An invalid KeyStore path provided. Path cannot be an empty string.")
return errors.New("An invalid KeyStore path provided. Path cannot be an empty string")
}
ks.m.Lock()
defer ks.m.Unlock()
if ks.isOpen {
return errors.New("KeyStore already initilized.")
return errors.New("KeyStore already initilized")
}
ks.path = path
......@@ -74,11 +75,11 @@ func (ks *fileBasedKeyStore) ReadOnly() bool {
func (ks *fileBasedKeyStore) StoreKey(k Key) (err error) {
if ks.readOnly {
return errors.New("Read only KeyStore.")
return errors.New("Read only KeyStore")
}
if k == nil {
return errors.New("Invalid key. It must be different from nil.")
return errors.New("Invalid key. It must be different from nil")
}
switch k.(type) {
case *ecdsaPrivateKey:
......
......@@ -27,10 +27,12 @@ func signSM2(k *sm2.PrivateKey, digest []byte, opts SignerOpts) (signature []byt
return MarshalSM2Signature(r, s)
}
// SM2签名结构
type SM2Signature struct {
R, S *big.Int
}
// 编码SM2起签名
func MarshalSM2Signature(r, s *big.Int) ([]byte, error) {
return asn1.Marshal(SM2Signature{r, s})
}
......
......@@ -13,14 +13,17 @@ import (
"github.com/tjfoc/gmsm/sm2"
)
// SM2PrivateKey
type SM2PrivateKey struct {
PrivKey *sm2.PrivateKey
}
// Bytes
func (k *SM2PrivateKey) Bytes() (raw []byte, err error) {
return nil, errors.New("Not supported.")
return nil, errors.New("Not supported")
}
// SKI
func (k *SM2PrivateKey) SKI() (ski []byte) {
if k.PrivKey == nil {
return nil
......@@ -33,22 +36,27 @@ func (k *SM2PrivateKey) SKI() (ski []byte) {
return hash.Sum(nil)
}
// Symmetric
func (k *SM2PrivateKey) Symmetric() bool {
return false
}
// Private
func (k *SM2PrivateKey) Private() bool {
return true
}
// PublicKey
func (k *SM2PrivateKey) PublicKey() (Key, error) {
return &SM2PublicKey{&k.PrivKey.PublicKey}, nil
}
// SM2PublicKey
type SM2PublicKey struct {
PubKey *sm2.PublicKey
}
// Bytes
func (k *SM2PublicKey) Bytes() (raw []byte, err error) {
raw, err = sm2.MarshalSm2PublicKey(k.PubKey)
if err != nil {
......@@ -57,6 +65,7 @@ func (k *SM2PublicKey) Bytes() (raw []byte, err error) {
return
}
// SKI
func (k *SM2PublicKey) SKI() (ski []byte) {
if k.PubKey == nil {
return nil
......@@ -69,14 +78,17 @@ func (k *SM2PublicKey) SKI() (ski []byte) {
return hash.Sum(nil)
}
// Symmetric
func (k *SM2PublicKey) Symmetric() bool {
return false
}
// Private
func (k *SM2PublicKey) Private() bool {
return false
}
// PublicKey
func (k *SM2PublicKey) PublicKey() (Key, error) {
return k, nil
}
......@@ -20,15 +20,16 @@ type cspCryptoSigner struct {
pk interface{}
}
// 创建签名器
func New(csp lccsp.CSP, key lccsp.Key) (crypto.Signer, error) {
if csp == nil {
return nil, errors.New("bccsp instance must be different from nil.")
return nil, errors.New("bccsp instance must be different from nil")
}
if key == nil {
return nil, errors.New("key must be different from nil.")
return nil, errors.New("key must be different from nil")
}
if key.Symmetric() {
return nil, errors.New("key must be asymmetric.")
return nil, errors.New("key must be asymmetric")
}
pub, err := key.PublicKey()
......
......@@ -44,18 +44,19 @@ func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
return nil, false
}
// PrivateKeyToPEM
func PrivateKeyToPEM(privateKey interface{}, pwd []byte) ([]byte, error) {
if len(pwd) != 0 {
return privateKeyToEncryptedPEM(privateKey, pwd)
}
if privateKey == nil {
return nil, errors.New("Invalid key. It must be different from nil.")
return nil, errors.New("Invalid key. It must be different from nil")
}
switch k := privateKey.(type) {
case *ecdsa.PrivateKey:
if k == nil {
return nil, errors.New("Invalid ecdsa private key. It must be different from nil.")
return nil, errors.New("Invalid ecdsa private key. It must be different from nil")
}
oidNamedCurve, ok := oidFromNamedCurve(k.Curve)
......@@ -95,7 +96,7 @@ func PrivateKeyToPEM(privateKey interface{}, pwd []byte) ([]byte, error) {
), nil
case *sm2.PrivateKey:
if k == nil {
return nil, errors.New("Invalid sm2 private key. It must be different from nil.")
return nil, errors.New("Invalid sm2 private key. It must be different from nil")
}
return sm2.WritePrivateKeytoMem(k, nil)
default:
......@@ -105,13 +106,13 @@ func PrivateKeyToPEM(privateKey interface{}, pwd []byte) ([]byte, error) {
func privateKeyToEncryptedPEM(privateKey interface{}, pwd []byte) ([]byte, error) {
if privateKey == nil {
return nil, errors.New("Invalid private key. It must be different from nil.")
return nil, errors.New("Invalid private key. It must be different from nil")
}
switch k := privateKey.(type) {
case *ecdsa.PrivateKey:
if k == nil {
return nil, errors.New("Invalid ecdsa private key. It must be different from nil.")
return nil, errors.New("Invalid ecdsa private key. It must be different from nil")
}
raw, err := x509.MarshalECPrivateKey(k)
......@@ -137,19 +138,20 @@ func privateKeyToEncryptedPEM(privateKey interface{}, pwd []byte) ([]byte, error
}
}
// PublicKeyToPEM
func PublicKeyToPEM(publicKey interface{}, pwd []byte) ([]byte, error) {
if len(pwd) != 0 {
return publicKeyToEncryptedPEM(publicKey, pwd)
}
if publicKey == nil {
return nil, errors.New("Invalid public key. It must be different from nil.")
return nil, errors.New("Invalid public key. It must be different from nil")
}
switch k := publicKey.(type) {
case *ecdsa.PublicKey:
if k == nil {
return nil, errors.New("Invalid ecdsa public key. It must be different from nil.")
return nil, errors.New("Invalid ecdsa public key. It must be different from nil")
}
PubASN1, err := x509.MarshalPKIXPublicKey(k)
if err != nil {
......@@ -164,7 +166,7 @@ func PublicKeyToPEM(publicKey interface{}, pwd []byte) ([]byte, error) {
), nil
case *sm2.PublicKey:
if k == nil {
return nil, errors.New("Invalid sm2 public key. It must be different from nil.")
return nil, errors.New("Invalid sm2 public key. It must be different from nil")
}
return sm2.WritePublicKeytoMem(k, nil)
......@@ -175,16 +177,16 @@ func PublicKeyToPEM(publicKey interface{}, pwd []byte) ([]byte, error) {
func publicKeyToEncryptedPEM(publicKey interface{}, pwd []byte) ([]byte, error) {
if publicKey == nil {
return nil, errors.New("Invalid public key. It must be different from nil.")
return nil, errors.New("Invalid public key. It must be different from nil")
}
if len(pwd) == 0 {
return nil, errors.New("Invalid password. It must be different from nil.")
return nil, errors.New("Invalid password. It must be different from nil")
}
switch k := publicKey.(type) {
case *ecdsa.PublicKey:
if k == nil {
return nil, errors.New("Invalid ecdsa public key. It must be different from nil.")
return nil, errors.New("Invalid ecdsa public key. It must be different from nil")
}
raw, err := x509.MarshalPKIXPublicKey(k)
if err != nil {
......@@ -209,9 +211,10 @@ func publicKeyToEncryptedPEM(publicKey interface{}, pwd []byte) ([]byte, error)
}
}
// DER字符转成公钥
func DERToPublicKey(raw []byte) (pub interface{}, err error) {
if len(raw) == 0 {
return nil, errors.New("Invalid DER. It must be different from nil.")
return nil, errors.New("Invalid DER. It must be different from nil")
}
key, err := x509.ParsePKIXPublicKey(raw)
......@@ -222,6 +225,7 @@ func DERToPublicKey(raw []byte) (pub interface{}, err error) {
return key, err
}
// Clone
func Clone(src []byte) []byte {
clone := make([]byte, len(src))
copy(clone, src)
......
......@@ -6,6 +6,7 @@ package generator
import "crypto/x509"
// CAGenerator
type CAGenerator interface {
SignCertificate(baseDir, name string, sans []string, pub interface{}) (*x509.Certificate, error)
......
......@@ -25,12 +25,14 @@ import (
"github.com/tjfoc/gmsm/sm2"
)
// EcdsaCA
type EcdsaCA struct {
Name string
Signer crypto.Signer
SignCert *x509.Certificate
}
// SM2CA
type SM2CA struct {
Name string
Signer crypto.Signer
......@@ -38,10 +40,11 @@ type SM2CA struct {
Sm2Key csp.Key
}
// NewCA
func NewCA(baseDir, name string, signType int) (generator.CAGenerator, error) {
if signType == ty.AUTH_ECDSA {
if signType == ty.AuthECDSA {
return newEcdsaCA(baseDir, name)
} else if signType == ty.AUTH_SM2 {
} else if signType == ty.AuthSM2 {
return newSM2CA(baseDir, name)
} else {
return nil, fmt.Errorf("Invalid sign type")
......@@ -92,6 +95,7 @@ func newEcdsaCA(baseDir, name string) (*EcdsaCA, error) {
return ca, nil
}
// 证书签名
func (ca *EcdsaCA) SignCertificate(baseDir, name string, sans []string, pub interface{}) (*x509.Certificate, error) {
template := x509Template()
template.KeyUsage = x509.KeyUsageDigitalSignature
......@@ -112,6 +116,7 @@ func (ca *EcdsaCA) SignCertificate(baseDir, name string, sans []string, pub inte
return cert, nil
}
// 生成本地用户
func (ca *EcdsaCA) GenerateLocalUser(baseDir, name string) error {
err := createFolderStructure(baseDir, true)
if err != nil {
......@@ -229,6 +234,7 @@ func newSM2CA(baseDir, name string) (*SM2CA, error) {
return ca, nil
}
// 证书签名
func (ca *SM2CA) SignCertificate(baseDir, name string, sans []string, pub interface{}) (*x509.Certificate, error) {
template := x509Template()
template.KeyUsage = x509.KeyUsageDigitalSignature
......@@ -250,6 +256,7 @@ func (ca *SM2CA) SignCertificate(baseDir, name string, sans []string, pub interf
return utils.ParseSm2CertificateToX509(cert), nil
}
// 生成本地用户
func (ca *SM2CA) GenerateLocalUser(baseDir, name string) error {
err := createFolderStructure(baseDir, true)
if err != nil {
......
......@@ -11,6 +11,7 @@ import (
"github.com/tjfoc/gmsm/sm2"
)
// CreateCertificateToMem
func CreateCertificateToMem(template, parent *sm2.Certificate, key csp.Key) (cert []byte, err error) {
pk := key.(*csp.SM2PrivateKey).PrivKey
......@@ -25,6 +26,7 @@ func CreateCertificateToMem(template, parent *sm2.Certificate, key csp.Key) (cer
return
}
// CreateCertificateToPem
func CreateCertificateToPem(FileName string, template, parent *sm2.Certificate, key csp.Key) (bool, error) {
pk := key.(*csp.SM2PrivateKey).PrivKey
......@@ -44,6 +46,7 @@ func CreateCertificateToPem(FileName string, template, parent *sm2.Certificate,
return result, err
}
// ParseX509CertificateToSm2
func ParseX509CertificateToSm2(x509Cert *x509.Certificate) *sm2.Certificate {
sm2cert := &sm2.Certificate{
Raw: x509Cert.Raw,
......@@ -103,6 +106,7 @@ func ParseX509CertificateToSm2(x509Cert *x509.Certificate) *sm2.Certificate {
return sm2cert
}
// ParseSm2CertificateToX509
func ParseSm2CertificateToX509(sm2Cert *sm2.Certificate) *x509.Certificate {
if sm2Cert == nil {
return nil
......
......@@ -19,7 +19,7 @@ import (
func getCSPFromOpts(KeyStorePath string) (csp.CSP, error) {
if KeyStorePath == "" {
return nil, errors.New("Invalid config. It must not be nil.")
return nil, errors.New("Invalid config. It must not be nil")
}
fks, err := csp.NewFileBasedKeyStore(nil, KeyStorePath, false)
......@@ -30,6 +30,7 @@ func getCSPFromOpts(KeyStorePath string) (csp.CSP, error) {
return csp.New(fks)
}
// GeneratePrivateKey
func GeneratePrivateKey(keystorePath string, opt int) (csp.Key, crypto.Signer, error) {
var err error
var priv csp.Key
......@@ -48,6 +49,7 @@ func GeneratePrivateKey(keystorePath string, opt int) (csp.Key, crypto.Signer, e
return priv, s, err
}
// GetECPublicKey
func GetECPublicKey(priv csp.Key) (*ecdsa.PublicKey, error) {
pubKey, err := priv.PublicKey()
if err != nil {
......@@ -66,6 +68,7 @@ func GetECPublicKey(priv csp.Key) (*ecdsa.PublicKey, error) {
return ecPubKey.(*ecdsa.PublicKey), nil
}
// GetSM2PublicKey
func GetSM2PublicKey(priv csp.Key) (*sm2.PublicKey, error) {
pubKey, err := priv.PublicKey()
if err != nil {
......
......@@ -5,16 +5,14 @@
package utils
import (
"bufio"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"os"
"github.com/33cn/chain33/util"
)
// DirMissingOrEmpty
func DirMissingOrEmpty(path string) (bool, error) {
dirExists, err := DirExists(path)
if err != nil {
......@@ -34,6 +32,7 @@ func DirMissingOrEmpty(path string) (bool, error) {
return false, nil
}
// DirExists
func DirExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
......@@ -45,6 +44,7 @@ func DirExists(path string) (bool, error) {
return false, err
}
// DirEmpty
func DirEmpty(path string) (bool, error) {
f, err := os.Open(path)
if err != nil {
......@@ -59,6 +59,7 @@ func DirEmpty(path string) (bool, error) {
return false, err
}
// ReadFile
func ReadFile(file string) ([]byte, error) {
fileCont, err := ioutil.ReadFile(file)
if err != nil {
......@@ -68,6 +69,7 @@ func ReadFile(file string) ([]byte, error) {
return fileCont, nil
}
// ReadPemFile
func ReadPemFile(file string) ([]byte, error) {
bytes, err := ReadFile(file)
if err != nil {
......@@ -82,35 +84,7 @@ func ReadPemFile(file string) ([]byte, error) {
return bytes, nil
}
func CheckFileIsExist(filename string) bool {
var exist = true
if _, err := os.Stat(filename); os.IsNotExist(err) {
exist = false
}
return exist
}
// DeleteFile
func DeleteFile(file string) error {
return os.Remove(file)
}
func WriteStringToFile(file, content string) (writeLen int, err error) {
var f *os.File
if err = util.MakeDir(file); err != nil {
return
}
util.DeleteFile(file)
if CheckFileIsExist(file) {
f, err = os.OpenFile(file, os.O_APPEND, 0666)
} else {
f, err = os.Create(file)
}
if err != nil {
return
}
defer f.Close()
w := bufio.NewWriter(f)
writeLen, err = w.WriteString(content)
w.Flush()
return
}
......@@ -25,6 +25,7 @@ import (
"github.com/tjfoc/gmsm/sm2"
)
// SKI
func SKI(curve elliptic.Curve, x, y *big.Int) (ski []byte) {
raw := elliptic.Marshal(curve, x, y)
......@@ -33,6 +34,7 @@ func SKI(curve elliptic.Curve, x, y *big.Int) (ski []byte) {
return hash.Sum(nil)
}
// GetPublicKeySKIFromCert
func GetPublicKeySKIFromCert(cert []byte, signType int) (string, error) {
dcert, _ := pem.Decode(cert)
if dcert == nil {
......@@ -41,14 +43,14 @@ func GetPublicKeySKIFromCert(cert []byte, signType int) (string, error) {
var ski []byte
switch signType {
case ty.AUTH_ECDSA:
case ty.AuthECDSA:
x509Cert, err := x509.ParseCertificate(dcert.Bytes)
if err != nil {
return "", errors.Errorf("Unable to parse cert from decoded bytes: %s", err)
}
ecdsaPk := x509Cert.PublicKey.(*ecdsa.PublicKey)
ski = SKI(ecdsaPk.Curve, ecdsaPk.X, ecdsaPk.Y)
case ty.AUTH_SM2:
case ty.AuthSM2:
sm2Cert, err := sm2.ParseCertificate(dcert.Bytes)
if err != nil {
return "", errors.Errorf("Unable to parse cert from decoded bytes: %s", err)
......@@ -62,6 +64,7 @@ func GetPublicKeySKIFromCert(cert []byte, signType int) (string, error) {
return hex.EncodeToString(ski), nil
}
// 证书编码进签名
func EncodeCertToSignature(signByte []byte, cert []byte) ([]byte, error) {
certSign := crypto.CertSignature{}
certSign.Signature = append(certSign.Signature, signByte...)
......@@ -69,6 +72,7 @@ func EncodeCertToSignature(signByte []byte, cert []byte) ([]byte, error) {
return asn1.Marshal(certSign)
}
// 从签名中解码证书
func DecodeCertFromSignature(signByte []byte) ([]byte, []byte, error) {
var certSignature crypto.CertSignature
_, err := asn1.Unmarshal(signByte, &certSignature)
......@@ -79,6 +83,7 @@ func DecodeCertFromSignature(signByte []byte) ([]byte, []byte, error) {
return certSignature.Cert, certSignature.Signature, nil
}
// pem结构转成byte类型私钥
func PrivKeyByteFromRaw(raw []byte, signType int) ([]byte, error) {
block, _ := pem.Decode(raw)
if block == nil {
......@@ -86,13 +91,13 @@ func PrivKeyByteFromRaw(raw []byte, signType int) ([]byte, error) {
}
switch signType {
case ty.AUTH_ECDSA:
case ty.AuthECDSA:
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return ecdsa_util.SerializePrivateKey(key.(*ecdsa.PrivateKey)), nil
case ty.AUTH_SM2:
case ty.AuthSM2:
key, err := sm2.ParsePKCS8PrivateKey(block.Bytes, nil)
if err != nil {
return nil, err
......
......@@ -20,6 +20,7 @@ func init() {
ety.InitFuncList(types.ListMethod(&Cert{}))
}
// 初始化
func Init(name string, sub []byte) {
driverName = name
var cfg ct.Authority
......@@ -30,10 +31,12 @@ func Init(name string, sub []byte) {
drivers.Register(driverName, newCert, types.GetDappFork(driverName, "Enable"))
}
// 获取cert执行器名
func GetName() string {
return newCert().GetName()
}
// cert执行器
type Cert struct {
drivers.DriverBase
}
......@@ -45,10 +48,12 @@ func newCert() drivers.Driver {
return c
}
// 获取cert执行器名
func (c *Cert) GetDriverName() string {
return driverName
}
// cert执行器tx证书校验
func (c *Cert) CheckTx(tx *types.Transaction, index int) error {
// 基类检查
err := c.DriverBase.CheckTx(tx, index)
......
......@@ -16,6 +16,7 @@ func calcCertHeightKey(height int64) []byte {
return []byte(fmt.Sprintf("LODB-cert-%d", height))
}
// 启用证书交易执行
func (c *Cert) ExecLocal_New(payload *ct.CertNew, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if !authority.IsAuthEnable {
clog.Error("Authority is not available. Please check the authority config or authority initialize error logs.")
......@@ -38,6 +39,7 @@ func (c *Cert) ExecLocal_New(payload *ct.CertNew, tx *types.Transaction, receipt
return &set, nil
}
// 更新证书交易执行
func (c *Cert) ExecLocal_Update(payload *ct.CertUpdate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if !authority.IsAuthEnable {
clog.Error("Authority is not available. Please check the authority config or authority initialize error logs.")
......@@ -61,6 +63,7 @@ func (c *Cert) ExecLocal_Update(payload *ct.CertUpdate, tx *types.Transaction, r
return &set, nil
}
// 非证书变更交易执行
func (c *Cert) ExecLocal_Normal(payload *ct.CertNormal, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if !authority.IsAuthEnable {
clog.Error("Authority is not available. Please check the authority config or authority initialize error logs.")
......
......@@ -5,6 +5,7 @@
package types
var (
// cert执行器名
CertX = "cert"
ExecerCert = []byte(CertX)
actionName = map[string]int32{
......
......@@ -7,6 +7,7 @@ package types
import "errors"
var (
// cert校验失败
ErrValidateCertFailed = errors.New("ErrValidateCertFailed")
ErrGetHistoryCertData = errors.New("ErrGetHistoryCertData")
ErrUnknowAuthSignType = errors.New("ErrUnknowAuthSignType")
......
......@@ -12,10 +12,8 @@ const (
CertActionUpdate = 2
CertActionNormal = 3
SignNameAuthECDSA = "auth_ecdsa"
AUTH_ECDSA = 257
SignNameAuthSM2 = "auth_sm2"
AUTH_SM2 = 258
AuthECDSA = 257
AuthSM2 = 258
)
func init() {
......@@ -25,28 +23,34 @@ func init() {
types.RegisterDappFork(CertX, "Enable", 0)
}
// cert执行器类型结构
type CertType struct {
types.ExecTypeBase
}
// NewType
func NewType() *CertType {
c := &CertType{}
c.SetChild(c)
return c
}
// GetPayload
func (b *CertType) GetPayload() types.Message {
return &CertAction{}
}
// GetName
func (b *CertType) GetName() string {
return CertX
}
// GetLogMap
func (b *CertType) GetLogMap() map[int64]*types.LogInfo {
return nil
}
// GetTypeMap
func (b *CertType) GetTypeMap() map[string]int32 {
return actionName
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment