【发布时间】:2016-08-04 15:59:37
【问题描述】:
我正在尝试使用 16 字节密钥在 DES 中加密具有动态长度的文本,但是密钥和文本的块大小存在问题,我正在使用 openssl 库进行 DES 加密。如何使用长度为 16 字节的密钥。
这是我的例子:
char * Encrypt( char Key, char *Msg, int size) {
static char* Res;
DES_cblock Key2;
DES_key_schedule schedule;
Res = ( char * ) malloc( size );
memcpy(Key2, Key, 8);
DES_set_odd_parity( &Key2 );
DES_set_key_checked( &Key2, &schedule );
unsigned char buf[9];
buf[8] = 0;
DES_ecb_encrypt(( DES_cblock ) &Msg, ( DES_cblock ) &buf, &schedule, DES_ENCRYPT );
memcpy(Res, buf, sizeof(buf));
return (Res);
}
int main(int argc, char const *argv[]) {
char key[] = "password";
char clear[] = "This is a secret message";
char *encrypted;
encrypted = (char *) malloc(sizeof(clear));
printf("Clear text\t : %s \n",clear);
memcpy(encrypted, Encrypt(key, clear, sizeof(clear)), sizeof(clear));
printf("Encrypted text\t : %s \n",encrypted);
return 0;
}
【问题讨论】:
-
小心,您显示的代码中存在内存泄漏。你在哪里释放你在
Encrypt函数中分配的内存? -
AES 是否接受 16 字节密钥?
-
AES 允许 128、192 和 256 位密钥。
-
AES = "高级加密标准", DES = "不推荐使用的加密标准"™。
-
由于这是 C++ 代码,您不应该使用原始指针,也不应该进行手动内存管理。要安全地管理内存缓冲区,请使用
std::vector<char>或std::unique_ptr<char[]>。