【问题标题】:OpenSSL C Cryptopals Challenge7OpenSSL C Cryptopals 挑战赛7
【发布时间】:2019-11-18 16:31:21
【问题描述】:

我一直在尝试学习 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 复制了大部分内容:

加密和解密函数与文档完全相同。我只修改了主要功能。我还从某个地方复制了 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;
}

【问题讨论】:

    标签: c encryption openssl


    【解决方案1】:

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

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

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

    更新

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

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

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

    【讨论】:

    • 哎呀。我的错。以为我改变了这个......感谢您发现这一点。但不幸的是,将其更改为 128_ecb 后没有任何变化。错误是一样的:-(
    • 哦,我明白了。很快我就会到我的电脑上运行你的代码。我会尝试找出导致错误的原因并更新我的答案
    • Henadzi Matuts - 你是对的。我的错。现在一切正常。谢谢!密码必须是“YELLOW SUBMARINE”,无需将其修改为 ASCII HEX 版本(就像我在命令行 openssl 工具中所做的那样)。我把这个弄混了。现在一切都清楚了。并且打开文件模式可以是“r”,不一定是“rb”。再次感谢。
    • @YotKay,我终于能够运行实际代码了。确实,它适用于正确的键,所以我很高兴我的想法很有帮助。然而,考虑到“r”/“rb”,对我来说需要使用“rb”,如果 fread 遇到一些特殊字符(在 Windows 上尝试过),它会切断输入。还有一件事,使用不正确的密钥解密会导致错误,因为 OpenSSL 加密上下文默认启用了填充(检查 EVP_CIPHER_CTX_set_padding 函数)。如果您将禁用填充,并尝试使用一些损坏的密钥解密数据,则不会出现错误而不是无效的明文。
    猜你喜欢
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 2018-01-21
    相关资源
    最近更新 更多