将base64解码的字符串转换为无符号字符[32] [英] Convert base64 decoded string to unsigned char[32]

查看:319
本文介绍了将base64解码的字符串转换为无符号字符[32]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ed25519-donna 进行数字签名.

I'm using ed25519-donna to digitally sign.

密钥为unsigned char[32],签名为unsigned char[64].

我发现此base64编码,但它只能解码为string.

I've found this base64 encoding, but it only decodes into string.

我已经找到并尝试了许多技术,但是仍然不确定如何转换.

I've found and tried many techniques but am still unsure of how to convert.

如何将base64解码的string转换为unsigned char[32]?

How can a base64 decoded string be converted to an unsigned char[32]?

推荐答案

Gracchus:

是的.享受吧!

#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;
}

这篇关于将base64解码的字符串转换为无符号字符[32]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆