


Base64 algorithm principle, as well as encoding, decoding [encryption, decryption] introduction_PHP tutorial
Base64 encoding is an encoding method often used in our program development. It is a representation method based on using 64 printable characters to represent binary data. It is usually used as a encoding method for storing and transmitting some binary data! It is also a common encoding method for binary data represented by printable characters in MIME (Multipurpose Internet Mail Extensions, mainly used as an email standard)! It actually just defines a method of transmitting content using printable characters, and does not create a new character set! Sometimes, after we learn the idea of conversion, we can actually construct some of our own interface definition coding methods based on our own actual needs. Okay, let’s take a look at its conversion ideas!
Base64 implementation conversion principle
It is a method that uses 64 printable characters to represent all binary data. Since 2 to the 6th power is equal to 64, every 6 bits can be used as a unit, corresponding to a certain printable character. We know that three bytes have 24 bits, which can correspond to 4 Base64 units, that is, 3 bytes need to be represented by 4 Base64 printable characters. Printable characters in Base64 include letters A-Z, a-z, and numbers 0-9, so there are 62 characters in total. In addition, the two printable symbols are generally different in different systems. However, the other two characters of Base64 that we often refer to are: "+/". The corresponding table of these 64 characters is as follows.
编号 字符 编号 字符 编号 字符 编号 字符 0 A 16 Q 32 g 48 w 1 B 17 R 33 h 49 x 2 C 18 S 34 i 50 y 3 D 19 T 35 j 51 z 4 E 20 U 36 k 52 0 5 F 21 V 37 l 53 1 6 G 22 W 38 m 54 2 7 H 23 X 39 n 55 3 8 I 24 Y 40 o 56 4 9 J 25 Z 41 p 57 5 10 K 26 a 42 q 58 6 11 L 27 b 43 r 59 7 12 M 28 c 44 s 60 8 13 N 29 d 45 t 61 9 14 O 30 e 46 u 62 + 15 P 31 f 47 v 63 /
During conversion, three bytes of data are put into a 24-bit buffer one after another, and the byte that comes first occupies the high bit. If the data is less than 3 bytes, the remaining bits in the buffer will be filled with 0s. Then, 6 bits are taken out each time, and the characters in <br>ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
are selected according to their values as the encoded output. Continue until all input data is converted.
If there are two input data left at the end, add 1 "=" after the encoding result; if there is one input data left at the end, add 2 "=" after the encoding result; if there is no data left, just what Do not add them, so as to ensure the accuracy of data restoration.
The encoded data is slightly longer than the original data, 4/3 of the original. No matter what kind of characters, all characters will be encoded, so unlike Quoted-printable encoding, some printable characters are retained. Therefore, it is not as readable as Quoted-printable encoding!
文本 | M | a | n | |||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ASCII编码 | 77 | 97 | 110 | |||||||||||||||||||||
二进制位 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 |
索引 | 19 | 22 | 5 | 46 | ||||||||||||||||||||
Base64编码 | T | W | F | u |
The Ascii code of M is 77, the first six digits correspond to 19, the corresponding base64 character is T, and so on. Other character encodings can be automatically converted! Let's look at the other situation where it's not exactly 3 bytes!
文本(1 Byte) | A | |||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
二进制位 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | ||||||||||||||||
二进制位(补0) | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | ||||||||||||
Base64编码 | Q | Q | = | = | ||||||||||||||||||||
文本(2 Byte) | B | C | ||||||||||||||||||||||
二进制位 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 1 | x | x | x | x | x | x | ||
二进制位(补0) | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | x | x | x | x | x | x |
Base64编码 | Q | k | M | = |
Base64 conversion code implementation
Now that we know the method, it seems to be very easy if we want to write a simple conversion ourselves! Below, I wrote down the php code I do the conversion!
<span><?php </span></span>
/**
*base64编码方法、本方法只是做base64转换过程代码举例说明,通过该例子可以任意改造不同语言版
*@author 程默
*@copyright http://blog.chacuo.net
*@param $src 原字符串
*@return string base64字符串*
*/
function
c_base64_encode(
$src
)
{
static
$base
=
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
;
////将原始的3个字节转换为4个字节
$slen
=
strlen
(
$src
);
$smod
= (
$slen
%3);
<code>$snum
=
floor
(
$slen
/3);
$desc
=
array
();
for
(
$i
=0;
$i
<code>$snum
;
$i
++)
{
////读取3个字节
$_arr
=
array_map
(
'ord'
,
str_split
(
substr
(
$src
,
$i
*3,3)));
///计算每一个base64值
$_dec0
=
$_arr
[0]>>2;
$_dec1
= ((
$_arr
[0]&3)<code>$_arr
[1]>>4);
$_dec2
= ((
$_arr
[1]&0xF)<code>$_arr
[2]>>6);
$_dec3
=
$_arr
[2]&63;
$desc
=
array_merge
(
$desc
,
array
(
$base
[
$_dec0
],
$base
[
$_dec1
],
$base
[
$_dec2
],
$base
[
$_dec3
]));
}
if
(
$smod
==0)
return
implode(
''
,
$desc
);
///计算非3倍数字节
$_arr
=
array_map
(
'ord'
,
str_split
(
substr
(
$src
,
<code>$snum*3,3)));
$_dec0
=
$_arr
[0]>>2;
///只有一个字节
if
(!isset(
$_arr
[1]))
{
$_dec1
= ((
$_arr
[0]&3)
$_dec2
=
$_dec3
=
"="
;
}
else
{
///2个字节
$_dec1
= ((
$_arr
[0]&3)<code>$_arr
[1]>>4);
$_dec2
=
$base
[(
$_arr
[1]&7)
$_dec3
=
"="
;
}
$desc
=
array_merge
(
$desc
,
array
(
$base
[
$_dec0
],
$base
[
$_dec1
],
$_dec2
,
$_dec3
));
return
implode(
''
,
$desc
);
}
<img src="/static/imghw/default1.png" data-src="http://www.bkjia.com/uploads/allimg/140519/121254K20-0.png" class="lazy" title="Base64 algorithm principle, as well as encoding, decoding [encryption, decryption] introduction_PHP tutorial" alt="Base64 algorithm principle, as well as encoding, decoding [encryption, decryption] introduction_PHP tutorial" style="max-width:90%" style="max-width:90%" border="0" />Copy after login
Okay, through this example, I think I have some understanding of the base64 encoding conversion principle and algorithm! The conversion process is very simple. You only need to make a mapping table and then do some shift operations on the original one! Through this example, can we make our own base32 encoding? Welcome friends to communicate!
Author: Cheng Mo’s blog QQ:8292669
Original URL: http://blog.chacuo.net/719.html
Subscribe and stay tuned: http://blog.chacuo.net/feed
The copyright of this article belongs to the author. You are welcome to reprint it. Please be sure to add a link to the original text.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
