我试图使用 openssl 生成一个 32 字节的 base64 字符串,但它并不总是生成 32 字节的字符串,有时输出是乱码且显示不正确
#include <openssl/rand.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Base64Encode(const unsigned char* buffer, unsigned char** b64text) { //Encodes a binary safe base 64 string
BIO *bio, *b64;
BUF_MEM *bufferPtr;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); //Ignore newlines - write everything in one line
BIO_write(bio, buffer, strlen(buffer));
BIO_flush(bio);
BIO_get_mem_ptr(bio, &bufferPtr);
BIO_set_close(bio, BIO_NOCLOSE);
BIO_free_all(bio);
*b64text=bufferPtr->data;
return (0); //success
}
int main() {
unsigned char buffer[35], *base64EncodeOutput;
int ret = RAND_bytes(buffer, 32);
buffer[32]='\0'; // Null terminate
(void)Base64Encode(buffer, &base64EncodeOutput);
(void)printf("Return value of the operation was: %d\n%s\n", ret, base64EncodeOutput);
return EXIT_SUCCESS;
}
使用gcc rand_str.c -lcrypto && ./a.out | 编译运行tail -1
,有时会产生如下内容:
I6YaDVSRPw5Ux+2paY4u4ToMKtZXQoBj`�
有时输出的长度甚至不到 32 个字节。
我的目标是复制此命令的作用:
openssl rand -base64 32
我需要做哪些不同的事情?
最佳答案
BIO_write(bio, buffer, strlen(buffer));
NUL 是一个有效的随机字节,因此 strlen 有时会返回小于所需值 (32) 的值。
` 是由于 base64 缓冲区没有 NUL 终止符,因此它正在读取一些随机垃圾。我不知道有什么方法可以强制 OpenSSL 添加 NUL,但你可以告诉 printf 在哪里停止:
(void)printf("操作的返回值为:%d\n%.44s\n", ret, base64EncodeOutput);
关于c - 生成随机 n 字节 Base64 字符串后的不可打印字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38356835/