PHP uses asymmetric encryption algorithm (RSA)

Posted by nwoottonn on Tue, 11 Jan 2022 12:42:48 +0100

Type of encryption:

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

Unidirectional encryption: the ciphertext is generated by summarizing the data, and the ciphertext is irreversibly pushed and restored. Algorithm representatives: Base64, MD5, SHA;

Bidirectional encryption: Contrary to unidirectional encryption, ciphertext can be inversely reduced to plaintext. Bidirectional encryption is 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 codes agreed by each other. Algorithm representatives: DES, 3DES, AES, IDEA, RC4, RC5;

Asymmetric encryption: compared with symmetric encryption, asymmetric encryption does not need to have the same set of keys. Asymmetric encryption is a "key exchange protocol for information disclosure". Asymmetric encryption requires two sets of keys, public key and private key. The public key and private key are paired, that is, only the corresponding private key can be decrypted when the public key is used for data encryption. The two keys are mathematically related. The ciphertext encrypted with a user's key can only be decrypted with the user's encryption key. If you know one of them, you can't calculate the other. Therefore, if one of a pair of keys is disclosed, the nature of the other key will not be compromised. Here, the public key is the public key and the non-public key is the private key. Algorithm representatives: RSA, DSA.

In the past, I was confused about encrypting the information transmitted from the client to the server. If the user login information in the app was captured and obtained, in words of username:root and password:123456, it would not be very embarrassing.

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 seen by the server with the private key, and what others see is garbled code, hehe.

Asymmetric encryption algorithm

Two keys are required: a public key and a private key.
The public key and the private key are a pair. If the data is encrypted with the public key, only the corresponding private key can be decrypted;
If the data is encrypted with a private key, it can only be decrypted with the corresponding public key.
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 soy purple in daily use:
Private key_ key. PEM is used on the server side, and the public key is issued to front ends such as android and ios
After the client is encrypted 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 a public key and private key pair. The encrypted content of the private key can be decrypted through the public key (or vice versa)

Copy code
1 download the open source RSA key generation tool openssl (usually the program comes with Linux system), unzip it to a separate folder, enter the bin directory, and execute the following command:

  a,openssl genrsa -out rsa_private_key.pem 1024
  b,openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out private_key.pem
  c,openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

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

From the above, we can see that the corresponding public key can be generated through the private key
Copy code
Some websites also provide services to generate rsa public and private keys: 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;    
    }

}

Call demo:

<?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>';

Topics: PHP security https