gpt4 book ai didi

c - c中的openssl aes解密

转载 作者:行者123 更新时间:2023-11-30 14:53:40 24 4
gpt4 key购买 nike

我正在尝试使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com