/
ecdsa.go
118 lines (95 loc) · 2.66 KB
/
ecdsa.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
package crypto
import (
"crypto"
"crypto/ecdsa"
"crypto/rand"
_ "crypto/sha256"
_ "crypto/sha512"
"encoding/base64"
"math/big"
"gopkg.in/jwt.v1/util"
)
type SigningECDSA struct {
Signing
KeySize int
CurveBits int
}
func init() {
util.Debug("SigningECDSA init")
SigningES256 := &SigningECDSA{Signing{"ES256", crypto.SHA256}, 32, 256}
SigningES384 := &SigningECDSA{Signing{"ES384", crypto.SHA384}, 48, 384}
SigningES512 := &SigningECDSA{Signing{"ES512", crypto.SHA512}, 66, 521}
AddSigningFunc("ES256", SigningES256)
AddSigningFunc("ES384", SigningES384)
AddSigningFunc("ES512", SigningES512)
}
func (s *SigningECDSA) Verify(data, sign string, key interface{}) error { // Returns nil if signature is valid
var err error
// Decode the signature
var sig []byte
if sig, err = base64.RawURLEncoding.DecodeString(sign); err != nil {
return err
}
// Get the key
var ecdsaKey *ecdsa.PublicKey
switch k := key.(type) {
case *ecdsa.PublicKey:
ecdsaKey = k
default:
return ErrorInvalidKeyType
}
if len(sig) != 2*s.KeySize {
return ErrorECDSAVerification
}
r1 := big.NewInt(0).SetBytes(sig[:s.KeySize])
s1 := big.NewInt(0).SetBytes(sig[s.KeySize:])
// Create hashed
if !s.Hash.Available() {
return ErrorHashUnavailable
}
hashed := s.Hash.New()
hashed.Write([]byte(data))
// Verify the signature
if verifystatus := ecdsa.Verify(ecdsaKey, hashed.Sum(nil), r1, s1); verifystatus == true {
return nil
} else {
return ErrorECDSAVerification
}
}
func (s *SigningECDSA) Sign(data string, key interface{}) (string, error) { // Returns encoded signature or error
if ecdsaKey, ok := key.(*ecdsa.PrivateKey); ok && ecdsaKey != nil {
util.Debug("ecdsaKey", ecdsaKey)
if !s.Hash.Available() {
return "", ErrorHashUnavailable
}
hashed := s.Hash.New()
hashed.Write([]byte(data))
if r1, s1, err := ecdsa.Sign(rand.Reader, ecdsaKey, hashed.Sum(nil)); err == nil {
curveBits := ecdsaKey.Curve.Params().BitSize
if s.CurveBits != curveBits {
return "", ErrorInvalidKey
}
keyBytes := curveBits / 8
if curveBits%8 > 0 {
keyBytes += 1
}
rBytes := r1.Bytes()
rBytesPadded := make([]byte, keyBytes)
copy(rBytesPadded[keyBytes-len(rBytes):], rBytes)
sBytes := s1.Bytes()
sBytesPadded := make([]byte, keyBytes)
copy(sBytesPadded[keyBytes-len(sBytes):], sBytes)
out := append(rBytesPadded, sBytesPadded...)
return base64.RawURLEncoding.EncodeToString(out), nil
} else {
return "", err
}
}
return "", ErrorInvalidKeyType
}
func (s *SigningECDSA) Alg() string { // returns the alg identifier for this method (example: 'HS256')
return s.Name
}
func (s *SigningECDSA) HashType() crypto.Hash {
return s.Hash
}