c - c编程中使用openssl使用文件IO进行三重DES加密解密

标签 c pointers encryption openssl

我正在尝试对文本文件 input.txt 进行 Triple DES 加密,并将加密数据保存到 output.txt。然后再次在同一个程序中,我解密output.txt并将其保存到recovered.txt。

加密有效。但是recovered.txt 没有得到与input.txt 一样的精确输出

我在这里做错了什么? 屏幕截图包含示例输入/输出

My input.txt output.txt and recovered.txt. recovered.txt should be same as input.txt

这是我的代码

#include <openssl/des.h>    
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DES_BLOCK_SIZE 8


FILE *fp;
FILE *rp;
FILE *op;
size_t count;   
char * buffer;
int bytes_read, bytes_written;
unsigned char indata[DES_BLOCK_SIZE]; 
unsigned char outdata[DES_BLOCK_SIZE];

DES_cblock cb1 = { 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE };
DES_cblock cb2 = { 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE };
DES_cblock cb3 = { 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE, 0xAE };

DES_key_schedule ks1;
DES_key_schedule ks2;
DES_key_schedule ks3;

DES_cblock cblock = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

void encrypt(){ 
  DES_set_odd_parity(&cblock);


      fp=fopen("input.txt","a+b");
      op=fopen("output.txt","w");
      if (fp==NULL) {fputs ("File error",stderr); exit (1);}   
      if (op==NULL) {fputs ("File error",stderr); exit (1);}      

while (1) {     

    bytes_read = fread(indata, 1, DES_BLOCK_SIZE, fp); 

    DES_ede3_cbc_encrypt(indata, outdata, DES_BLOCK_SIZE, &ks1, &ks2, &ks3,&cblock, 1);
    bytes_written = fwrite(outdata, 1, bytes_read, op); 
    if (bytes_read < DES_BLOCK_SIZE) 
    break; 
  }   

  fclose (fp); 
  fclose (op);
  free (buffer); 
}

void decrypt(){
  //Opening files where text cipher text is read and the plaintext recovered   
  memset(cblock,0,sizeof(DES_cblock));      
  DES_set_odd_parity(&cblock);

  rp=fopen("recovered.txt","w");
  op=fopen("output.txt","a+b");
  if (rp==NULL) {fputs ("File error",stderr); exit (1);}   
  if (op==NULL) {fputs ("File error",stderr); exit (1);} 

  //Initializing the encryption KEY
  while (1) {     

    bytes_read = fread(indata, 1, DES_BLOCK_SIZE, op);

    DES_ede3_cbc_encrypt(indata, outdata, DES_BLOCK_SIZE, &ks1, &ks2, &ks3, &cblock,0);
    bytes_written = fwrite(outdata, 1, bytes_read, rp); 
    if (bytes_read < DES_BLOCK_SIZE)
    break; 
    }   
  fclose (rp); 
  fclose (op);
  free (buffer); 
}

int main() {

  encrypt();
  decrypt();  
  return 0;
}

最佳答案

我已经测试了你的代码,这里有一些你需要注意的地方:

加密

  • 使用 PKCS#5 填充方案,here这是一个简单的解释
  • 由于您已完成填充,因此始终写入 DES_BLOCK_SIZE 量的数据作为加密输出

解密

  • 确保始终读取 DES_BLOCK_SIZE 量的数据作为输入
  • 在写入文件之前去除填充

关于c - c编程中使用openssl使用文件IO进行三重DES加密解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22828235/

相关文章:

c - freeDiameter - 事件时间戳

c - 黄金分割例程分割错误

c - 将 char 指针复制到 char 指针数组时发生段错误

go - Go 运行时中的中间轮 AES 加密是如何工作的?

security - 如何对加密库进行基准测试?

php - 在 Javascript 和 PHP 之间混淆 POST 变量

c - scanf 之后 fgets 不起作用

c - 这个基于指针的代码的答案是什么?为什么?

c - (void **)&x 和 (void *)x 有什么区别?

c - 如何在 C 中使用指针算术将值从一个数组复制到另一个数组