mcrypt linux how to use rijndael 256 cbc

◇◆丶佛笑我妖孽 提交于 2019-12-11 05:52:42

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/7347713/mcrypt-linux-how-to-use-rijndael-256-cbc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!