-
Notifications
You must be signed in to change notification settings - Fork 0
/
rsa.go
81 lines (64 loc) · 1.73 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
package crypto
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io"
)
var (
ErrPemDecodeFailed = errors.New("pem_data_decode_failed")
ErrPemKeyDecodeFailed = errors.New("pem_key_decode_failed")
)
func Sign(message []byte, key *rsa.PrivateKey) ([]byte, error) {
hashed := sha256.Sum256(message)
s, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, hashed[:])
if err != nil {
return nil, fmt.Errorf("failed to sign message: %w", err)
}
return s, nil
}
func Verify(message, signature []byte, key *rsa.PublicKey) error {
hashed := sha256.Sum256(message)
return rsa.VerifyPKCS1v15(key, crypto.SHA256, hashed[:], signature)
}
func ParsePublicKey(source io.Reader) (*rsa.PublicKey, error) {
data, err := io.ReadAll(source)
if err != nil {
return nil, fmt.Errorf("failed to read data from source: %w", err)
}
p, _ := pem.Decode(data)
if p == nil {
return nil, ErrPemDecodeFailed
}
if p.Type != "PUBLIC KEY" {
return nil, fmt.Errorf("public key is not RSA format: %s", p.Type)
}
r, err := x509.ParsePKIXPublicKey(p.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse public key: %w", err)
}
return r.(*rsa.PublicKey), nil
}
func ParsePrivateKey(source io.Reader) (*rsa.PrivateKey, error) {
data, err := io.ReadAll(source)
if err != nil {
return nil, fmt.Errorf("failed to read data from source: %w", err)
}
p, _ := pem.Decode(data)
if p == nil {
return nil, ErrPemDecodeFailed
}
if p.Type != "RSA PRIVATE KEY" {
return nil, fmt.Errorf("private key is not RSA format: %s", p.Type)
}
r, err := x509.ParsePKCS1PrivateKey(p.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse private key: %w", err)
}
return r, nil
}