c - OpenSSL C Cryptopals 挑战7

标签 c encryption openssl

我一直在尝试学习 OpenSSL C API。我发现有趣的cryptopals挑战页面并想尝试一些简单的挑战。我接受了挑战 7,AES ECB:https://cryptopals.com/sets/1/challenges/7

阅读 OpenSSL 文档后,我想做一些编码。我从 OpenSSL wiki 页面复制粘贴了下面的大部分代码。但不知何故我无法完成这项工作。我试着用谷歌搜索这个错误,发现人们在 Python 中轻松解决了这个挑战。 ,但没有找到 C 的任何内容。

输入文件以 Base64 编码,并带有换行符。所以我首先要做的是删除换行符。我是使用 tr 工具手动完成的,而不是以编程方式完成的。

tr -d '\n' < cipertext > ciphertext.no_newlines

接下来我解码了它,也是手动的:

base64 -d ciphertext.no_newlines > ciphertext.no_newlines_decoded

接下来,我复制了 OpenSSL 网页 https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption 中的大部分内容。 :

加密和解密函数是文档中的精确副本。我只修改了main函数。我还从某处复制了 readFile 函数(测试它工作正常)。

我是这样编译的:

gcc -I /opt/openssl/include challenge7.c /opt/openssl/lib/libcrypto.a -lpthread -ldl -o challenge7 

但我收到此错误:

140095710082880:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:crypto/evp/evp_enc.c:570:
[1]    24550 abort (core dumped)  ./challenge7

我用谷歌搜索了这个错误,发现它可能与 OpenSSL 版本之间的不兼容有关,即用于加密文件的版本和我计算机上的版本之间的不兼容。难道真的是这个原因吗?如果是这样,那么这是有史以来最糟糕的库,我无法使用相同的算法使用不同版本的库解密文件。我有点不敢相信这一点。我听说 OpenSSL 很糟糕,但不知怎的,我不相信这是这个错误的原因。

有人可以帮我找出我一直做错的地方吗?完整代码如下:

#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <string.h>

char* readFile(char* filename, int* size) 
{
    char* source = NULL;

    FILE *fp = fopen(filename, "r");
    if (fp != NULL) {
        if (fseek(fp, 0L, SEEK_END) == 0) {
            long bufsize = ftell(fp);
            if (bufsize == -1) {
                fputs("ftell error", stderr);
            } else {
                source = malloc(sizeof(char) * (bufsize + 1));
                if (fseek(fp, 0L, SEEK_SET) != 0) { 
                    fputs("fseek error", stderr);
                }

                size_t nl = fread(source, sizeof(char), bufsize, fp);
                if (ferror(fp) != 0) {
                    fputs("Error reading file", stderr);
                } else {
                    source[nl] = '\0';
                    *size = nl;
                }
            }
        }
        fclose(fp);
    }
    return source;
}

void handleErrors(void)
{
    ERR_print_errors_fp(stderr);
    abort();
}

int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
            unsigned char *iv, unsigned char *ciphertext)
{
    EVP_CIPHER_CTX *ctx;

    int len;

    int ciphertext_len;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new()))
        handleErrors();

    /*
     * Initialise the encryption operation. IMPORTANT - ensure you use a key
     * and IV size appropriate for your cipher
     * In this example we are using 256 bit AES (i.e. a 256 bit key). The
     * IV size for *most* modes is the same as the block size. For AES this
     * is 128 bits
     */
    if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
        handleErrors();

    /*
     * Provide the message to be encrypted, and obtain the encrypted output.
     * EVP_EncryptUpdate can be called multiple times if necessary
     */
    if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
        handleErrors();
    ciphertext_len = len;

    /*
     * Finalise the encryption. Further ciphertext bytes may be written at
     * this stage.
     */
    if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
        handleErrors();
    ciphertext_len += len;

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    return ciphertext_len;
}

int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
            unsigned char *iv, unsigned char *plaintext)
{
    EVP_CIPHER_CTX *ctx;

    int len;

    int plaintext_len;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new()))
        handleErrors();

    /*
     * Initialise the decryption operation. IMPORTANT - ensure you use a key
     * and IV size appropriate for your cipher
     * In this example we are using 256 bit AES (i.e. a 256 bit key). The
     * IV size for *most* modes is the same as the block size. For AES this
     * is 128 bits
     */
    if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
        handleErrors();

    /*
     * Provide the message to be decrypted, and obtain the plaintext output.
     * EVP_DecryptUpdate can be called multiple times if necessary.
     */
    if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
        handleErrors();
    plaintext_len = len;

    /*
     * Finalise the decryption. Further plaintext bytes may be written at
     * this stage.
     */
    if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len))
        handleErrors();
    plaintext_len += len;

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    return plaintext_len;
}

int main (void)
{
    unsigned char *key = (unsigned char *)"59454C4C4F57205355424D4152494E45";
    unsigned char *iv = NULL;

    int decryptedtext_len;
    int ciphertext_len;
    char* ciphertext = readFile("ciphertext.no_newlines_decoded", &ciphertext_len);

    unsigned char decryptedtext[10000];
    decryptedtext_len = decrypt(ciphertext, ciphertext_len, key, iv, decryptedtext);
    decryptedtext[decryptedtext_len] = '\0';
    printf("Decrypted text is:\n");
    printf("%s\n", decryptedtext);

    return 0;
}

最佳答案

可能的原因是您使用的是 AES-CBC 密码,而不是建议的 AES-ECB (EVP_DecryptInit_ex(ctx, **EVP_aes_256_cbc()** ,NULL,键,iv))。

实际的错误可能是由于将 NULL 指针作为 CBC 密码的 IV 传递而引起的(我不知道这个 API 在这种情况下实际如何工作,但 IV 对于 CBC 加密模式是强制性的)。

因此请尝试使用适当的 EVP_aes_128_ecb() 加密模式。

已更新

另一件会导致 EVP_DecryptFinal_ex 错误的事情是您的输入数据字节长度不是 16 的倍数(AES block 长度)。检查您的 ciphertext.no_newlines_decoded 大小是否是 16 的倍数。

下一点是 OpenSSL API 对字节而不是以零结尾的字符串进行操作。因此,您应该将“rb”而不是“r”传递给 fopen 调用,并读取字节而不附加任何零终止符。

我还认为您错误地使用了 key ,我认为您应该按给定方式定义并传递它(unsigned char *key = (unsigned char *)"YELLOW SUBMARINE")。虽然以您的方式使用 key 不会导致您遇到错误,但会导致解密文本不正确。

关于c - OpenSSL C Cryptopals 挑战7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58919056/

相关文章:

c++ - 字符串未使用 <openssl/aes> 正确解密

c - newNode 内存泄漏/分段故障

c - 为什么缓冲区位于 main() 本地,然后无法显式关闭流是一个错误?

encryption - TLS over TLS 可能吗?

nginx - CentOS 安装 nginx 失败

ios - 使用位码构建 openSSL

C编程分段故障链表程序

C 自由() : invalid pointer allocated in other function

javascript - 当我在 JavaScript 中计算 1000^1000 时如何避免无穷大的结果

java - 如何处理 AES CTR 的 IV/Nonce/Counter?