Asymmetric encryption algorithm in PHP

PHP uses asymmetric encryption algorithm (RSA)

In the daily design and development, in order to ensure the security of data transmission and data storage, the clear data can be encrypted into complex ciphertext by specific algorithm. At present, the mainstream encryption methods can be roughly divided into one-way encryption and two-way encryption.

One way encryption: the ciphertext is generated by the summary calculation of the data, and the ciphertext is not reversible. Algorithm representative: Base64, MD5, SHA; 

Bidirectional encryption: in contrast to unidirectional encryption, ciphertext can be conversed to plaintext. Bidirectional encryption can be divided into symmetric encryption and asymmetric encryption.

Symmetric encryption: it means that data users must have the same key to encrypt and decrypt, just like a series of secret codes agreed by each other. Algorithm representatives: DES, 3DES, AES, IDEA, RC4, RC5;

Asymmetric encryption: compared with symmetric encryption, there is no need to have the same set of keys. Asymmetric encryption is a "key exchange protocol for information disclosure". Asymmetric encryption requires public key and private key. Public key and private key are matched,
In other words, public key is used for data encryption, and only the corresponding private key can be decrypted. These two keys are mathematically related. A ciphertext encrypted with a user's key can only be decrypted with that user's encryption key. If you know one of them, and
You can't work out another one. Therefore, if one of a pair of keys is disclosed, it will not harm the other key property. Here, the public key is the public key and the secret key is the private key. Algorithm representative: RSA, DSA.

Before, I had been confused about the encryption of the information from the client to the server. If the login information of the user in the app is captured, it's not very embarrassing if it's capitalized with username:root, password:123456.

When I accidentally entered copyright, I met rsa and contacted Alipay when I paid. I didn't know what it was until I knew it now.

He can guarantee that the information given by the client can only be viewed by the server with the private key, and that what others see is garbled code, hehe.

Asymmetric encryption algorithm
Two keys are required: public key and private key.
Public key and private key are a pair. If public key is used to encrypt data, only the corresponding private key can decrypt it;
If the private key is used to encrypt the data, only the corresponding public key can be used to decrypt.
Because encryption and decryption use two different keys, this algorithm is called asymmetric encryption algorithm.

Note the above point: only the corresponding private key can decrypt the data encrypted by the public key

It is purple in daily use:
The private key private key.pem is used on the server side, and the public key is distributed to android, ios and other front ends

After the client encrypts with the public key, the data can only be understood by the server with the unique private key.

Specific implementation:

1. The first step of encryption and decryption is to generate public key and private key pairs. The contents encrypted by private key can be decrypted by public key (and vice versa)

 1 download the open source RSA key generation tool openssl (usually the Linux system comes with the program), extract it to a separate folder, enter the bin directory, and execute the following command:
 2 a,openssl genrsa -out rsa_private_key.pem 1024
 3 b,openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out private_key.pem
 4 c,openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
 5 
 6 the first command generates the original RSA private key file RSA private key.pem
 The second command converts the original RSA private key to pkcs8 format
 Article 3 generate RSA public key RSA public key.pem
 9 
As can be seen from the above: the corresponding public key can be generated through the private key
Some websites also provide services for generating RSA public key and private key: http://www.bm8.com.cn/webtool/rsa/
2. PHP encryption and decryption class library:
<?php


class Rsa {
 
    /**     
     * Get private key     
     * @return bool|resource     
     */    
    private static function getPrivateKey() 
    {        
        $abs_path = dirname(__FILE__) . '/rsa_private_key.pem';
        $content = file_get_contents($abs_path);    
        return openssl_pkey_get_private($content);    
    }    

    /**     
     * Get public key     
     * @return bool|resource     
     */    
    private static function getPublicKey()
    {   
        $abs_path = dirname(__FILE__) . '/rsa_public_key.pem';
        $content = file_get_contents($abs_path);    
        return openssl_pkey_get_public($content);     
    }

    /**     
     * Private key encryption     
     * @param string $data     
     * @return null|string     
     */    
    public static function privEncrypt($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 privDecrypt($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;    
    }

}
<?php

require_once "Rsa.php";
$rsa = new Rsa();
$data['name'] = 'Tom';
$data['age']  = '20';
$privEncrypt = $rsa->privEncrypt(json_encode($data));
echo 'After private key encryption:'.$privEncrypt.'<br>';

$publicDecrypt = $rsa->publicDecrypt($privEncrypt);
echo 'After public key decryption:'.$publicDecrypt.'<br>';

$publicEncrypt = $rsa->publicEncrypt(json_encode($data));
echo 'After public key encryption:'.$publicEncrypt.'<br>';

$privDecrypt = $rsa->privDecrypt($publicEncrypt);
echo 'After decryption of private key:'.$privDecrypt.'<br>';

 

Keywords: Programming PHP OpenSSL Android iOS

Added by czukoman20 on Tue, 21 Apr 2020 06:17:09 +0300