github.com/turingchain2020/turingchain@v1.1.21/common/crypto/util.go (about) 1 // Copyright Turing Corp. 2018 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 crypto 6 7 import ( 8 "crypto/sha256" 9 "encoding/binary" 10 "errors" 11 "fmt" 12 "math" 13 14 "github.com/tjfoc/gmsm/sm3" 15 "golang.org/x/crypto/ripemd160" 16 ) 17 18 //Sha256 加密算法 19 func Sha256(bytes []byte) []byte { 20 hasher := sha256.New() 21 hasher.Write(bytes) 22 return hasher.Sum(nil) 23 } 24 25 //Ripemd160 加密算法 26 func Ripemd160(bytes []byte) []byte { 27 hasher := ripemd160.New() 28 hasher.Write(bytes) 29 return hasher.Sum(nil) 30 } 31 32 //Sm3Hash 加密算法 33 func Sm3Hash(msg []byte) []byte { 34 c := sm3.New() 35 c.Write(msg) 36 return c.Sum(nil) 37 } 38 39 // BasicValidation 公私钥数据签名验证基础实现 40 func BasicValidation(c Crypto, msg, pub, sig []byte) error { 41 42 pubKey, err := c.PubKeyFromBytes(pub) 43 if err != nil { 44 return err 45 } 46 s, err := c.SignatureFromBytes(sig) 47 if err != nil { 48 return err 49 } 50 if !pubKey.VerifyBytes(msg, s) { 51 return ErrSign 52 } 53 return nil 54 } 55 56 //ToAggregate 判断签名是否可以支持聚合签名,并且返回聚合签名的接口 57 func ToAggregate(c Crypto) (AggregateCrypto, error) { 58 if aggr, ok := c.(AggregateCrypto); ok { 59 return aggr, nil 60 } 61 return nil, ErrNotSupportAggr 62 } 63 64 // WithOptionCGO 设置为CGO版本 65 func WithOptionCGO() Option { 66 return func(d *Driver) error { 67 d.isCGO = true 68 return nil 69 } 70 } 71 72 // WithOptionDefaultDisable 设置默认不启用 73 func WithOptionDefaultDisable() Option { 74 return func(d *Driver) error { 75 d.enableHeight = -1 76 return nil 77 } 78 } 79 80 // MaxManualTypeID 手动指定ID最大值 65534 81 const MaxManualTypeID = math.MaxUint16 - 1 82 83 // WithOptionTypeID 手动指定typeID, 不指定情况,系统将根据name自动生成typeID 84 func WithOptionTypeID(id int32) Option { 85 return func(d *Driver) error { 86 if id <= 0 { 87 return errors.New("TypeIDMustPositive") 88 } 89 if id > MaxManualTypeID { 90 return fmt.Errorf("TypeIDMustLessThan %d", MaxManualTypeID+1) 91 } 92 d.typeID = id 93 return nil 94 } 95 } 96 97 // WithOptionInitFunc 设置插件初始化接口 98 func WithOptionInitFunc(fn DriverInitFunc) Option { 99 return func(d *Driver) error { 100 if fn == nil { 101 return errors.New("NilInitFunc") 102 } 103 d.initFunc = fn 104 return nil 105 } 106 } 107 108 // GenDriverTypeID 根据名称生成driver type id 109 func GenDriverTypeID(name string) int32 { 110 buf := Sha256([]byte(name)) 111 id := int32(binary.BigEndian.Uint32(buf) % 1e8) 112 // 自动生成的在区间[65535, 1e8+65535) 113 return id + MaxManualTypeID + 1 114 }