开发者

mcrypt linux how to use rijndael 256 cbc

开发者 https://www.devze.com 2023-04-03 17:37 出处:网络
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

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.!

thi开发者_如何转开发s is the link i've found with the library i would like to use: http://linux.die.net/man/3/mcrypt


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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消