[botan-devel] CBC mode with no padding

Jack Lloyd jack at randombit.net
Thu Nov 23 19:48:26 EST 2017

On Thu, Nov 23, 2017 at 06:56:06PM -0500, Jeffrey Walton wrote:
> Hi Everyone,
> I'm trying to use SM4 cipher in CBC mode with no padding. The code is
> available at https://pastebin.com/tFEjzZtz.
> The code either fails to compile (no start() on cipher object) or
> crashes (just a segfault; no uncaught exceptions).
> The documentation for SymmetricCipher is at
> https://botan.randombit.net/manual/symmetric_crypto.html, but I don't
> see a discussion of "no padding". I found a Null_Padding class, but I
> have not figured out how to wire it in to the machinery.
> How do I use SM4 cipher in CBC mode with no padding?

The problem is you were attempting this via BlockCipher (which is just
the bare n-bit permutation) vs Cipher_Mode which is the API for
encrypting messages.

The segfault probably occured because BlockCipher::create("Foo")
returns null if no such cipher exists; ::create_or_throw will throw
instead. And there is no block cipher named "SM4/CBC".

As for skipping padding, CBC mode allows speciying the padding type as
in BlockCipher/CBC/PaddingMode eg AES-128/CBC/PKCS7 or SM4/CBC/NoPadding.

Modified version of your paste follows. Hope this helps. -Jack

#include "botan/block_cipher.h"
#include "botan/auto_rng.h"
#include "botan/hex.h"
#include "botan/cipher_mode.h"
using namespace Botan;

#include <iostream>

int main ()
    AutoSeeded_RNG prng;
    for (unsigned int i=0; i<10; ++i)
        std::vector<uint8_t> key(16);
        std::vector<uint8_t> iv(16);
        Botan::secure_vector<uint8_t> block(16);

        prng.randomize(&key[0], key.size());
        std::cout << "Key: " << Botan::hex_encode(key) << std::endl;
        prng.randomize(&iv[0], iv.size());
        std::cout << "IV: " << Botan::hex_encode(iv) << std::endl;
        prng.randomize(&block[0], block.size());
        std::cout << "Plaintext: " << Botan::hex_encode(block) << std::endl;

        std::unique_ptr<Botan::Cipher_Mode> cipher(Botan::get_cipher_mode("SM4/CBC/NoPadding", Botan::ENCRYPTION));
        //cipher->set_key(key, 16, iv);
        std::cout << "Ciphertext: " << Botan::hex_encode(block) << std::endl;
    return 0;

More information about the botan-devel mailing list