-
Notifications
You must be signed in to change notification settings - Fork 672
/
rsapss.go
123 lines (104 loc) · 2.44 KB
/
rsapss.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
116
117
118
119
120
121
122
123
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package crypto
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/hashing"
)
var (
_ Factory = &FactoryRSAPSS{}
_ PublicKey = &PublicKeyRSAPSS{}
_ PrivateKey = &PrivateKeyRSAPSS{}
)
const rsaPSSSize = 3072
type FactoryRSAPSS struct{}
func (*FactoryRSAPSS) NewPrivateKey() (PrivateKey, error) {
k, err := rsa.GenerateKey(rand.Reader, rsaPSSSize)
if err != nil {
return nil, err
}
return &PrivateKeyRSAPSS{sk: k}, nil
}
func (*FactoryRSAPSS) ToPublicKey(b []byte) (PublicKey, error) {
key, err := x509.ParsePKIXPublicKey(b)
if err != nil {
return nil, err
}
switch key := key.(type) {
case *rsa.PublicKey:
return &PublicKeyRSAPSS{
pk: key,
bytes: b,
}, nil
default:
return nil, errWrongKeyType
}
}
func (*FactoryRSAPSS) ToPrivateKey(b []byte) (PrivateKey, error) {
key, err := x509.ParsePKCS1PrivateKey(b)
if err != nil {
return nil, err
}
return &PrivateKeyRSAPSS{
sk: key,
bytes: b,
}, nil
}
type PublicKeyRSAPSS struct {
pk *rsa.PublicKey
addr ids.ShortID
bytes []byte
}
func (k *PublicKeyRSAPSS) Verify(msg, sig []byte) bool {
return k.VerifyHash(hashing.ComputeHash256(msg), sig)
}
func (k *PublicKeyRSAPSS) VerifyHash(hash, sig []byte) bool {
return rsa.VerifyPSS(k.pk, crypto.SHA256, hash, sig, nil) == nil
}
func (k *PublicKeyRSAPSS) Address() ids.ShortID {
if k.addr == ids.ShortEmpty {
addr, err := ids.ToShortID(hashing.PubkeyBytesToAddress(k.Bytes()))
if err != nil {
panic(err)
}
k.addr = addr
}
return k.addr
}
func (k *PublicKeyRSAPSS) Bytes() []byte {
if k.bytes == nil {
b, err := x509.MarshalPKIXPublicKey(k.pk)
if err != nil {
panic(err)
}
k.bytes = b
}
return k.bytes
}
type PrivateKeyRSAPSS struct {
sk *rsa.PrivateKey
pk *PublicKeyRSAPSS
bytes []byte
}
func (k *PrivateKeyRSAPSS) PublicKey() PublicKey {
if k.pk == nil {
k.pk = &PublicKeyRSAPSS{pk: &k.sk.PublicKey}
}
return k.pk
}
func (k *PrivateKeyRSAPSS) Sign(msg []byte) ([]byte, error) {
return k.SignHash(hashing.ComputeHash256(msg))
}
func (k *PrivateKeyRSAPSS) SignHash(hash []byte) ([]byte, error) {
return rsa.SignPSS(rand.Reader, k.sk, crypto.SHA256, hash, nil)
}
func (k *PrivateKeyRSAPSS) Bytes() []byte {
if k.bytes == nil {
k.bytes = x509.MarshalPKCS1PrivateKey(k.sk)
}
return k.bytes
}