-
Notifications
You must be signed in to change notification settings - Fork 54
/
cbc_cipher_asm.go
77 lines (67 loc) · 1.86 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
//go:build amd64 || arm64
// +build amd64 arm64
package sm4
import (
"crypto/cipher"
"github.com/emmansun/gmsm/internal/subtle"
"github.com/emmansun/gmsm/internal/xor"
)
// Assert that sm4CipherAsm implements the cbcDecAble interfaces.
var _ cbcDecAble = (*sm4CipherAsm)(nil)
type cbc struct {
b *sm4CipherAsm
iv []byte
tmp []byte
}
func (b *sm4CipherAsm) NewCBCDecrypter(iv []byte) cipher.BlockMode {
var c cbc
c.b = b
c.iv = make([]byte, BlockSize)
c.tmp = make([]byte, BlockSize)
copy(c.iv, iv)
return &c
}
func (x *cbc) BlockSize() int { return BlockSize }
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 subtle.InexactOverlap(dst[:len(src)], src) {
panic("cipher: invalid buffer overlap")
}
if len(src) == 0 {
return
}
end := len(src)
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)
for start > 0 {
x.b.DecryptBlocks(temp, src[start:end])
for i := 0; i < x.b.batchBlocks; i++ {
xor.XorBytes(dst[end-(i+1)*BlockSize:end-i*BlockSize], temp[x.b.blocksSize-(i+1)*BlockSize:x.b.blocksSize-i*BlockSize], src[end-(i+2)*BlockSize:end-(i+1)*BlockSize])
}
end = start
start -= x.b.blocksSize
}
copy(batchSrc, src[:end])
x.b.DecryptBlocks(temp, batchSrc)
count := end / BlockSize
for i := count; i > 1; i-- {
xor.XorBytes(dst[end-BlockSize:end], temp[end-BlockSize:end], src[end-2*BlockSize:end-BlockSize])
end -= BlockSize
}
xor.XorBytes(dst[0:end], temp[0:end], x.iv[:])
// 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)
}