📄 base64.cpp
字号:
#include "stdafx.h"
static const unsigned char alphabet[65] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
size_t b64Decode(const char *src,
unsigned char *dst, size_t dstsize)
{
char decoder[256];
int i, bits, c;
unsigned char *pdst = dst;
for (i = 0; i < 256; ++i)
decoder[i] = 64;
for (i = 0; i < 64 ; ++i)
decoder[alphabet[i]] = i;
bits = 1;
while(*src)
{
c = (unsigned char)(*(src++));
if (c == '=')
{
if (bits & 0x40000)
{
if (dstsize < 2) break;
*(pdst++) = (bits >> 10);
*(pdst++) = (bits >> 2) & 0xff;
break;
}
if (bits & 0x1000 && dstsize)
*(pdst++) = (bits >> 4);
break;
}
// skip invalid chars
if (decoder[c] == 64)
continue;
bits = (bits << 6) + decoder[c];
if (bits & 0x1000000)
{
if (dstsize < 3) break;
*(pdst++) = (bits >> 16);
*(pdst++) = (bits >> 8) & 0xff;
*(pdst++) = (bits & 0xff);
bits = 1;
dstsize -= 3;
}
}
return pdst-dst;
}
void b64Decode(string& dest, const string& src)
{
size_t limit = src.length()/4*3;
dest.resize(limit+2);
unsigned size = b64Decode(src.c_str(), (unsigned char*)dest.c_str(), limit);
dest.resize(size);
}
/* How many bytes it will take to store LEN bytes in base64. */
#define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
/* Encode the string S of length LENGTH to base64 format and place it
to STORE. STORE will be 0-terminated, and must point to a writable
buffer of at least 1+BASE64_LENGTH(length) bytes. */
static void base64_encode (const char *s, char *store, int length)
{
/* Conversion table. */
static char tbl[64] = {
'A','B','C','D','E','F','G','H',
'I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X',
'Y','Z','a','b','c','d','e','f',
'g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v',
'w','x','y','z','0','1','2','3',
'4','5','6','7','8','9','+','/'
};
int i;
unsigned char *p = (unsigned char *)store;
/* Transform the 3x8 bits to 4x6 bits, as required by base64. */
for (i = 0; i < length; i += 3)
{
*p++ = tbl[s[0] >> 2];
*p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
*p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
*p++ = tbl[s[2] & 0x3f];
s += 3;
}
/* Pad the result if necessary... */
if (i == length + 1)
*(p - 1) = '=';
else if (i == length + 2)
*(p - 1) = *(p - 2) = '=';
/* ...and zero-terminate it. */
*p = '\0';
}
/* Create the authentication header contents for the `Basic' scheme.
This is done by encoding the string `USER:PASS' in base64 and
prepending `HEADER: Basic ' to it. */
char * basic_authentication_encode (const char *user, const char *passwd)
{
char *t1, *t2, *res;
int len1 = strlen (user) + 1 + strlen (passwd);
int len2 = BASE64_LENGTH (len1);
t1 = (char *)malloc (len1 + 1);
sprintf (t1, "%s:%s", user, passwd);
res = (char *)malloc (6+len2 + 1);
strcpy(res, "Basic ");
t2 = res+6;
base64_encode (t1, t2, len1);
free(t1);
return res;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -