【问题标题】:Base64 decoding - bit shift results in unexpected end of char array in CBase64 解码 - 位移导致 C 中 char 数组意外结束
【发布时间】:2020-10-15 14:06:02
【问题描述】:

我已经使用了很多不同的函数来解码 C 中 Base64 编码的字符数组。现在,我正在使用这个函数来解码 Base64 字符数组。

    unsigned int b64_decode(const unsigned char* in, unsigned int in_len, unsigned char* out) {

    unsigned int i=0, j=0, k=0, s[4];

    for (i=0;i<in_len;i++) {
        s[j++]=b64_int(*(in+i));
        if (j==4) {
            out[k+0] = ((s[0]&255)<<2)+((s[1]&0x30)>>4);
            if (s[2]!=64) {
                out[k+1] = ((s[1]&0x0F)<<4)+((s[2]&0x3C)>>2);
                if ((s[3]!=64)) {
                    out[k+2] = ((s[2]&0x03)<<6)+(s[3]); k+=3;
                } else {
                    k+=2;
                }
            } else {
                k+=1;
            }
            j=0;
        }
    }

    return k;
}

问题是,对于像 QKSRjAEAAAAB3bW3rVpoJOA8bsb3eEuEEDiq 这样的 Base64 字符串,我得到的字符串只有五个字符,即使解码后的文本也应该更长。我尝试调试代码,这是因为第六个字符的位移结果为0,这意外地结束了字符串。在线 Base64 解码器可以毫无问题地解码上述字符串。

然后我想将解码后的字符串转换为十六进制。我是这样做的:

for (int i = 0, j = 0; i < size; ++i, j += 2) {
                sprintf(data_hex + j, "%02x", decoded_data[i] & 0xff);
            }

预期输入示例:QKSRjAEAAAAB3bW3rVpoJOA8bsb3eEuEEDiq

预期输出示例:40a4918c0100000001ddb5b7ad5a6824e03c6ec6f7784b841038aa

感谢您的回复。

【问题讨论】:

  • 你试过一些位于here的解码器吗?
  • 是的,我尝试了 OpenSSL 解决方案,但结果相同。
  • 结果是@¤‘Ś 大小为 5
  • 你在尝试使用 printf 吗?那是行不通的。试试fwrite(string, 1, length, stdout);

标签: c base64 bit-shift


【解决方案1】:

好吧,您花了一段时间才弄清楚您是从哪里获得此代码的。关键是意识到b64_int() 不是标准库函数。

因此,为了后代,您的代码的原始来源是 here,在文件 base64.hbase64.cc 中。

这是有效的程序:

#include <stdio.h>
#include <string.h>
#include "base64.h"

int main(void) {

  unsigned char in[] = "QKSRjAEAAAAB3bW3rVpoJOA8bsb3eEuEEDiq\0";
  int inLength = strlen((char*)in);

  unsigned char out[1000]; 
  unsigned int outLength = b64_decode(in, inLength, out);
  
  // Prints the result in Hexadecimal format.
  for (int i = 0; i < outLength; i++)
    printf("%x", out[i]);

  printf("\n");
  return 0;
}

关键是捕获b64_decode() 的返回值,它告诉您预期结果中有多少字节。目前还不清楚您是否这样做,因为您没有提供调用b64_decode() 函数的程序的代码示例。

Working online demo

【讨论】:

  • 感谢您的回复。这很好,只是对我来说,base64 编码的数据没有 '\0' 终止符,我需要将结果以十六进制格式存储以用于其他目的,这就是我在示例中使用 sprintf 的原因。
猜你喜欢
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 2012-04-09
  • 2016-04-19
  • 2014-07-23
  • 1970-01-01
相关资源
最近更新 更多