sm4: improve cbc decrypt performance

This commit is contained in:
Sun Yimin 2022-07-20 11:43:49 +08:00 committed by GitHub
parent 54a06d72e1
commit 572bf6574e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -43,28 +43,30 @@ func (x *cbc) CryptBlocks(dst, src []byte) {
if len(src) == 0 { if len(src) == 0 {
return 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) end := len(src)
// Copy the last block of ciphertext in preparation as the new iv.
copy(x.tmp, src[end-BlockSize:end]) copy(x.tmp, src[end-BlockSize:end])
start := end - x.b.blocksSize start := end - x.b.blocksSize
var temp []byte = make([]byte, x.b.blocksSize) var temp []byte = make([]byte, x.b.blocksSize)
var batchSrc []byte = make([]byte, x.b.blocksSize) var batchSrc []byte = make([]byte, x.b.blocksSize+BlockSize)
for start > 0 { for start > 0 {
x.b.DecryptBlocks(temp, src[start:end]) x.b.DecryptBlocks(temp, src[start:end])
for i := 0; i < x.b.batchBlocks; i++ { copy(batchSrc, src[start-BlockSize:])
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]) xor.XorBytes(dst[start:], temp, batchSrc)
}
end = start end = start
start -= x.b.blocksSize start -= x.b.blocksSize
} }
copy(batchSrc, src[:end]) // Handle remain first blocks
x.b.DecryptBlocks(temp, batchSrc) copy(batchSrc[BlockSize:], src[:end])
count := end / BlockSize x.b.DecryptBlocks(temp, batchSrc[BlockSize:])
for i := count; i > 1; i-- { copy(batchSrc, x.iv)
xor.XorBytes(dst[end-BlockSize:end], temp[end-BlockSize:end], src[end-2*BlockSize:end-BlockSize]) xor.XorBytes(dst, temp[:end], batchSrc)
end -= BlockSize
}
xor.XorBytes(dst[0:end], temp[0:end], x.iv[:])
// Set the new iv to the first block we copied earlier. // Set the new iv to the first block we copied earlier.
x.iv, x.tmp = x.tmp, x.iv x.iv, x.tmp = x.tmp, x.iv
} }