-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathaes_gcm_amd64.go
84 lines (66 loc) · 2.03 KB
/
aes_gcm_amd64.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
73
74
75
76
77
78
79
80
81
82
83
84
// Copyright (c) 2018 Andreas Auernhammer. All rights reserved.
// Use of this source code is governed by a license that can be
// found in the LICENSE file.
// +build amd64,!gccgo,!appengine
package siv
import (
"crypto/aes"
"crypto/cipher"
"crypto/subtle"
"golang.org/x/sys/cpu"
)
func polyval(tag *[16]byte, additionalData, plaintext, key []byte)
func aesGcmXORKeyStream(dst, src, iv, keys []byte, keyLen uint64)
func newGCM(key []byte) aead {
if cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ {
block, _ := aes.NewCipher(key)
return &aesGcmSivAsm{block: block, keyLen: len(key)}
}
return newGCMGeneric(key)
}
var _ aead = (*aesGcmSivAsm)(nil)
type aesGcmSivAsm struct {
block cipher.Block
keyLen int
}
func (c *aesGcmSivAsm) seal(ciphertext, nonce, plaintext, additionalData []byte) {
encKey, authKey := deriveKeys(nonce, c.block, c.keyLen)
var tag [16]byte
polyval(&tag, additionalData, plaintext, authKey)
for i := range nonce {
tag[i] ^= nonce[i]
}
tag[15] &= 0x7f
var encKeys [240]byte
keySchedule(encKeys[:], encKey)
encryptBlock(tag[:], tag[:], encKeys[:], uint64(len(encKey)))
ctrBlock := tag
ctrBlock[15] |= 0x80
aesGcmXORKeyStream(ciphertext, plaintext, ctrBlock[:], encKeys[:], uint64(len(encKey)))
copy(ciphertext[len(plaintext):], tag[:])
}
func (c *aesGcmSivAsm) open(plaintext, nonce, ciphertext, additionalData []byte) error {
tag := ciphertext[len(ciphertext)-16:]
ciphertext = ciphertext[:len(ciphertext)-16]
encKey, authKey := deriveKeys(nonce, c.block, c.keyLen)
var ctrBlock [16]byte
copy(ctrBlock[:], tag)
ctrBlock[15] |= 0x80
var encKeys [240]byte
keySchedule(encKeys[:], encKey)
aesGcmXORKeyStream(plaintext, ciphertext, ctrBlock[:], encKeys[:], uint64(len(encKey)))
var sum [16]byte
polyval(&sum, additionalData, plaintext, authKey)
for i := range nonce {
sum[i] ^= nonce[i]
}
sum[15] &= 0x7f
encryptBlock(sum[:], sum[:], encKeys[:], uint64(len(encKey)))
if subtle.ConstantTimeCompare(sum[:], tag[:]) != 1 {
for i := range plaintext {
plaintext[i] = 0
}
return errOpen
}
return nil
}