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

cert合约linter告警整改

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