Base64 encoding and decoding

zhaozj2021-02-17  33

Generally, most of the "=" is not "Base64" encoding format, only "quoted-printable" encoding format will often appear "=" although it is MIME encoding, but the algorithm is different, "quoted-printable" I am not too Clear. Let's talk about Base64.

The base64 algorithm is converted to 4 6-digit characters (32), so the length of the encoded can be expanded by 1/3, and the encoding switch needs to be used to use a Base64 code table: Table 1 : The base64 alphabet

Value Encoding Value Encoding 0 A 17 R 34 I 51 Z 1 B 18 S 35 J 52 0 2 C 19 T 36 K 53 1 3 D 20 U 37 L 54 2 4 E 21 V 38 M 55 3 5 F 22 W 39 N 56 4 6 G 23 x 40 o 57 5 7 H 24 y 41 P 58 6 8 i 25 Z 42 Q 59 7 9 J 26 A 43 R 60 8 10 K 27 B 44 S 61 9 11 L 28 C 45 T 62 12 m 29 D 46 U 63/13 N 30 E 47 V 14 O 31 F 48 W (PAD) = 15p 32 g 49 x 16 Q 33 H 50 Y can be saved as a constant in VB: private const base64table = "Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 / ="

The encoding process is like this. The first character is first shifted by 2 bits to get the first target character's Base64 table location, according to this value to take the corresponding character, the first target character, and then the first character Left shift 6 digits plus the second character right shift 4 bits, that is, get the second target character, and then the second character left, add the third character to the right, and obtain the third target character. The last right of the third character will obtain the fourth target character in the last right of the third character.

For example, we take a simple string "Test ..." to convert it with sourceByte = strconv (SourceText, vbfromunicode) to obtain binary arrays: t e s t ... 84 69 83 84 ... 01010100 01000101 01010011 01010100. after ..01010100 / 01000101/01010011/0101010001010100010001010101001101010100 conversion: 01010100010001010101001101010100010101/000100/010101/010011/010101/00010101 000100 010101 010011 010101 00 .... 21 4 21 19 21 ... V E V T V ... finally got It is "vevtv ..." for the first target character, we can do this: (SourceByte (1) and 252) / 4 Second: (Sourcebyte (1) and 3) * 64 (Sourcebyte (2) and 240) / 16 Third: (SourceByte (2) and 15) * 16 (Sourcebyte (3) and 48) / 64 Fourth: (Sourcebyte (3) and 63)

The Base64 decoding process is just the opposite, I will not say more, and there are still many RFCs about MIME. If you need more information, please find yourself, I will pick it out from

转载请注明原文地址:https://www.9cbs.com/read-29889.html

New Post(0)