我正在使用 openssl 库对 base64 进行编码和解码,这是我的加密代码
#include <openssl/buffer.h>
#include <stdlib.h>
char *base64(const unsigned char *input, int length);
int main(int argc, char **argv)
{
char nonce[10];
srand(time(NULL));
printf("rand():%d\n", rand());
sprintf(nonce, "%d", rand());
char *output = base64(nonce, sizeof(nonce));
printf("Base64: *%s*\n", output);
free(output);
}
char *base64(const unsigned char *input, int length)
{
BIO *bmem, *b64;
BUF_MEM *bptr;
char *buff;
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bmem);
BIO_write(b64, input, length);
BIO_flush(b64);
BIO_get_mem_ptr(b64, &bptr);
buff = (char *) malloc(bptr->length);
memcpy(buff, bptr->data, bptr->length-1);
buff[bptr->length-1] = '\0';
BIO_free_all(b64);
return buff;
}
当 NjI0MjQ3MwAECA== rand() 输出为 1308702736 时的 o/p (这是 rand gen o/p 的一个实例的示例),当我使用解码函数解码此值时,我得到 6242473,它完全不同,解码时我必须得到 1308702736,
我的解码功能如下
#include <string.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
char *unbase64(unsigned char *input, int length);
int main(int argc, char **argv)
{
char *output = unbase64("NjI0MjQ3MwAECA==\n", strlen("NjI0MjQ3MwAECA==\n"));
printf("Unbase64: *%s*\n", output);
free(output);
}
char *unbase64(unsigned char *input, int length)
{
BIO *b64, *bmem;
char *buffer = (char *)malloc(length);
memset(buffer, 0, length);
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new_mem_buf(input, length);
bmem = BIO_push(b64, bmem);
BIO_read(bmem, buffer, length);
BIO_free_all(bmem);
return buffer;
}
注意:要编译此代码 v 必须使用 -lcrypto 我需要帮助来解决这个问题我被困在这里,搜索解决方案但没有得到任何解决方案,并且还有一个疑问为什么 base64 解码器 b 的输入被 \n 终止?有人能帮我解决这个问题吗