c - c中的openssl aes解密

标签 c openssl aes

我正在尝试使用 php 和 c 创建一个 openssl aes 加密/解密。我能够使用 php 和 openssl 加密文本,这将以 base64 字符串输出加密的字符串。我试图将这个base64编码的字符串传递给c程序,以使用c中的openssl对其进行解码。

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();

    if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
        handleErrors();

    if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
        handleErrors();
    plaintext_len = len;


    if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors();
    plaintext_len += len;

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    return plaintext_len;
}

有没有办法在c中使用openssl解密base64字符串?我可以使用类似

的命令行来解密它
openssl enc -aes-256-cbc -d -in file.encrypted -nosalt -nopad -K 31323334353637383132333435363738 -iv 31323334353637383132333435363738

提前致谢

最佳答案

您正在直接处理 Base64 编码数据。 首先需要对数据进行base64解码以获得实际的加密数据。然后应用AES解密得到解密数据

BIO *b64, *bmem;
buffer = (char *)malloc(datalength);
b64 = BIO_new(BIO_f_base64());
if(b64 == NULL)
{

    return NULL;
}
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);  
bmem = BIO_new_mem_buf(input, length);
if(bmem == NULL)
{
    return NULL;
}
bmem = BIO_push(b64, bmem);
if(bmem == NULL)
{
    return NULL;
}

ret = BIO_read(bmem, buffer, length);
if(ret == 0)
{
    return NULL;
}
BIO_free_all(bmem);
return buffer;

关于c - c中的openssl aes解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47093199/

相关文章:

c - 矩阵邻居 C 代码

c - 加载共享库时出错 : libcmocka. so.0: 没有这样的文件或目录

c - 使用 while 循环在 C 中切换

c++ - 未解析的外部符号 OpenSSL 库 C++

c - 通过管道使用 openssl 安全吗?

javascript - C# .NET AES 与 JavaScript 的互操作性

php - 在 PHP 中从 ISO C 时间戳转换为整数纪元

python - 从 Python 中的 PrivateKey/CertificateRequest/Certificate 中提取公钥模数,格式与 OpenSSL 相同

encryption - 使用 OpenSSL 问题输出解密字符串

php - 具有 PKCS7 填充编码数据的 AES 256 具有一半 ECB 和一半 CBC block