WrapKey implements the RFC 3394 Wrap algorithm
(plaintext, kek []byte)
| 43 | |
| 44 | // WrapKey implements the RFC 3394 Wrap algorithm |
| 45 | func 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 | |
| 90 | var errCorruptKey = errors.DefineCorruption("corrupt_key", "corrupt key data") |
| 91 |