DES加密解密算法c++
时间: 2023-11-18 18:52:03 浏览: 110
DES加密解密算法是一种对称加密算法,使用相同的密钥进行加密和解密。下面是使用C语言实现DES加密解密算法的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/des.h>
void des_encrypt(char *key, char *input, char *output)
{
DES_cblock key2;
DES_key_schedule schedule;
memcpy(key2, key, 8);
DES_set_key_unchecked(&key2, &schedule);
DES_cblock input2,output2;
memcpy(input2, input, 8);
DES_ecb_encrypt(&input2, &output2, &schedule, DES_ENCRYPT);
memcpy(output, output2, 8);
}
void des_decrypt(char *key, char *input, char *output)
{
DES_cblock key2;
DES_key_schedule schedule;
memcpy(key2, key, 8);
DES_set_key_unchecked(&key2, &schedule);
DES_cblock input2,output2;
memcpy(input2, input, 8);
DES_ecb_encrypt(&input2, &output2, &schedule, DES_DECRYPT);
memcpy(output, output2, 8);
}
int main()
{
char key[8] = {'1', '2', '3', '4', '5', '6', '7', '8'};
char input[8] = {'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r'};
char output[8];
des_encrypt(key, input, output);
printf("encrypted data: ");
for (int i = 0; i < 8; i++) {
printf("%02x ", output[i]);
}
printf("\n");
des_decrypt(key, output, input);
printf("decrypted data: %s\n", input);
return 0;
}
```
以上代码使用了OpenSSL库中的DES加密解密函数,可以在Linux或者MacOS下编译运行。
阅读全文