【问题标题】:How to decrypt ciphertext using openssl in C?如何在C中使用openssl解密密文?
【发布时间】:2013-07-15 19:11:27
【问题描述】:

如何解密在 python 中使用 AES 加密的密文。

加密.py

使用它,我使用 AES 制作了密文,并将其与 IV 连接起来 并将其写入文件 file.txt。

from Crypto.Cipher import AES
import hashlib, os
Plain = 'This is a string'             #String to Encrypt
key = 'mysecretpassword'      
#key = hashlib.md5(key).digest()       #Key
IV = 'InitializationVector'
IV = hashlib.md5(IV).digest()          #Initialization Vector
print len(IV)
Obj1 = AES.new(key, AES.MODE_CBC, IV)
Cipher = Obj1.encrypt(Plain)           #Cipher text
File = open('file.txt','w')
File.write(Cipher+IV)      #Concatenated the string and IV and
                           #wrote that to a file file.txt 
File.close()

解密.c

现在使用它,我从 file.txt 中获得了密文和 IV。现在我怎么能 使用 openssl 或任何其他库解密密码?

#include <stdio.h>
#include <string.h>
int main ()
{
  char filename[] = "file.txt";
  FILE *file = fopen ( filename, "r" );
  char key[] = "mysecretpassword";
  if (file != NULL) {
    char line [1000];
    char *p = line;
    char *array = line;
    while(fgets(line,sizeof line,file)!= NULL) {
      fprintf(stdout,"%s\n",line);
      char otherString[strlen(line)-15];
      strncpy(otherString, p, strlen(line)-16);
      otherString[strlen(otherString)-1] = '\0';
      printf("%s\n", otherString);//Here I got the Encrypted string
      array=array+(strlen(array)-16);
      printf("%s\n",array);//Here I got the IV
      //Here how to decrypt the Cipher text using "IV" and "key"
    }
    fclose(file);
  }
  else {
    perror(filename);
  }
  return 0;
}

我真的是个新手。请原谅我的问题中的错误,请随时帮助我,这将是您最大的善意。提前非常感谢。

【问题讨论】:

    标签: python c encryption cryptography openssl


    【解决方案1】:
    #include "openssl/aes.h"
    
      char buffer[1000];
      AES_KEY dec_key;
      AES_set_decrypt_key(key, 128, &dec_key);
      AES_cbc_encrypt(otherString, buffer, strlen(line) - 16, 
                         &dec_key,  array, AES_DECRYPT);
    //AES_KEY dec_key;
    //AES_set_decrypt_key(key, keySize, &dec_key);
    //AES_cbc_encrypt(ciphertext, result, textLen, &dec_key, iv, AES_DECRYPT);
    

    这对我有用。 128 是 16 字节密钥的位。

    但我相信,你在 -1 -15 -16 字符串长度的某个地方也有错误。可以更改while循环的这一部分来解决问题:

      int strLen = strlen(line) - 16;
    
      char otherString[strLen + 1];
      strncpy(otherString, p, strLen);
      otherString[strLen] = '\0';
    
      array = array + strLen;
    

    这里也是不错的 AES CBC 加密/解密 example codeyour working code

    【讨论】:

      猜你喜欢
      • 2018-11-28
      • 1970-01-01
      • 2012-04-07
      • 2018-10-27
      • 1970-01-01
      • 2015-10-06
      • 2019-04-20
      • 2014-01-08
      • 2021-03-17
      相关资源
      最近更新 更多