-
Notifications
You must be signed in to change notification settings - Fork 18
/
rsa.go
92 lines (76 loc) · 2.36 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
82
83
84
85
86
87
88
89
90
91
92
// Copyright (C) 2017 Space Monkey, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package httpsig
import (
"crypto"
"crypto/rsa"
)
// RSASHA1 implements RSA PKCS1v15 signatures over a SHA1 digest
var RSASHA1 Algorithm = rsa_sha1{}
type rsa_sha1 struct{}
func (rsa_sha1) Name() string {
return "rsa-sha1"
}
func (a rsa_sha1) Sign(key interface{}, data []byte) ([]byte, error) {
k := toRSAPrivateKey(key)
if k == nil {
return nil, unsupportedAlgorithm(a)
}
return RSASign(k, crypto.SHA1, data)
}
func (a rsa_sha1) Verify(key interface{}, data, sig []byte) error {
k := toRSAPublicKey(key)
if k == nil {
return unsupportedAlgorithm(a)
}
return RSAVerify(k, crypto.SHA1, data, sig)
}
// RSASHA256 implements RSA PKCS1v15 signatures over a SHA256 digest
var RSASHA256 Algorithm = rsa_sha256{}
type rsa_sha256 struct{}
func (rsa_sha256) Name() string {
return "rsa-sha256"
}
func (a rsa_sha256) Sign(key interface{}, data []byte) ([]byte, error) {
k := toRSAPrivateKey(key)
if k == nil {
return nil, unsupportedAlgorithm(a)
}
return RSASign(k, crypto.SHA256, data)
}
func (a rsa_sha256) Verify(key interface{}, data, sig []byte) error {
k := toRSAPublicKey(key)
if k == nil {
return unsupportedAlgorithm(a)
}
return RSAVerify(k, crypto.SHA256, data, sig)
}
// RSASign signs a digest of the data hashed using the provided hash
func RSASign(key *rsa.PrivateKey, hash crypto.Hash, data []byte) (
signature []byte, err error) {
h := hash.New()
if _, err := h.Write(data); err != nil {
return nil, err
}
return rsa.SignPKCS1v15(Rand, key, hash, h.Sum(nil))
}
// RSAVerify verifies a signed digest of the data hashed using the provided hash
func RSAVerify(key *rsa.PublicKey, hash crypto.Hash, data, sig []byte) (
err error) {
h := hash.New()
if _, err := h.Write(data); err != nil {
return err
}
return rsa.VerifyPKCS1v15(key, hash, h.Sum(nil), sig)
}