-
Notifications
You must be signed in to change notification settings - Fork 29
/
aeskw.go
64 lines (47 loc) · 1.62 KB
/
aeskw.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
package jose
import (
"errors"
"fmt"
"github.com/dvsekhvalnov/jose2go/aes"
"github.com/dvsekhvalnov/jose2go/arrays"
)
func init() {
RegisterJwa(&AesKW{ keySizeBits: 128})
RegisterJwa(&AesKW{ keySizeBits: 192})
RegisterJwa(&AesKW{ keySizeBits: 256})
}
// AES Key Wrap key management algorithm implementation
type AesKW struct {
keySizeBits int
}
func (alg *AesKW) Name() string {
switch alg.keySizeBits {
case 128: return A128KW
case 192: return A192KW
default: return A256KW
}
}
func (alg *AesKW) WrapNewKey(cekSizeBits int, key interface{}, header map[string]interface{}) (cek []byte, encryptedCek []byte, err error) {
if kek,ok:=key.([]byte); ok {
kekSizeBits := len(kek) << 3
if kekSizeBits != alg.keySizeBits {
return nil,nil, errors.New(fmt.Sprintf("AesKW.WrapNewKey(): expected key of size %v bits, but was given %v bits.",alg.keySizeBits, kekSizeBits))
}
if cek,err = arrays.Random(cekSizeBits>>3);err==nil {
encryptedCek,err=aes.KeyWrap(cek,kek)
return
}
return nil,nil,err
}
return nil,nil,errors.New("AesKW.WrapNewKey(): expected key to be '[]byte' array")
}
func (alg *AesKW) Unwrap(encryptedCek []byte, key interface{}, cekSizeBits int, header map[string]interface{}) (cek []byte, err error) {
if kek,ok:=key.([]byte); ok {
kekSizeBits := len(kek) << 3
if kekSizeBits != alg.keySizeBits {
return nil,errors.New(fmt.Sprintf("AesKW.Unwrap(): expected key of size %v bits, but was given %v bits.", alg.keySizeBits, kekSizeBits))
}
return aes.KeyUnwrap(encryptedCek, kek)
}
return nil,errors.New("AesKW.Unwrap(): expected key to be '[]byte' array")
}