-
Notifications
You must be signed in to change notification settings - Fork 54
/
cbc_cipher_asm.go
102 lines (86 loc) · 2.41 KB
/
cbc_cipher_asm.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//go:build (amd64 && !purego) || (arm64 && !purego)
// +build amd64,!purego arm64,!purego
package sm4
import (
"crypto/cipher"
"github.com/emmansun/gmsm/internal/alias"
"github.com/emmansun/gmsm/internal/subtle"
)
// Assert that sm4CipherAsm implements the cbcEncAble and cbcDecAble interfaces.
var _ cbcEncAble = (*sm4CipherAsm)(nil)
var _ cbcDecAble = (*sm4CipherAsm)(nil)
const cbcEncrypt = 1
const cbcDecrypt = 0
type cbc struct {
b *sm4CipherAsm
iv []byte
tmp []byte
enc int
}
func (b *sm4CipherAsm) NewCBCEncrypter(iv []byte) cipher.BlockMode {
var c cbc
c.b = b
c.enc = cbcEncrypt
c.iv = make([]byte, BlockSize)
c.tmp = make([]byte, BlockSize)
copy(c.iv, iv)
return &c
}
func (b *sm4CipherAsm) NewCBCDecrypter(iv []byte) cipher.BlockMode {
var c cbc
c.b = b
c.enc = cbcDecrypt
c.iv = make([]byte, BlockSize)
c.tmp = make([]byte, BlockSize)
copy(c.iv, iv)
return &c
}
func (x *cbc) BlockSize() int { return BlockSize }
//go:noescape
func encryptBlocksChain(xk *uint32, dst, src []byte, iv *byte)
func (x *cbc) CryptBlocks(dst, src []byte) {
if len(src)%BlockSize != 0 {
panic("cipher: input not full blocks")
}
if len(dst) < len(src) {
panic("cipher: output smaller than input")
}
if alias.InexactOverlap(dst[:len(src)], src) {
panic("cipher: invalid buffer overlap")
}
if len(src) == 0 {
return
}
if x.enc == cbcEncrypt {
encryptBlocksChain(&x.b.enc[0], dst, src, &x.iv[0])
return
}
// For each block, we need to xor the decrypted data with the previous block's ciphertext (the iv).
// To avoid making a copy each time, we loop over the blocks BACKWARDS.
end := len(src)
// Copy the last block of ciphertext in preparation as the new iv.
copy(x.tmp, src[end-BlockSize:end])
start := end - x.b.blocksSize
var temp []byte = make([]byte, x.b.blocksSize)
var batchSrc []byte = make([]byte, x.b.blocksSize+BlockSize)
for start > 0 {
x.b.DecryptBlocks(temp, src[start:end])
copy(batchSrc, src[start-BlockSize:])
subtle.XORBytes(dst[start:], temp, batchSrc)
end = start
start -= x.b.blocksSize
}
// Handle remain first blocks
copy(batchSrc[BlockSize:], src[:end])
x.b.DecryptBlocks(temp, batchSrc[BlockSize:])
copy(batchSrc, x.iv)
subtle.XORBytes(dst, temp[:end], batchSrc)
// Set the new iv to the first block we copied earlier.
x.iv, x.tmp = x.tmp, x.iv
}
func (x *cbc) SetIV(iv []byte) {
if len(iv) != BlockSize {
panic("cipher: incorrect length IV")
}
copy(x.iv[:], iv)
}