1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Cipher block chaining (CBC) mode.
7 // CBC provides confidentiality by xoring (chaining) each plaintext block
8 // with the previous ciphertext block before applying the block cipher.
10 // See NIST SP 800-38A, pp 10-11
21 func newCBC(b Block, iv []byte) *cbc {
24 blockSize: b.BlockSize(),
26 tmp: make([]byte, b.BlockSize()),
32 // NewCBCEncrypter returns a BlockMode which encrypts in cipher block chaining
33 // mode, using the given Block. The length of iv must be the same as the
34 // Block's block size.
35 func NewCBCEncrypter(b Block, iv []byte) BlockMode {
36 return (*cbcEncrypter)(newCBC(b, iv))
39 func (x *cbcEncrypter) BlockSize() int { return x.blockSize }
41 func (x *cbcEncrypter) CryptBlocks(dst, src []byte) {
43 for i := 0; i < x.blockSize; i++ {
46 x.b.Encrypt(x.iv, x.iv)
47 for i := 0; i < x.blockSize; i++ {
50 src = src[x.blockSize:]
51 dst = dst[x.blockSize:]
57 // NewCBCDecrypter returns a BlockMode which decrypts in cipher block chaining
58 // mode, using the given Block. The length of iv must be the same as the
59 // Block's block size as must match the iv used to encrypt the data.
60 func NewCBCDecrypter(b Block, iv []byte) BlockMode {
61 return (*cbcDecrypter)(newCBC(b, iv))
64 func (x *cbcDecrypter) BlockSize() int { return x.blockSize }
66 func (x *cbcDecrypter) CryptBlocks(dst, src []byte) {
68 x.b.Decrypt(x.tmp, src[:x.blockSize])
69 for i := 0; i < x.blockSize; i++ {
75 src = src[x.blockSize:]
76 dst = dst[x.blockSize:]