-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathkeycrypter.go
65 lines (55 loc) · 1.31 KB
/
keycrypter.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
package jwe
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"errors"
)
var (
ErrUnsupportedKeyType = errors.New("unsupported key type")
ErrUnsupportedKeyAlgorithm = errors.New("unsupported key algorithm")
)
type KeyAlgorithm string
var KeyAlgorithmRSAOAEP = KeyAlgorithm("RSA-OAEP")
type rsaEncrypter struct {
key *rsa.PublicKey
}
func (r *rsaEncrypter) Encrypt(cek []byte, alg KeyAlgorithm) ([]byte, error) {
switch alg {
case KeyAlgorithmRSAOAEP:
return rsa.EncryptOAEP(sha1.New(), rand.Reader, r.key, cek, []byte{})
default:
return nil, ErrUnsupportedKeyAlgorithm
}
}
type rsaDecrypter struct {
key *rsa.PrivateKey
}
func (r *rsaDecrypter) Decrypt(encryptedKey []byte, alg KeyAlgorithm) ([]byte, error) {
switch alg {
case KeyAlgorithmRSAOAEP:
return rsa.DecryptOAEP(sha1.New(), rand.Reader, r.key, encryptedKey, []byte{})
default:
return nil, ErrUnsupportedKeyAlgorithm
}
}
func createEncrypter(key interface{}) (*rsaEncrypter, error) {
switch pbk := key.(type) {
case *rsa.PublicKey:
return &rsaEncrypter{
key: pbk,
}, nil
default:
return nil, ErrUnsupportedKeyType
}
}
func createDecrypter(key interface{}) (*rsaDecrypter, error) {
switch pk := key.(type) {
case *rsa.PrivateKey:
return &rsaDecrypter{
key: pk,
}, nil
default:
return nil, ErrUnsupportedKeyType
}
}