In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article shows you how to achieve interface signature verification in PHP, the content is concise and easy to understand, it will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
Sample code:
/ / create signature private function _ createSign () {$strSalt = '1scv6zfzSR1wLaWN; $strVal =''; if ($this- > params) {$params = $this- > params; ksort ($params); $strVal = http_build_query ($params,'','&', PHP_QUERY_RFC3986);} return md5 (md5 ($strSalt). Md5 ($strVal)) } / / verify the signature if ($_ GET ['sign']! = $this- > _ createSign ()) {echo' Invalid Sign.';}
The MD5 method is used above, and MD5 belongs to one-way hash encryption.
One-way hash encryption definition
Changing an arbitrarily long input string into a fixed-length output string, and it is difficult to get the input string from the output string, this method is called single hash encryption.
Common algorithm
MD5
SHA
MAC
CRC
Advantages
Take MD5 as an example.
Convenient storage: encrypted are fixed-size (32-bit) strings, which can allocate fixed-size space storage.
Low loss: the performance loss of encryption / encryption is minimal.
File encryption: only a 32-bit string is needed to verify the integrity of a large file.
Irreversible: irreversible in most cases, with good security.
Shortcoming
There is the possibility of violent cracking, it is best to improve the security by adding salt value.
Application scenario
Used for sensitive data, such as user passwords, request parameters, file encryption, etc.
Recommend how to store passwords
Password_hash () uses an one-way hash algorithm with sufficient strength to create a hash of the password.
Sample code:
/ / password encryption $password = '123456password candidate strPwdHash = password_hash ($password, PASSWORD_DEFAULT); / / password authentication if (password_verify ($password, $strPwdHash)) {/ / Success} else {/ / Fail}
Address of the PHP manual:
Http://php.net/manual/zh/function.password-hash.php
Symmetric encryption definition
The same key can be used for both encryption and decryption of data, which is called symmetric encryption.
Common algorithm
DES
AES
AES is an upgraded version of DES with longer key length, more choices, more flexibility, higher security, and faster speed.
Advantages
The algorithm is open, the amount of computation is small, the encryption speed is fast and the encryption efficiency is high.
Shortcoming
The sender and receiver must agree on the key so that both parties can keep the key, and key management becomes a burden on both sides.
Application scenario
Encryption of a relatively large amount of data or critical data.
AES
The AES encrypted class library is easy to find on the Internet, please pay attention to the mcrypt_encrypt and mcrypt_decrypt methods in the class library!
It has been deprecated in the PHP7.2 version, using both openssl_encrypt and openssl_decrypt methods in the new version.
Sample code (class library):
Class Aes {/ * var string $method encryption and decryption method * / protected $method; / * var string $secret_key encryption key * / protected $secret_key; / * * var string $iv encryption and decryption vector * / protected $iv; / * var int $options * / protected $options / * Constructor * @ param string $key key * @ param string $method encryption method * @ param string $iv Vector * @ param int $options * / public function _ _ construct ($key ='', $method = 'AES-128-CBC', $iv ='', $options = OPENSSL_RAW_DATA) {$this- > secret_key = isset ($key)? $key: 'CWq3g0hgl7Ao2OKI' $this- > method = in_array ($method, openssl_get_cipher_methods ())? $method: 'AES-128-CBC'; $this- > iv = $iv; $this- > options = in_array ($options, [OPENSSL_RAW_DATA, OPENSSL_ZERO_PADDING])? $options: OPENSSL_RAW_DATA } / * encrypted * @ param string $data encrypted data * @ return string * / public function encrypt ($data =') {return base64_encode (openssl_encrypt ($data, $this- > method, $this- > secret_key, $this- > options, $this- > iv)) } / * * decrypt * @ param string $data decrypted data * @ return string * / public function decrypt ($data =') {return openssl_decrypt (base64_decode ($data), $this- > method, $this- > secret_key, $this- > options, $this- > iv);}}
Sample code:
$aes = new Aes ('HFu8Z5SjAT7CudQc'); $encrypted = $aes- > encrypt (' Peasants' hard hoeing at noon'); before echo 'encryption: farmers' hard hoeing at noon
After encryption:', $encrypted,'; $decrypted = $aes- > decrypt ($encrypted); echo 'after encryption:', $encrypted,'
After decryption:', $decrypted
Running result:
Asymmetric encryption definition
Two keys are required for encryption and decryption, which are the public key (public key) and the private key (private key), which is called asymmetric encryption.
Common algorithm
RSA
Advantages
Compared with symmetric encryption, security is better, encryption and decryption requires different keys, public keys and private keys can encrypt and decrypt each other.
Shortcoming
Encryption and decryption takes a long time and is slow, so it is only suitable for encrypting a small amount of data.
Application scenario
It is suitable for scenarios with high security requirements, and suitable for encrypting a small amount of data, such as payment data, login data and so on.
RSA and RSA2
RSA2 has stronger security capabilities than RSA.
Ant Financial Services Group and Sina Weibo are all using RSA2 algorithm.
Create public and private keys:
Openssl genrsa-out private_key.pem 2048openssl rsa-in private_key.pem-pubout-out public_key.pem
Execute the above command and two files, private_key.pem and public_key.pem, are generated.
Sample code (class library):
Class Rsa2 {private static $PRIVATE_KEY = 'private_key.pem content'; private static $PUBLIC_KEY = 'public_key.pem content'; / * * obtain private key * @ return bool | resource * / private static function getPrivateKey () {$privateKey = self::$PRIVATE_KEY; return openssl_pkey_get_private ($privateKey) } / * get the public key * @ return bool | resource * / private static function getPublicKey () {$publicKey = self::$PUBLIC_KEY; return openssl_pkey_get_public ($publicKey) } / * Private key encryption * @ param string $data * @ return null | string * / public static function privateEncrypt ($data =') {if (! is_string ($data)) {return null;} return openssl_private_encrypt ($data,$encrypted,self::getPrivateKey ())? Base64_encode ($encrypted): null;} / * * Public key encryption * @ param string $data * @ return null | string * / public static function publicEncrypt ($data =') {if (! is_string ($data)) {return null;} return openssl_public_encrypt ($data,$encrypted,self::getPublicKey ())? Base64_encode ($encrypted): null;} / * * Private key decryption * @ param string $encrypted * @ return null * / public static function privateDecrypt ($encrypted =') {if (! is_string ($encrypted)) {return null;} return (openssl_private_decrypt (base64_decode ($encrypted), $decrypted, self::getPrivateKey ())? $decrypted: null } / * Public key decryption * @ param string $encrypted * @ return null * / public static function publicDecrypt ($encrypted =') {if (! is_string ($encrypted)) {return null;} return (openssl_public_decrypt (base64_decode ($encrypted), $decrypted, self::getPublicKey ())? $decrypted: null } / * create signature * @ param string $data data * @ return null | string * / public function createSign ($data =') {if (! is_string ($data)) {return null;} return openssl_sign ($data, $sign, self::getPrivateKey (), OPENSSL_ALGO_SHA256)? Base64_encode ($sign): null;} / * verify signature * @ param string $data data * @ param string $sign signature * @ return bool * / public function verifySign ($data ='', $sign ='') {if (! is_string ($sign) | |! is_string ($sign)) {return false } return (bool) openssl_verify ($data, base64_decode ($sign), self::getPublicKey (), OPENSSL_ALGO_SHA256);}}
Sample code:
$rsa2 = new Rsa2 (); $privateEncrypt = $rsa2- > privateEncrypt ('Farmers' hard hoeing at noon'); echo 'private key encryption:'. $privateEncrypt.'
'; $publicDecrypt = $rsa2- > publicDecrypt ($privateEncrypt); echo' public key decryption:'. $publicDecrypt.'
'; $publicEncrypt = $rsa2- > publicEncrypt (' Farmers' hard hoe at noon'); echo 'public key encryption:'. $publicEncrypt.'
'; $privateDecrypt = $rsa2- > privateDecrypt ($publicEncrypt); echo' private key decrypted:'. $privateDecrypt.'
'; $sign = $rsa2- > createSign (' farmers work hard to hoe at noon'); echo 'generate signature:'. $privateEncrypt.'
'; $status = $rsa2- > verifySign (' Farmers work hard to hoe at noon', $sign); echo 'verify signature:'. ($status? 'success': 'failure')
Running result:
Some of the data screenshots are as follows:
JS-RSA
JSEncrypt: the Javascript library used to perform OpenSSL RSA encryption, decryption, and key generation.
Git source: https://github.com/travist/jsencrypt
Application scenarios:
When we do the login function of WEB, we usually submit it to the server through Form or Ajax for verification.
To prevent packet grabbing, the login password must be encrypted (RSA) before being submitted to the server for verification.
Some big companies are using it, such as Taobao, JD.com, Sina and so on.
The sample code is not provided, and the code provided on Git is very complete.
Key security management
The premise that these encryption technologies can achieve the effect of secure encryption is the confidentiality of the key.
In practice, the keys of different environments should be different (development environment, pre-release environment, formal environment).
So, how do you keep the key securely?
Environment variable
Set the key to the environment variable and load it each time from the environment variable.
Configuration center
The key is stored in the configuration center and managed uniformly.
Key expiration policy
Set the validity period of the key, such as reset once a month.
I hope the boss will provide new ideas here.
Interface debugging tool Postman
A powerful Chrome plug-in for debugging and sending HTTP requests to web pages.
There is no need to introduce this. Everyone must have used it.
SocketLog
Git source: https://github.com/luofei614/SocketLog
Pain points to be resolved:
The API that is running has Bug and cannot be debugged with var_dump in the file because it affects the call to client. It is not very convenient to write the log to a file and view it.
When we re-develop a new system, we want to see which Sql statements have been executed and error messages such as the warning,notice of the program.
SocketLog, which can solve the above problem, outputs the debug log to the browser's console through WebSocket.
Usage
Install and configure the Chrome plug-in
SocketLog server installation
Debugging with SocketLog in PHP
Configure log types and related parameters
Online interface documentation
After the development of the interface, it is necessary to provide interface documents to the requestor, and most of the documents are written in Markdown format.
There are also some open source systems that can be downloaded and installed on your own servers.
There are also some online systems that can be used online and support offline export.
According to your own situation, choose the documentation platform that suits you.
Common interface documentation platforms:
Eolinker
Apizza
Yapi
RAP2
DOClever
Expansion
First, in the choice of HTTP and RPC, there may be some questions, RPC framework configuration is more complex, clearly using HTTP can achieve why choose RPC?
The following is a brief introduction to the difference between HTTP and RPC.
Transport protocol:
HTTP is based on the HTTP protocol.
RPC can be either HTTP or TCP.
HTTP is also a way to implement RPC.
Performance consumption:
HTTP is mostly implemented on JSON, and serialization takes time and performance.
RPC can be transmitted based on binary, consuming less performance.
Recommend a new serialization class library like JSON, but with faster and less footprint than JSON transfer.
Official website address: https://msgpack.org/
There are also some differences in service governance and load balancing configuration.
Use the scene:
For example, browser interface, APP interface and third-party interface, HTTP is recommended.
For example, RPC is recommended for intra-group service calls.
Compared with HTTP, RPC has lower performance consumption, higher transmission efficiency and convenient service governance.
The recommended RPC framework: Thrift.
Second, dynamic token
Briefly introduce several dynamic tokens, and those who are interested can learn more about them.
OTP:One-Time Password one-time password.
An one-time password encrypted by HOTP:HMAC-based One-Time Password based on the HMAC algorithm.
TOTP:Time-based One-Time Password one-time password based on the timestamp algorithm.
The above is how to implement interface signature verification in PHP. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 252
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.