-
Notifications
You must be signed in to change notification settings - Fork 113
/
algorithm.go
92 lines (80 loc) · 1.99 KB
/
algorithm.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
package crypto
import (
"github.com/iost-official/go-iost/crypto/backend"
"github.com/iost-official/go-iost/ilog"
)
// AlgorithmBackend is the interface of algorithm backend
type AlgorithmBackend interface {
Sign(message []byte, seckey []byte) []byte
Verify(message []byte, pubkey []byte, sig []byte) bool
GetPubkey(seckey []byte) []byte
GenSeckey() []byte
CheckSeckey(seckey []byte) error
}
// Algorithm is the crypto algorithm of signature
type Algorithm uint8
// Algorithm list
const (
_ Algorithm = iota
Secp256k1
Ed25519
)
func (a Algorithm) getBackend() AlgorithmBackend {
switch a {
case Secp256k1:
return &backend.Secp256k1{}
case Ed25519:
return &backend.Ed25519{}
default:
return &backend.Secp256k1{}
}
}
// NewAlgorithm returns a new algorithm by name
func NewAlgorithm(name string) Algorithm {
switch name {
case "secp256k1":
return Secp256k1
case "ed25519":
return Ed25519
default:
return Ed25519
}
}
// String return algorithm readable string
func (a Algorithm) String() string {
switch a {
case Secp256k1:
return "secp256k1"
case Ed25519:
return "ed25519"
default:
return "secp256k1"
}
}
// Sign will signature the message with seckey
func (a Algorithm) Sign(message []byte, seckey []byte) []byte {
return a.getBackend().Sign(message, seckey)
}
// Verify will verify the message with pubkey and sig
func (a Algorithm) Verify(message []byte, pubkey []byte, sig []byte) (ret bool) {
// catch ed25519.Verify panic
defer func() {
if e := recover(); e != nil {
ilog.Warnf("verify panic. err=%v", e)
ret = false
}
}()
return a.getBackend().Verify(message, pubkey, sig)
}
// GetPubkey will get the public key of the secret key
func (a Algorithm) GetPubkey(seckey []byte) []byte {
return a.getBackend().GetPubkey(seckey)
}
// GenSeckey will generate the secret key
func (a Algorithm) GenSeckey() []byte {
return a.getBackend().GenSeckey()
}
// CheckSeckey ...
func (a Algorithm) CheckSeckey(seckey []byte) error {
return a.getBackend().CheckSeckey(seckey)
}