我正在使用ed25519-donna进行数字签名。
密钥为unsigned char[32]
,签名为unsigned char[64]
。
我找到this base64 encoding,但它只会解码为string
。
我发现并尝试了很多技巧,但我仍然不确定如何转换。
如何将base64解码string
转换为unsigned char[32]
?
答案 0 :(得分:3)
格拉:
在这里。享受!
#include <iostream>
#include <string>
struct BASE64_DEC_TABLE {
signed char n[256];
BASE64_DEC_TABLE() {
for(int i=0; i<256; ++i) n[i] = -1;
for(unsigned char i='0'; i<='9'; ++i) n[i] = 52+i-'0';
for(unsigned char i='A'; i<='Z'; ++i) n[i] = i-'A';
for(unsigned char i='a'; i<='z'; ++i) n[i] = 26+i-'a';
n['+'] = 62;
n['/'] = 63;
}
int operator [] (unsigned char i) const { return n[i]; }
};
size_t Base64Decode(const std::string& source, void* pdest, size_t dest_size) {
static const BASE64_DEC_TABLE b64table;
if(!dest_size) return 0;
const size_t len = source.length();
int bc=0, a=0;
char* const pstart = static_cast<char*>(pdest);
char* pd = pstart;
char* const pend = pd + dest_size;
for(size_t i=0; i<len; ++i) {
const int n = b64table[source[i]];
if(n == -1) continue;
a |= (n & 63) << (18 - bc);
if((bc += 6) > 18) {
*pd = a >> 16; if(++pd >= pend) return pd - pstart;
*pd = a >> 8; if(++pd >= pend) return pd - pstart;
*pd = a; if(++pd >= pend) return pd - pstart;
bc = a = 0;
} }
if(bc >= 8) {
*pd = a >> 16; if(++pd >= pend) return pd - pstart;
if(bc >= 16) *(pd++) = a >> 8;
}
return pd - pstart;
}
int main() {
std::string base64_string = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=";
unsigned char decoded_data[32] = {0};
Base64Decode(base64_string, decoded_data, sizeof(decoded_data));
for(auto b : decoded_data) {
std::cout << static_cast<unsigned>(b) << ' ';
}
std::cout << std::endl;
return 0;
}
答案 1 :(得分:0)
更有效的base64解码解决方案是使用Boost C ++库。使用Boost C ++库的Base64解码功能可在以下位置找到:attempt to decode a value not in base64 char set