forked from 33cn/chain33
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
115 lines (99 loc) · 2.07 KB
/
crypto.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package crypto 加解密、签名接口定义
package crypto
import (
"fmt"
"sync"
)
//PrivKey 私钥
type PrivKey interface {
Bytes() []byte
Sign(msg []byte) Signature
PubKey() PubKey
Equals(PrivKey) bool
}
//Signature 签名
type Signature interface {
Bytes() []byte
IsZero() bool
String() string
Equals(Signature) bool
}
//PubKey 公钥
type PubKey interface {
Bytes() []byte
KeyString() string
VerifyBytes(msg []byte, sig Signature) bool
Equals(PubKey) bool
}
//Crypto 加密
type Crypto interface {
GenKey() (PrivKey, error)
SignatureFromBytes([]byte) (Signature, error)
PrivKeyFromBytes([]byte) (PrivKey, error)
PubKeyFromBytes([]byte) (PubKey, error)
}
var (
drivers = make(map[string]Crypto)
driversType = make(map[string]int)
)
var driverMutex sync.Mutex
//const
const (
SignNameED25519 = "ed25519"
)
//Register 注册
func Register(name string, driver Crypto) {
driverMutex.Lock()
defer driverMutex.Unlock()
if driver == nil {
panic("crypto: Register driver is nil")
}
if _, dup := drivers[name]; dup {
panic("crypto: Register called twice for driver " + name)
}
drivers[name] = driver
}
//RegisterType 注册类型
func RegisterType(name string, ty int) {
driverMutex.Lock()
defer driverMutex.Unlock()
if _, dup := driversType[name]; dup {
panic("crypto: Register(ty) called twice for driver " + name)
}
driversType[name] = ty
}
//GetName 获取name
func GetName(ty int) string {
for name, t := range driversType {
if t == ty {
return name
}
}
return "unknown"
}
//GetType 获取type
func GetType(name string) int {
if ty, ok := driversType[name]; ok {
return ty
}
return 0
}
//New new
func New(name string) (c Crypto, err error) {
driverMutex.Lock()
defer driverMutex.Unlock()
c, ok := drivers[name]
if !ok {
err = fmt.Errorf("unknown driver %q", name)
return
}
return c, nil
}
//CertSignature 签名
type CertSignature struct {
Signature []byte
Cert []byte
}