[英]Inconsistent encryption and decryption with OpenSSL RC4 in C++
首先,我知道 RC4 不是最安全的加密方法,而且它已經過時了,這只是一個學校項目。 只是想我把它放在那里,因為人們可能會問。
我正在使用 OpenSSL 的 RC4 在 C++ 中制作一個簡單的加密和解密程序。 我注意到加密和解密不一致。 這是我到目前為止所擁有的:
#include <fcntl.h>
#include <openssl/evp.h>
#include <openssl/rc4.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int inputFile = open(argv[1], O_RDONLY);
if (inputFile < 0) {
printf("Error opening file\n");
return 1;
}
unsigned char *keygen = reinterpret_cast<unsigned char*>(argv[2]);
RC4_KEY key;
size_t size = lseek(inputFile, 0, SEEK_END);
lseek(inputFile, 0, SEEK_SET);
unsigned char *fileIn = (unsigned char*) calloc(size, 1);
if (pread(inputFile, fileIn, size, 0) == -1) {
perror("Error opening read\n");
return 1;
}
unsigned char *fileOut = (unsigned char*) calloc(size, 1);
unsigned char *actualKey;
EVP_BytesToKey(EVP_rc4(), EVP_sha256(), NULL, keygen, sizeof(keygen), 1, actualKey, NULL);
RC4_set_key(&key, sizeof(actualKey), actualKey);
RC4(&key, size, fileIn, fileOut);
int outputFile = open(argv[3], O_WRONLY | O_TRUNC | O_CREAT, 0644);
if (outputFile < 0) {
perror("Error opening output file");
return 1;
}
if (pwrite(outputFile, fileOut, size, 0) == -1) {
perror("error writing file");
return 1;
}
close(inputFile);
close(outputFile);
free(fileIn);
free(fileOut);
return 0;
}
在 Ubuntu 中運行它的語法是:
./myRC4 test.txt pass123 testEnc.txt
大多數情況下,這可以正常工作,並加密和解密文件。 但是偶爾我會遇到分段錯誤。 如果我這樣做了,我會再次運行相同的命令,它可以很好地加密或解密,至少 for.txt 文件是這樣。
當我測試 on.jpg 文件或任何更大的文件時,問題似乎更常見且不一致。 我注意到有時圖像似乎已被解密(沒有分段錯誤),但實際上並沒有,我通過在原始文件和解密文件之間進行比較來測試。
關於我為什么會出現這些不一致的任何想法? 這與我如何為 fileOut 和 fileIn 分配 memory 有關系嗎?
先感謝您
在將actualKey
傳遞給EVP_BytesToKey
之前,需要指向適當大小的緩沖區。 因為你正在傳遞一個未初始化的指針,這將解釋你不一致的結果。
EVP_BytesToKey
的 文檔有這樣說:
如果
data
是NULL
,則EVP_BytesToKey()
返回存儲派生密鑰所需的字節數。
因此,您可以調用EVP_BytesToKey
一次,將data
參數設置為NULL
以確定actualKey
的長度,然后分配一個合適的緩沖區並再次調用它,同時actualKey
指向該緩沖區。
正如其他人所指出的,將sizeof(keygen)
傳遞給EVP_BytesToKey
也是不正確的。 您可能的意思是strlen (argv [2])
。
同樣,將sizeof(actualKey)
傳遞給RC4_set_key
也是一個錯誤。 相反,您應該傳遞EVP_BytesToKey
返回的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.