Home Backend Development PHP Tutorial Base64编码原理分析与PHP实现

Base64编码原理分析与PHP实现

Jun 20, 2016 pm 12:44 PM

Base64是一种基于64个可打印字符来表示二进制数据的表示方法。由于2的6次方等于64,所以每6个为一个单元,对应某个可打印字符。

三个bites有24个比特,对应于4个Base64单元,即3个字节需要用4个可打印字符来表示。它可用来作为电子邮件的传输编码。

在Base64中的可打印字符包括字母A-Z、a-z、数字0-9,这样共有62个字符,此外两个可打印符号在不同的系统中而不同。

如在mime(多用途邮件扩展)中,Base64的使用的64个可打印字符

A-Za-z:大小写字母各26个

0-9:加上10个数字

+:加号

/:斜杠

一共64个字符,等号“=”用来作为后缀用途

对应的转换关系为

0-63:A-Za-z0-9+/


转换的时候,将三个byte的数据,先后放入一个24bit的缓冲区中,先来的byte占高位。数据不足3byte的话,于缓冲器中剩下的bit用0补足。然后,每次取出6(因为26=64)个bit,按照其值选择ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/中的字符作为编码后的输出。不断进行,直到全部输入数据转换完成。

当原数据长度不是3的整数倍时, 如果最后剩下一个输入数据,在编码结果后加2个“=”;如果最后剩下两个输入数据,编码结果后加1个“=”;如果没有剩下任何数据,就什么都不要加,这样才可以保证数据还原的正确性。

实例分析:

编码:"Lailaiji"

通过查ASCII表找到对应关系

L:0x4c |  a:0x61  | i:0x69   |  l:0x6C    |  j:0x6A

因此转换成二进制为:0100 1100 , 0110 0001 , 0110 1001 , 0110 1100 ,  0110 0001 , 0110 1001 , 0110 1010 ,  0110 1001

第一步:先取三个字节的数据即:0100 1100 , 0110 0001 , 0110 1001,然后从这个三字节中取出6位即010011,在最高位补充两个位00使其成为1个byte,即0001 0011,剩余的18位也如此循环,最终这三个字节将扩展成为4个字节即:0001 0011, 0000 0110, 0000 0101, 0010 1001

第二步,从剩余的字节序列中再重复第一步,走到小于3个字节

第三步,这时剩余字节为:0110 1010,0110 1001不足3个字节,需要在从低位以0进行补充,即成0110 1010,0110 1001,0000 0000重复第一步,得到:0001 1010,0010 0110, 0010 0100, 0000 0000,

经过以后的运算后,我们将得到一组位序列:

0001 0011, 0000 0110, 0000 0101, 0010 1001

0001 1011,0000 0110, 0000 0101, 0010 1001

0001 1010,0010 0110, 0010 0100, 0000 0000 

转换成十进制为:19,6,5,41,27,6,5,41,26,38,36,0

对应的字符为:T,G,F,p,b,G,F,p,a,m,k,A

特别注重的是,最后一个字节0000 0000即0x00,通过查表为A,由于最后这8位是补充的,所以它应当被转换成=号,而不是A

因此:最终结果为:TGFpbGFpamk=

PHP实现:

<?php$input = '赖来基';$obj = new MyBase64();$output = $obj->encode($input);echo "Encode:",$output.PHP_EOL;$output = $obj->decode($output);echo "Decode:",$output.PHP_EOL;class MyBase64{	private $_table = array();	private $_revtable = array();	public function __construct(){		$this->_initTable();	}	public function decode($string)	{		$orign_len = strlen($string);		$j = 0;		$ret = null;		for($i=0; $i<$orign_len; $i+=4)		{			$chr1 = $this->getRevChr($string[$i]);			$chr2 = $this->getRevChr($string[$i+1]);			$chr3 = $this->getRevChr($string[$i+2]);			$chr4 = $this->getRevChr($string[$i+3]);			$_chr1 = $chr1<<2 | ($chr2&0x3F) >>4;			$_chr2 = ($chr2&0x0F)<<4 | ($chr3&0xFC) >>2;			$_chr3 = ($chr3&0x03)<<6 | $chr4;			$ret .= chr($_chr1);			$ret .= chr($_chr2);			$ret .= chr($_chr3);		}		$ret = rtrim($ret);		return $ret;	}	private function getRevChr($chr)	{		if(isset($this->_revtable[$chr]))		{			return $this->_revtable[$chr];		}else{			return 0;		}	}	public function _decode($string)	{		$orign_len = strlen($string);		$de = null;		$kv = array_flip($this->_table);		$b  = null;		for($i = 0 ;$i < $orign_len;$i++)		{			$chr = $string[$i];			if($chr != '='){				$c = $kv[$chr];			}else{				$c = chr(0);			}			printf("%x",$c);			$b[] = pack('C',$c);			echo PHP_EOL;		}		for($i = 0 ;$i < count($b);$i+=3){			$ch1 = ($b[$i]<<2) | ($b[$i+1]>>4);			$ch2 = ($b[$i+1]<<4) | ($b[$i+2]>>2);			$ch3 = ($b[$i+2]<<6) | ($b[$i+3]);			printf('%08b,%08b,%08b',$ch1,$ch2,$ch3);			echo PHP_EOL;			printf('%08b,%08b',($b[$i]<<2) , ($b[$i+1]>>4));			echo PHP_EOL;		}	}	public function encode($string)	{		$orign_len = strlen($string);		$len       = intval(ceil($orign_len/3)*3);		$bin       = pack('a'.$len,$string);		$gen       = null;		for($i=0; $i<$len; $i+=3)		{			$ch1 = ord($bin[$i]) >> 2;			$ch2 = ((ord($bin[$i]) & 0x03) << 4) | (ord($bin[$i+1]) >> 4);			$ch3 = ((ord($bin[$i+1]) & 0x0F) << 2) | ((ord($bin[$i+2]) & 0xC0) >> 6);			$ch4 = ord($bin[$i+2]) & 0x3F;			$gen.= $this->_table[$ch1];			$gen.= $this->_table[$ch2];			$gen.= $this->_table[$ch3];			$gen.= $this->_table[$ch4];		}		if($orign_len-$len){			$gen = substr($gen,0, -abs($orign_len-$len));			for($i=0;$i<$len-$orign_len;$i++)			{				$gen .= '=';			}					}		return $gen;	}	private function  _initTable()	{		$tbl = array();		for($i=ord('A');$i<=ord('Z');$i++)		{			$tbl[] = chr($i);		}		for($i=ord('a');$i<=ord('z');$i++)		{			$tbl[] = chr($i);		}		for($i=ord('0');$i<=ord('9');$i++)		{			$tbl[] = chr($i);		}		$tbl[]           = '+';		$tbl[]           = '/';		$reverse         = array_flip($tbl);		$this->_table    = $tbl;		$this->_revtable = $reverse;	}}
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1264
29
C# Tutorial
1237
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

See all articles