-
Notifications
You must be signed in to change notification settings - Fork 29
/
rsa_oaep.go
72 lines (61 loc) · 1.62 KB
/
rsa_oaep.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
package jose
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"errors"
"hash"
"github.com/dvsekhvalnov/jose2go/arrays"
)
// RS-AES using OAEP key management algorithm implementation
func init() {
RegisterJwa(&RsaOaep{shaSizeBits: 1})
RegisterJwa(&RsaOaep{shaSizeBits: 256})
RegisterJwa(&RsaOaep{shaSizeBits: 384})
RegisterJwa(&RsaOaep{shaSizeBits: 512})
}
type RsaOaep struct {
shaSizeBits int
}
func (alg *RsaOaep) Name() string {
switch alg.shaSizeBits {
case 1:
return RSA_OAEP
case 256:
return RSA_OAEP_256
case 384:
return RSA_OAEP_384
default:
return RSA_OAEP_512
}
}
func (alg *RsaOaep) WrapNewKey(cekSizeBits int, key interface{}, header map[string]interface{}) (cek []byte, encryptedCek []byte, err error) {
if pubKey, ok := key.(*rsa.PublicKey); ok {
if cek, err = arrays.Random(cekSizeBits >> 3); err == nil {
encryptedCek, err = rsa.EncryptOAEP(alg.sha(), rand.Reader, pubKey, cek, nil)
return
}
return nil, nil, err
}
return nil, nil, errors.New("RsaOaep.WrapNewKey(): expected key to be '*rsa.PublicKey'")
}
func (alg *RsaOaep) Unwrap(encryptedCek []byte, key interface{}, cekSizeBits int, header map[string]interface{}) (cek []byte, err error) {
if privKey, ok := key.(*rsa.PrivateKey); ok {
return rsa.DecryptOAEP(alg.sha(), rand.Reader, privKey, encryptedCek, nil)
}
return nil, errors.New("RsaOaep.Unwrap(): expected key to be '*rsa.PrivateKey'")
}
func (alg *RsaOaep) sha() hash.Hash {
switch alg.shaSizeBits {
case 1:
return sha1.New()
case 256:
return sha256.New()
case 384:
return sha512.New384()
default:
return sha512.New()
}
}