Question

I am working on linux/ubuntu. I found out that mcrypt is automatically included as a library in this platform. I want to create an encryption with aes 256 and cbc padding 7 (iv). Could someone please give me an example of how to encrypt a string with aes 256 and cbc iv, padding 7?

Rijndael is the same with aes.!

this is the link i've found with the library i would like to use: http://linux.die.net/man/3/mcrypt

Was it helpful?

Solution

Are you asking how to use mcrypt? Here's a basic skeleton:

#include <mcrypt.h>

int main()
{
  char algo[] = "rijndael-256";
  char mode[] = "cbc";

  char key[] = ...
  char iv[]  = ...

  MCRYPT td = mcrypt_module_open(algo, NULL, mode, NULL);
  if (td == MCRYPT_FAILED) { /* error */ }

  int r =  mcrypt_generic_init(td, key, keysize, iv);

  /* use  mdecrypt_generic() or mcrypt_generic() */

  mcrypt_generic_deinit(td);

  mcrypt_module_close(td);
}

You have to check the actual key size and IV size with mcrypt_enc_get_key_size(td) and mcrypt_enc_get_iv_size(td) and provide suitable key and IV data.


Edit: Because it's so simple, here's an algorithm to add and strip PCKS7 padding:

std::string add_pkcs7_padding(std::string s, std::size_t n)
{
  const std::size_t fill = n - (s.length() % n);
  s.append(fill, static_cast<char>(fill));
  return s;
}

std::string strip_pkcs7_padding(std::string s, std::size_t n)
{
  const std::size_t pad = static_cast<unsigned char>(*s.rbegin());
  return s.substr(0, s.length() - pad);
}

(Library-grade code would of course test that n can be represented by a char, and that during stripping the input string is non-empty and the padding is valid.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top