问题描述
我在linux / ubuntu上工作。我发现mcrypt是自动包含在这个平台上的一个库。我想用aes 256和cbc填充7(iv)创建加密。有人可以给我一个例子,如何加密一个字符串与aes 256和cbc iv,填充7?
Rijndael是一样的aes。
这是我发现的库我想使用的链接:
Are你问如何使用 mcrypt
?以下是一个基本框架:
#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);
/ *使用mdecrypt_generic()或mcrypt_generic()* /
mcrypt_generic_deinit(td);
mcrypt_module_close(td);
}
您必须检查实际钥匙尺寸和IV尺寸 mcrypt_enc_get_key_size(td)
和 mcrypt_enc_get_iv_size(td)
并提供合适的键和IV数据。
编辑:因为它很简单,所以添加和剥离PCKS7填充的算法如下:
std :: string add_pkcs7_padding(std :: string s,std :: size_t n)
{
const std :: size_t fill = n - (s.length );
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);
}
(库级代码当然会测试 n
可以由 char
表示,并且在剥离期间输入字符串是非空的,填充有效。)
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
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.)
这篇关于mcrypt linux如何使用rijndael 256 cbc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!