MCPcopy Create free account
hub / github.com/TheThingsNetwork/lorawan-stack / WrapKey

Function WrapKey

pkg/crypto/keywrap.go:45–88  ·  view source on GitHub ↗

WrapKey implements the RFC 3394 Wrap algorithm

(plaintext, kek []byte)

Source from the content-addressed store, hash-verified

43
44// WrapKey implements the RFC 3394 Wrap algorithm
45func WrapKey(plaintext, kek []byte) ([]byte, error) {
46 length := len(plaintext)
47 if length%8 != 0 {
48 return nil, errInvalidKeyLength.WithAttributes("size", length)
49 }
50
51 n := length / 8
52 if n < 2 {
53 return nil, errInvalidKeyLength.WithAttributes("size", length)
54 }
55
56 cipher, err := aes.NewCipher(kek)
57 if err != nil {
58 return nil, err
59 }
60
61 // Set A to initial value
62 a := iv
63
64 // Fill R blocks
65 r := make([][8]byte, n)
66 for i := range n {
67 copy(r[i][:], plaintext[i*8:(i+1)*8])
68 }
69
70 // Run the algorithm
71 for j := 0; j <= 5; j++ {
72 for i := 1; i <= n; i++ {
73 var b [aes.BlockSize]byte
74 cipher.Encrypt(b[:], concat(a, r[i-1]))
75 a = xor(msb(b), uint64((n*j)+i))
76 r[i-1] = lsb(b)
77 }
78 }
79
80 // Build the result
81 ciphertext := make([]byte, 0, 8*(n+1))
82 ciphertext = append(ciphertext, a[:]...)
83 for i := range n {
84 ciphertext = append(ciphertext, r[i][:]...)
85 }
86
87 return ciphertext, nil
88}
89
90var errCorruptKey = errors.DefineCorruption("corrupt_key", "corrupt key data")
91

Callers 4

WrapAES128KeyWithKEKFunction · 0.92
mustWrapKeyFunction · 0.92
TestKEKFunction · 0.85
WrapMethod · 0.85

Calls 6

concatFunction · 0.85
xorFunction · 0.85
msbFunction · 0.85
lsbFunction · 0.85
EncryptMethod · 0.65
WithAttributesMethod · 0.45

Tested by 2

mustWrapKeyFunction · 0.74
TestKEKFunction · 0.68