base64加解密

简介

​ Base64是一种用64种可见字符(英文字母、数字、符号等)来表示8位字节码的编码方式,其基于原信息的二进制码进行编码,由此其编码后的结果与原本的信息在语义上无关。

编码方式

​ Base64将没三个8Bit的字节转换为四个6Bit的字节,然后在6Bit的高位添0形成新的8Bit字节,即经Base64编码后信息的长度理论会增加1/3。

​ 例:

转换前(二进制) 转换后(二进制)
11111111,11111111,11111111 00111111,0011111,0011111,0011111

代码示例

  • 内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
string codeTest(string info) {
size_t len = info.size();
size_t mod = len % 3;
size_t sub = len / 3;

if(mod != 0)len += (3 - mod);

BYTE* unCrypt = (BYTE*)info.c_str();
size_t enLen = len / 3 * 4 + 1;
BYTE* enCrypt = (BYTE*)malloc(sizeof(BYTE*) * enLen);
size_t unCount = 0, enCount = 0;

if (enCrypt != nullptr) {
for (int i = 0; i < sub; i++) {
enCrypt[enCount++] = (unCrypt[3 * i] >> 2) + 62;
enCrypt[enCount] = unCrypt[3 * i] << 6;
enCrypt[enCount] += unCrypt[3 * i + 1] >> 2;
enCrypt[enCount] >>= 2;
enCrypt[enCount++] += 62;

enCrypt[enCount] = unCrypt[3 * i + 1] << 4;
enCrypt[enCount] += unCrypt[3 * i + 2] >> 4;
enCrypt[enCount] >>= 2;
enCrypt[enCount++] += 62;

enCrypt[enCount] = unCrypt[3 * i + 2] << 2;
enCrypt[enCount] >>= 2;
enCrypt[enCount++] += 62;

}

if (mod > 0) {
enCrypt[enCount++] = (unCrypt[3 * sub] >> 2) + 62;
if (mod == 1) {
enCrypt[enCount] = unCrypt[3 * sub] << 6;
enCrypt[enCount] >>= 2;
enCrypt[enCount++] += 62;
enCrypt[enCount++] = '=';
enCrypt[enCount++] = '=';
}
else {
enCrypt[enCount] = unCrypt[3 * sub] << 6;
enCrypt[enCount] += unCrypt[3 * sub + 1] >> 2;
enCrypt[enCount] >>= 2;
enCrypt[enCount++] += 62;

enCrypt[enCount] = unCrypt[3 * sub + 1] << 4;
enCrypt[enCount] += unCrypt[3 * sub + 2] >> 4;
enCrypt[enCount] >>= 2;
enCrypt[enCount++] += 62;

enCrypt[enCount++] = '=';
}
}

string out = (char*)enCrypt;
out = out.substr(0, enCount);
free(enCrypt);
return out;

}
return "code fail";
}
  • 运行结果

result1

0%