Table of Contents
JS到PHP使用RSA算法进行加密通讯
Home php教程 php手册 Javascript到PHP加密通讯的简单实现

Javascript到PHP加密通讯的简单实现

Jun 06, 2016 pm 07:54 PM
javascript php interconnected encryption accomplish Simple communication

互联网上大多数网站,用户的数据都是以明文形式直接提交到后端 CGI ,服务器之间的访问也大都是明文传输,这样可被一些别有用心之人通过一些手段监听到。对安全性要求较高的网站,比如银行和大型企业等都会使用 HTTPS 对通讯过程进行加密等处理。 但是使用 H

互联网上大多数网站,用户的数据都是以明文形式直接提交到后端CGI,服务器之间的访问也大都是明文传输,这样可被一些别有用心之人通过一些手段监听到。对安全性要求较高的网站,比如银行和大型企业等都会使用HTTPS对通讯过程进行加密等处理。

但是使用HTTPS的代价是及其昂贵的。不只是CA证书的购买,更重要的是严重的性能瓶颈,解决方法目前只能采用专门的SSL硬件加速设备如F5BIGIP等。因此一些网站选择了简单模拟SSL的做法,使用RSAAES来对传输数据进行加密。原理如下图所示:

Javascript到PHP加密通讯的简单实现

这样就在一定程度上提高了数据传输的安全性。但是对于大多数网站来说,大部分数据往往没必要搞这么严密,可以选择性地只针对某些重要的小数据进行加密,例如密码。对于小数据量加密来说,可以没必要使用整个流程,只使用RSA即可,这样将大大简化流程。

为什么是小数据量?因为相对于对称加密来说,非对称加密算法随着数据量的增加,加密过程将变的巨慢无比。所以实际数据加密一般都会选用对称加密算法。因此PHP中的openssl扩展公私钥加密函数也只支持小数据(加密时117字节,解密时128字节)。

网上已有一些AESRSA的开源Javascript算法库,在PHP中更可直接通过相关扩展来实现(AES算法可以通过mcrypt的相关函数来实现,RSA则可通过openssl的相关函数实现),而不用像网上说的用纯PHP代码实现算法。由于篇幅所限,本文只介绍JavascriptPHPRSA加密通讯实现,拿密码加密为例。

先上代码:

 

前端加密

首先加载三个RSAjs库文件,可到这里下载 http://www.ohdave.com/rsa/

view plaincopy to clipboardprint?

  1. $(document).ready(function(){    
  2. //十六进制公钥    
  3. var rsa_n = "C34E069415AC02FC4EA5F45779B7568506713E9210789D527BB89EE462662A1D0E94285E1A764F111D553ADD7C65673161E69298A8BE2212DF8016787E2F4859CD599516880D79EE5130FC5F8B7F69476938557CD3B8A79A612F1DDACCADAA5B6953ECC4716091E7C5E9F045B28004D33548EC89ED5C6B2C64D6C3697C5B9DD3";   
  4.       
  5. $("#submit").click(function(){    
  6.     setMaxDigits(131); //131 => n的十六进制位数/2+3    
  7.     var key = new RSAKeyPair("10001"'', rsa_n); //10001 => e的十六进制    
  8.     var password = $("#password").val();    
  9.     password = encryptedString(key, password);//美中不足,不支持汉字~    
  10.     $("#password").val(password);    
  11.     $("#login").submit();    
  12. });    
  13. });   
 

PHP加密函数

view plaincopy to clipboardprint?

  1. /**  
  2.  * 公钥加密  
  3.  *  
  4.  * @param string 明文  
  5.  * @param string 证书文件(.crt)  
  6.  * @return string 密文(base64编码)  
  7.  */    
  8. function publickey_encodeing($sourcestr$fileName)    
  9. {    
  10.     $key_content = file_get_contents($fileName);    
  11.     $pubkeyid    = openssl_get_publickey($key_content);    
  12.     if (openssl_public_encrypt($sourcestr$crypttext$pubkeyid))    
  13.     {    
  14.         return base64_encode("" . $crypttext);    
  15.     }  
  16.     return False;  
  17. }   
 

PHP解密函数

view plaincopy to clipboardprint?

  1. /**  
  2.  * 私钥解密  
  3.  *  
  4.  * @param string 密文(base64编码)  
  5.  * @param string 密钥文件(.pem)  
  6.  * @param string 密文是否来源于JS的RSA加密  
  7.  * @return string 明文  
  8.  */    
  9. function privatekey_decodeing($crypttext$fileName,$fromjs = FALSE)  
  10. {    
  11.     $key_content = file_get_contents($fileName);    
  12.     $prikeyid    = openssl_get_privatekey($key_content);    
  13.     $crypttext   = base64_decode($crypttext);    
  14.     $padding = $fromjs ? OPENSSL_NO_PADDING : OPENSSL_PKCS1_PADDING;  
  15.     if (openssl_private_decrypt($crypttext$sourcestr$prikeyid$padding))    
  16.     {    
  17.         return $fromjs ? rtrim(strrev($sourcestr), "\0") : "".$sourcestr;    
  18.     }    
  19.     return FALSE;    
  20. }    
 

测试代码

view plaincopy to clipboardprint?

  1. define("CRT""ssl/server.crt"); //公钥文件  
  2. define("PEM""ssl/server.pem"); //私钥文件  
  3. //JS->PHP 测试   
  4. $data = $_POST['password'];    
  5. $txt_en = base64_encode(pack("H*"$data)); //转成base64格式   
  6. $txt_de = privatekey_decodeing($txt_en, PEM, TRUE);    
  7. var_dump($txt_de);    
  8. //PHP->PHP 测试    
  9. $data = "测试TEST"//PHP端支持汉字:D  
  10. $txt_en = publickey_encodeing($data, CRT);    
  11. $txt_de = privatekey_decodeing($txt_en, PEM);    
  12. var_dump($txt_de);  
 

代码贴完,有几处需要说明一下。其中十六进制公钥的获取是关键。由于密钥从x.509证书中获取,所以要先生成密钥及证书文件(本文中用的1024位密钥),具体生成方法请自行Google :P。这里重点说一下怎么从中获取十六进制的密钥。

从文件中读取十六进制密钥,本人之前尝试了很多方式,网上说数据是用ASN.1编码过的……最后无意中注意到linux shellopenssl貌似可以从私钥文件(keypem)提取。

openssl asn1parse -out temp.ans -i -inform PEM

显示结果如下:


Javascript到PHP加密通讯的简单实现

从这里终于可以看到Javascript中所需要的十六进制公钥密钥:D


参考:

JS到PHP使用RSA算法进行加密通讯


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
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

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.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

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

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.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

See all articles