使用OpenSSL哈希字符串为SHA256后,如何将Base64转ASCII?
解决SHA256哈希转ASCII十六进制字符串的问题
首先明确:SHA256哈希本质是32字节的二进制数据,你提到的Base64是对这个二进制数据的编码格式。数据库存储SHA256哈希通常用十六进制ASCII字符串(共64个字符,每个二进制字节对应两个十六进制字符),以下是两种场景的解决方案:
场景1:直接从原始字符串生成SHA256十六进制ASCII字符串
跳过Base64编码步骤,直接计算哈希后转十六进制:
#include <openssl/sha.h> #include <stdio.h> #include <string.h> // 将二进制SHA256哈希转换为十六进制ASCII字符串 void sha256_to_hex(unsigned char *hash, char *hex_str) { int i; for (i = 0; i < SHA256_DIGEST_LENGTH; i++) { sprintf(hex_str + (i * 2), "%02x", hash[i]); } hex_str[SHA256_DIGEST_LENGTH * 2] = '\0'; // 确保字符串终止 } int main() { const char *password = "your_test_password"; unsigned char hash[SHA256_DIGEST_LENGTH]; char hex_hash[SHA256_DIGEST_LENGTH * 2 + 1]; // 预留64+1个字符空间 // 计算SHA256哈希 SHA256((unsigned char *)password, strlen(password), hash); // 转换为十六进制ASCII字符串 sha256_to_hex(hash, hex_hash); printf("SHA256 Hex: %s\n", hex_hash); // 此时hex_hash就是可直接存储到数据库的ASCII字符串 return 0; }
编译时需链接OpenSSL库:gcc your_file.c -o your_program -lcrypto
场景2:已有Base64编码的SHA256结果,转成十六进制ASCII字符串
如果已经得到Base64编码的哈希值,需先解码回二进制数据,再转十六进制:
#include <openssl/sha.h> #include <openssl/bio.h> #include <openssl/evp.h> #include <stdio.h> #include <string.h> // Base64解码函数 int base64_decode(const char *base64_str, unsigned char *out_buf, size_t *out_len) { BIO *bio, *b64; int decode_len; size_t len = strlen(base64_str); b64 = BIO_new(BIO_f_base64()); bio = BIO_new_mem_buf(base64_str, len); bio = BIO_push(b64, bio); BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); // 忽略换行符 decode_len = BIO_read(bio, out_buf, len); *out_len = decode_len; BIO_free_all(bio); return decode_len; } // 二进制转十六进制(同场景1的函数) void sha256_to_hex(unsigned char *hash, char *hex_str) { int i; for (i = 0; i < SHA256_DIGEST_LENGTH; i++) { sprintf(hex_str + (i * 2), "%02x", hash[i]); } hex_str[SHA256_DIGEST_LENGTH * 2] = '\0'; } int main() { const char *base64_hash = "your_existing_base64_string"; unsigned char hash[SHA256_DIGEST_LENGTH]; size_t hash_len; char hex_hash[SHA256_DIGEST_LENGTH * 2 + 1]; // Base64解码回二进制SHA256哈希 if (base64_decode(base64_hash, hash, &hash_len) != SHA256_DIGEST_LENGTH) { printf("Base64解码错误,输入不是有效的SHA256 Base64编码\n"); return 1; } // 转十六进制ASCII字符串 sha256_to_hex(hash, hex_hash); printf("SHA256 Hex: %s\n", hex_hash); return 0; }
关键说明
- 十六进制ASCII字符串是数据库存储哈希的标准格式,每个字节用0-9、a-f(或A-F)的两个字符表示,完全符合ASCII编码要求
- 避免直接存储Base64格式,因为十六进制可读性更好,且多数数据库和验证工具默认支持十六进制哈希格式
内容的提问来源于stack exchange,提问作者Pedro Barbeira
相关产品推荐
相关产品推荐

