-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verifier.go
70 lines (57 loc) · 1.67 KB
/
verifier.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
package local
import (
"context"
"crypto"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
)
var (
ErrFailedToDecodeKey = errors.New("failed to decode public key")
ErrKeyIsNotPublic = errors.New("key is not a public key")
ErrKeyIsNotPublicRSA = errors.New("key is not an RSA public key")
)
type verifier struct {
key *rsa.PublicKey
}
// NewVerifier creates a new verifier with local public key.
func NewVerifier(key *rsa.PublicKey) verifier {
return verifier{key: key}
}
// Verify verifies the given message against signature using the local public key.
// Signature must be a base64 encoded string. It returns an error if the verification fails.
func (l verifier) Verify(ctx context.Context, message, signature []byte) error {
decoded, err := base64.StdEncoding.DecodeString(string(signature))
if err != nil {
return fmt.Errorf("failed to decode signature: %w", err)
}
// calculate the digest of the message
digest := sha256.Sum256(message)
if err := rsa.VerifyPKCS1v15(l.key, crypto.SHA256, digest[:], decoded); err != nil {
return fmt.Errorf("failed to verify signature: %w", err)
}
return nil
}
// ParsePublicKey parses a public RSA key from a PEM encoded bytes.
func ParsePublicKey(pub []byte) (*rsa.PublicKey, error) {
pubPem, _ := pem.Decode(pub)
if pubPem == nil {
return nil, ErrFailedToDecodeKey
}
if pubPem.Type != "PUBLIC KEY" {
return nil, ErrKeyIsNotPublic
}
parsed, err := x509.ParsePKIXPublicKey(pubPem.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse public key: %w", err)
}
key, ok := parsed.(*rsa.PublicKey)
if !ok {
return nil, ErrKeyIsNotPublicRSA
}
return key, nil
}