-
Notifications
You must be signed in to change notification settings - Fork 69
/
rsa.go
95 lines (79 loc) · 1.98 KB
/
rsa.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
package dongle
import (
"crypto"
"fmt"
"github.com/dromara/dongle/rsa"
)
type rsaHash crypto.Hash
const (
MD5 rsaHash = 2 + iota
SHA1
SHA224
SHA256
SHA384
SHA512
RIPEMD160 = 19
)
type RsaError struct {
}
func NewRsaError() RsaError {
return RsaError{}
}
func (e RsaError) PublicKeyError() error {
return fmt.Errorf("rsa: invalid public key, please make sure the public key is valid")
}
func (e RsaError) PrivateKeyError() error {
return fmt.Errorf("rsa: invalid private key, please make sure the private key is valid")
}
// ByRsa encrypts by rsa with public key or private key.
func (e Encrypter) ByRsa(rsaKey []byte) Encrypter {
if len(e.src) == 0 || e.Error != nil {
return e
}
keyPair := rsa.NewKeyPair()
keyPair.SetPublicKey(rsaKey)
keyPair.SetPrivateKey(rsaKey)
if keyPair.IsPrivateKey() {
e.dst, e.Error = keyPair.EncryptByPrivateKey(e.src)
return e
}
e.dst, e.Error = keyPair.EncryptByPublicKey(e.src)
return e
}
// ByRsa decrypts by rsa with private key or public key.
func (d Decrypter) ByRsa(rsaKey []byte) Decrypter {
if len(d.src) == 0 || d.Error != nil {
return d
}
keyPair := rsa.NewKeyPair()
keyPair.SetPublicKey(rsaKey)
keyPair.SetPrivateKey(rsaKey)
if keyPair.IsPublicKey() {
d.dst, d.Error = keyPair.DecryptByPublicKey(d.src)
return d
}
d.dst, d.Error = keyPair.DecryptByPrivateKey(d.src)
return d
}
// ByRsa signs by rsa with private key.
func (s Signer) ByRsa(privateKey []byte, hash rsaHash) Signer {
if len(s.src) == 0 || s.Error != nil {
return s
}
keyPair := rsa.NewKeyPair()
keyPair.SetPrivateKey(privateKey)
keyPair.SetHash(crypto.Hash(hash))
s.dst, s.Error = keyPair.SignByPrivateKey(s.src)
return s
}
// ByRsa verify sign by rsa with public key.
func (v Verifier) ByRsa(publicKey []byte, hash rsaHash) Verifier {
if len(v.src) == 0 || v.Error != nil {
return v
}
keyPair := rsa.NewKeyPair()
keyPair.SetPublicKey(publicKey)
keyPair.SetHash(crypto.Hash(hash))
v.Error = keyPair.VerifyByPublicKey(v.src, v.sign)
return v
}