c - 解密(AES)和解码(Base64)后得到错误的纯文本

标签 c encryption base64

我编写了一个小型测试程序,它采用一串纯文本,使用 AES 对其进行加密,并将其编码为 Base 64。这部分似乎很好,但是当我尝试解码和解密时数据,我得到了错误的信息。

我的代码如下。我对 C 很陌生,所以我认为我犯了一个菜鸟错误,在某处错误地使用了指针或引用。我尝试在 EVP_DecryptFinal_ex 函数中查找自己的问题所在,但似乎找不到错误。笔记!请忽略ivkey的使用,这只是测试代码。

代码:

#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/pem.h>

// BASE 64 ENCODING
char* base64Encode(const unsigned char *message, const size_t length) {
    BIO *bio;
    BIO *b64;
    FILE* stream;

    int encodedSize = 4*ceil((double)length/3);
    char *buffer = (char*)malloc(encodedSize+1);

    stream = fmemopen(buffer, encodedSize+1, "w");
    b64 = BIO_new(BIO_f_base64());
    bio = BIO_new_fp(stream, BIO_NOCLOSE);
    bio = BIO_push(b64, bio);
    BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
    BIO_write(bio, message, length);
    (void)BIO_flush(bio);
    BIO_free_all(bio);
    fclose(stream);

    return buffer;
}


// BASE 64 DECODING
int calcDecodeLength(const char *b64input) {
    int len = strlen(b64input);
    int padding = 0;

    // Check for trailing '=''s as padding
    if (b64input[len-1] == '=' && b64input[len-2] == '=') {
        padding = 2;
    } else if (b64input[len-1] == '=') {
        padding = 1;
    }
    return (int)len*0.75 - padding;
}

int base64Decode(const char *b64message, unsigned char **buffer) {
    BIO *bio;
    BIO *b64;
    int decodeLen = calcDecodeLength(b64message);

    *buffer = (unsigned char*)malloc(decodeLen+1);
    FILE* stream = fmemopen((char*)b64message, strlen(b64message), "r");

    b64 = BIO_new(BIO_f_base64());
    bio = BIO_new_fp(stream, BIO_NOCLOSE);
    bio = BIO_push(b64, bio);
    BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
    size_t length = BIO_read(bio, *buffer, strlen(b64message));
    (*buffer)[length] = '\0';

    BIO_free_all(bio);
    fclose(stream);

    return decodeLen;
}


// AES ENCRYPTION
int encryptAes(const char *plainText, char *cipherText, const char *key) {
    unsigned char iv[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };

    int plainTextLength = 0;
    int cipherTextLength = 0;
    int blockLength = 0;
    static const int MAX_PADDING_LENGTH = 16;

    EVP_CIPHER_CTX encryptCtx;
    EVP_CIPHER_CTX_init(&encryptCtx);

    plainTextLength = strlen(plainText);
    cipherText = (unsigned char *) malloc(plainTextLength + MAX_PADDING_LENGTH);

    // Initialise the encryption with AES256 (CBC mode) using the key and IV
    EVP_EncryptInit_ex(&encryptCtx, EVP_aes_256_cbc(), NULL, key, iv);

    // Encrypt the plainText into the cipherText, update cipherTextLength with the length of the generated cipherText
    if (!EVP_EncryptUpdate(&encryptCtx, cipherText, &blockLength, (unsigned char *) plainText, plainTextLength) ) {
        printf("Error in EVP_EncryptUpdate \n");
        return 1;
    }
    cipherTextLength += blockLength;

    // Encrypt the "final" data remaining in a partial block
    if (!EVP_EncryptFinal_ex(&encryptCtx, cipherText + cipherTextLength, &blockLength)) {
        printf("Error in EVP_EncryptFinal_ex \n");
        return 1;
    }
    cipherTextLength += blockLength;

    EVP_CIPHER_CTX_cleanup(&encryptCtx);
    return cipherTextLength;
}


// AES DECRYPTION
int decryptAes(const char *cipherText, char *decipheredPlainText, int cipherTextLength, const char *key) {
    unsigned char iv[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };

    int plainTextLength = 0;
    int blockLength = 0;

    decipheredPlainText = (unsigned char *) malloc(cipherTextLength + 1);

    EVP_CIPHER_CTX decryptCtx;
    EVP_CIPHER_CTX_init(&decryptCtx);

    // Initialise the decryption with AES256 (CBC mode) using the key and IV
    EVP_DecryptInit_ex(&decryptCtx, EVP_aes_256_cbc(), NULL, key, iv);

    // Decrypt the cipherText into the plainText, update plainTextLength
    if (!EVP_DecryptUpdate(&decryptCtx, decipheredPlainText, &blockLength, cipherText, cipherTextLength)) {
        printf("Error in EVP_DecryptUpdate\n");
        return 1;
    }
    plainTextLength += blockLength;

    // Decrypt the "final" data remaining in a partial block
    if (!EVP_DecryptFinal_ex(&decryptCtx, decipheredPlainText + plainTextLength, &blockLength)) {
        printf("Error in EVP_DecryptFinal_ex\n");
        return 1;
    }
    plainTextLength += blockLength;

    EVP_CIPHER_CTX_cleanup(&decryptCtx);
    return plainTextLength;
}


int main(int argc, char **argv) {
    unsigned char key[] = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
    const char *plainText = "cipher cipher cipher cipher CIPHER TEXT! 187? 1$5 78@2 14 .TӒ��틪�ձ1z.$�?�U���<y";
    printf("Original Plain Text\t[%s]\n", plainText);

//////////////
// ENCRYPTION
//////////////
    // Encrypt the plain text using AES
    unsigned char cipherText[180];
    int cipherTextLength = encryptAes(plainText, cipherText, key);
    printf("Cipher Length\t\t[%d]\n", cipherTextLength);

    // Base64 encode the buffer
    char* encodedCipherText = base64Encode(cipherText, cipherTextLength);
    printf("Base64 is\t\t[%s]\n", encodedCipherText);

//////////////
// DECRYPTION
//////////////
    // Decode the Base64 string
    unsigned char* decodedCipherText;
    int decodedCipherTextLength = base64Decode(encodedCipherText, &decodedCipherText);
    printf("Decoded Cipher Length\t[%d]\n", decodedCipherTextLength);

    // Decrypt the cipher text
    unsigned char decryptedPlainText[180];
    int decryptedPlainTextLength = decryptAes(decodedCipherText, decryptedPlainText, decodedCipherTextLength, key);
    printf("Decrypted Plain Text\t[%s]\n", decryptedPlainText);

    // Compare before and after
    if (strcmp(plainText, (char *) decryptedPlainText) == 0) {
        printf("Decrypted data matches input data.\n");
    } else {
        printf("Decrypted data does not match input data.\n");
    }

    return 0;
}

命令:

gcc AesTest2.c -lcrypto -std=c99 -lm

输出:

Original Plain Text     [cipher cipher cipher cipher CIPHER TEXT! 187? 1$5 78@2 14 .TӒ��틪�ձ1z.$�?�U���<y]
Cipher Length           [112]
Base64 is               [AQAAAAAAAACIEYLbPgAAAOh04wX/fwAAdgAAAAAAAAAJAAAAAAAAAP504wX/fwAAAAAAAAAAAADgFILbPgAAABB14wX/fwAAlwWp2z4AAAAodeMF/38AAAAAAAABAAAA2LGg2z4AAABxB0AAAAAAAA==]
Decoded Cipher Length   [112]
Error in EVP_DecryptFinal_ex
Decrypted Plain Text    [�t��]
Decrypted data does not match input data.

如果有经验丰富的 C 开发人员提供任何帮助,我们将不胜感激。非常感谢。

最佳答案

您在 main() 中声明缓冲区,并将对它们的引用传递给 en/decrypt 函数。

在这些加密/解密函数中,您可以用 malloc() 返回的结果覆盖从 main() 接收的缓冲区地址。然后计算出的数据被写入新分配的内存中。从这两个加密/解密函数返回时,对后者的引用会丢失,从而导致内存泄漏。

由于 main() 中的所有缓冲区根本没有被触及。

您可以通过在调用加密/解密函数之前将它们设置为全部 0 并在从加密/解密函数返回后将它们打印出来来轻松证明这一点。

关于c - 解密(AES)和解码(Base64)后得到错误的纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18617436/

相关文章:

c++ - 从用户模式创建 BSOD?

python - python中的索引错误

c# - 使用 C# 进行文件压缩的​​最佳方法

java - 如何读取以链形式提供的 Base64 文件?

c - 在 C 程序中使用 golang 函数

c++ - 您如何对内存消耗进行基准测试?

c++ - 迭代已知维度矩阵的最快方法

linux - 如何通过 ftp 从一台 Linux 机器(客户端)传输加密文件并在另一台 Linux 机器(服务器)上解密

android - 将视频转换为 base64 得到 "out of memory error"

java - 在java中将base64字符串转换为服务器端的图像