diff --git a/sm4/cbc_cipher_asm.go b/sm4/cbc_cipher_asm.go index c85358d..4e05fb4 100644 --- a/sm4/cbc_cipher_asm.go +++ b/sm4/cbc_cipher_asm.go @@ -6,6 +6,7 @@ import ( "crypto/cipher" "github.com/emmansun/gmsm/internal/alias" + "github.com/emmansun/gmsm/internal/subtle" ) // Assert that sm4CipherAsm implements the cbcEncAble and cbcDecAble interfaces. @@ -61,7 +62,21 @@ func (x *cbc) CryptBlocks(dst, src []byte) { return } if x.enc == cbcEncrypt { - encryptBlocksChain(&x.b.enc[0], dst, src, &x.iv[0]) + iv := x.iv + + for len(src) > 0 { + // Write the xor to dst, then encrypt in place. + subtle.XORBytes(dst[:BlockSize], src[:BlockSize], iv) + x.b.Encrypt(dst[:BlockSize], dst[:BlockSize]) + + // Move to the next block with this block as the next iv. + iv = dst[:BlockSize] + src = src[BlockSize:] + dst = dst[BlockSize:] + } + + // Save the iv for the next CryptBlocks call. + copy(x.iv, iv) return } diff --git a/sm4/cipher_asm.go b/sm4/cipher_asm.go index 55877bf..9b7bd01 100644 --- a/sm4/cipher_asm.go +++ b/sm4/cipher_asm.go @@ -70,7 +70,7 @@ func (c *sm4CipherAsm) Encrypt(dst, src []byte) { if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) { panic("sm4: invalid buffer overlap") } - encryptBlockAsm(&c.enc[0], &dst[0], &src[0], INST_AES) + encryptBlockGo(c.enc, dst, src) } func (c *sm4CipherAsm) EncryptBlocks(dst, src []byte) { @@ -96,7 +96,7 @@ func (c *sm4CipherAsm) Decrypt(dst, src []byte) { if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) { panic("sm4: invalid buffer overlap") } - encryptBlockAsm(&c.dec[0], &dst[0], &src[0], INST_AES) + decryptBlockGo(c.dec, dst, src) } func (c *sm4CipherAsm) DecryptBlocks(dst, src []byte) {