我目前正在为我的班级开发 SSL 加密的 VFS 文件系统,但在文件加密方面遇到了一些问题。他们为我们提供的示例需要两个文件,输入和输出,其中输入文件文本被读取、加密并作为加密文件写入输出。但是,对于分配,我们需要获取单个输入文件并对该文件本身进行加密,而不是返回加密的输出。
我在下面编写了这段代码,试图获取所有加密文本并将其存储在缓冲区中,然后用保存在缓冲区中的加密文本覆盖输入文件。在将缓冲区写入输入文件的最后一个 for 循环中,我在代码中遇到了段错误。当count = 4时发生段错误;z 等于 3。我认为它正在发生,因为我以某种方式错误地存储了数据,但是我似乎无法在这里指出确切的问题。
任何帮助,将不胜感激。
这是代码。
#define BLOCKSIZE 1024
#define FAILURE 0
#define SUCCESS 1
extern int do_crypt(FILE* in, int action, char* key_str){
/* Local Vars */
/* Buffers */
unsigned char inbuf[BLOCKSIZE];
int inlen;
int z;
int count = 0;
/* Allow enough space in output buffer for additional cipher block */
unsigned char outbuf[BLOCKSIZE + EVP_MAX_BLOCK_LENGTH];
unsigned char **storebuf = malloc((BLOCKSIZE + EVP_MAX_BLOCK_LENGTH)*20);
int outlen;
//int writelen;
/* OpenSSL libcrypto vars */
EVP_CIPHER_CTX ctx;
unsigned char key[32];
unsigned char iv[32];
int nrounds = 5;
/* tmp vars */
int i;
/* Setup Encryption Key and Cipher Engine if in cipher mode */
if(action >= 0){
if(!key_str){
/* Error */
fprintf(stderr, "Key_str must not be NULL\n");
return 0;
}
/* Build Key from String */
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), NULL,
(unsigned char*)key_str, strlen(key_str), nrounds, key, iv);
if (i != 32) {
/* Error */
fprintf(stderr, "Key size is %d bits - should be 256 bits\n", i*8);
return 0;
}
/* Init Engine */
EVP_CIPHER_CTX_init(&ctx);
EVP_CipherInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key, iv, action);
}
/* Loop through Input File*/
for(;;){
/* Read Block into inbuf */
inlen = fread(inbuf, sizeof(*inbuf), BLOCKSIZE, in);
if(inlen <= 0){
/* EOF -> Break Loop */
break;
}
/* If in encrypt/decrypt mode, perform cipher transform on block */
if(action >= 0){
/*set up ctx with passed params */
if(!EVP_CipherUpdate(&ctx, outbuf, &outlen, inbuf, inlen))
{
/* Error */
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
}
/* If in pass-through mode. copy block as is */
else{
memcpy(outbuf, inbuf, inlen);
outlen = inlen;
}
storebuf[count] = malloc(outlen*sizeof(*outbuf));
memcpy(storebuf[count], outbuf, outlen);
/* Write Block */
//writelen = fwrite(outbuf, sizeof(*outbuf), outlen, out);//THIS LINE
if(storebuf[count] == NULL){
/* Error */
perror("malloc error");
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
count++;
}
count++;
/* If in cipher mode, handle necessary padding */
if(action >= 0){
/* Handle remaining cipher block + padding */
if(!EVP_CipherFinal_ex(&ctx, outbuf, &outlen))
{
/* Error */
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
/* Write remaining cipher block + padding*/
//fwrite(outbuf, sizeof(*inbuf), outlen, out);
storebuf[count] = malloc(outlen*sizeof(*inbuf));
memcpy(storebuf[count], outbuf, inlen);
EVP_CIPHER_CTX_cleanup(&ctx);
}
printf("%d, %s", count, storebuf[count]);
rewind(in);
for(z = 0; z < count-1; z++){
fwrite(storebuf[z], sizeof(*storebuf), strlen((char*)storebuf[z]), in);
}
/* Success */
return 1;
}