-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
52 lines (43 loc) · 1.3 KB
/
auth.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
package internal
import (
"crypto/ecdsa"
"crypto/sha1"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
)
// ValidateSignature ensures that the signature provided in base64EncodedSignature is valid, i.e.
// it was signed by the provided rawPubKey and contains the provided message
func ValidateSignature(rawPubKey string, base64EncodedSignature string, message string) error {
block, _ := pem.Decode([]byte(rawPubKey))
if block == nil {
return errors.New("invalid PEM block")
}
key, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return err
}
pubKey := key.(*ecdsa.PublicKey)
signature, err := base64.StdEncoding.DecodeString(base64EncodedSignature)
if err != nil {
return err
}
hash := sha1.Sum([]byte(message))
if !ecdsa.VerifyASN1(pubKey, hash[:], signature) {
return errors.New("invalid signature")
}
return nil
}
// Fingerprint will attempt to generate a fingerprint from the provided rawPubKey
// The fingerprint is simply the URL safe, Base64 encoded sha256 hash of the public key
func Fingerprint(rawPubKey string) (string, error) {
block, _ := pem.Decode([]byte(rawPubKey))
if block == nil {
return "", errors.New("invalid PEM block")
}
s := sha256.New()
s.Write(block.Bytes)
return base64.URLEncoding.EncodeToString(s.Sum(nil)), nil
}