Home > Backend Development > PHP Tutorial > How to encrypt and decrypt in PHP? PHP encryption and decryption methods

How to encrypt and decrypt in PHP? PHP encryption and decryption methods

青灯夜游
Release: 2023-04-04 12:56:01
forward
8511 people have browsed it

The content of this article is to introduce how to encrypt and decrypt PHP? PHP encryption and decryption methods. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In order to ensure the security of network transmission data, involving the transmission of sensitive data, it is best to pre-encrypt the data before transmitting it on the network. At the same time, ensure that the data is accessible at the other end. Decrypted, and it must be decrypted through a key (public key or private key). People without a key (public key or private key) cannot decrypt even if they get the encrypted data.

This article mainly introduces the AES encryption algorithm in symmetric encryption; the RSA encryption algorithm in asymmetric encryption. [Related video tutorial recommendations: PHP Tutorial]

1. Symmetric encryption

Encryption using a single-key cryptography system Method, the same key can be used for both encryption and decryption of information. This encryption method is called symmetric encryption, also known as single-key encryption.

Commonly used algorithms in symmetric encryption algorithms include: DES, 3DES, TDEA, Blowfish, RC2, RC4, RC5, IDEA, SKIPJACK, AES, etc.

AES encryption algorithm

Advanced Encryption Standard (AES) in cryptography, also known as Rijndael encryption method, is an American A block encryption standard adopted by the federal government. This standard is used to replace the original DES. It has been analyzed by many parties and is widely used around the world. In 2006, Advanced Encryption Standard has become one of the most popular algorithms for symmetric key encryption.

PHP's OpenSSL extension has implemented the AES encryption algorithm. We can encrypt and decrypt data through the methods provided by the OpenSSL extension. PHP has completely removed MCrypt encryption in version 7.2. The PHP manual has been migrated in 7.1 The page gives an alternative, which is to use OpenSSL to replace MCrypt.

PHP AES implementation (encryption, decryption)

PHP implementation code:

class AES
{
    //设置AES秘钥
    private static $aes_key = 'bUYJ3nTV6VBasdJF'; //此处填写前后端共同约定的秘钥

    /**
     * 加密
     * @param string $str    要加密的数据
     * @return bool|string   加密后的数据
     */
    static public function encrypt($str) {

        $data = openssl_encrypt($str, 'AES-128-ECB', self::$aes_key, OPENSSL_RAW_DATA);
        $data = base64_encode($data);

        return $data;
    }

    /**
     * 解密
     * @param string $str    要解密的数据
     * @return string        解密后的数据
     */
    static public function decrypt($str) {

        $decrypted = openssl_decrypt(base64_decode($str), 'AES-128-ECB', self::$aes_key, OPENSSL_RAW_DATA);
        return $decrypted;
    }
}
Copy after login

2. Asymmetric encryption

The symmetric encryption algorithm uses the same secret key for encryption and decryption; the asymmetric encryption algorithm requires two keys to For encryption and decryption, the two secret keys are the public key (public key for short) and the private key (private key for short).

The main algorithms used in asymmetric encryption are: RSA, Elgamal, backpack algorithm, Rabin, D-H, ECC (elliptic curve cryptography algorithm), etc.

RSA encryption algorithm

RSA is currently the most influential public key encryption algorithm. The algorithm is based on a very simple number theory fact: Multiplying two large primes is easy, but then factoring their product is extremely difficult, so the product can be exposed as an encryption key, the public key, and the two large primes combined to form the private key. The public key is releasable for anyone to use, and the private key is yours for decryption.

The decryptor owns the private key and releases the public key generated by the private key calculation to the encryptor. Encryption uses the public key to encrypt and send the ciphertext to the decryptor, who uses the private key to decrypt the ciphertext into plaintext.

Suppose A wants to send information to B, for example, first determine the roles: A is the encryptor, and B is the decryptor. First, B randomly determines a KEY, called a secret key, and keeps this KEY in machine B without sending it out; then, calculates another KEY from this KEY, called a public key. The property of this public key is that it is almost impossible to calculate on its own the private key that generated it. Next, the public key is transmitted to A through the network. After A receives the public key, he uses the public key to encrypt the information and sends the ciphertext to B through the network. Finally, B uses the known private key to encrypt the ciphertext. Decoded. The above is the workflow of the RSA algorithm.

The algorithm implementation process is:

  1. # Randomly select two large prime numbers p and q, p is not equal to q, and calculate N=pq.

  2. According to the Euler function, the number of integers not greater than N and relatively prime to N is (p-1)(q-1).

  3. Choose an integer e that is relatively prime with (p-1)(q-1), and e is less than (p-1)(q-1).

  4. Use the following formula to calculate d: d× e ≡ 1 (mod (p-1)(q-1)).

  5. Destroy the records of p and q.

In the above content, (N,e) is the public key and (N,d) is the private key.

Generate private key and public key

Generate private key file:

openssl genrsa -out rsa_private_key.pem 1024
Copy after login

Use the private key to generate public key:

openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
Copy after login

Data can be encrypted and decrypted through the generated public key and private key:

PHP RSA implementation (encryption, decryption)

PHP implementation code (public key encryption Private key decryption):

class RSA
{
    /**
     * @param string $str 要加密的数据
     * @param string $public_key 公钥
     * @return string
     */
    static public function encrypt($str, $public_key) {

        $encrypted = '';
        $pu_key = openssl_pkey_get_public($public_key);
        openssl_public_encrypt($str, $encrypted, $pu_key);//公钥加密

        $encrypted = base64_encode($encrypted);

        return $encrypted;
    }

    /**
     * 解密
     * @param string $str 要解密的数据
     * @param string $private_key 私钥
     * @return string
     */
    static public function decrypt($str, $private_key) {

        $decrypted = '';
        $pi_key =  openssl_pkey_get_private($private_key);
        openssl_private_decrypt(base64_decode($str), $decrypted, $pi_key);//私钥解密

        return $decrypted;
    }
}
Copy after login

PHP implementation code (private key encryption and public key decryption):

class RSA
{
    //私钥加密 
    static public function encrypt($str, private_key) {

        $encrypted = '';
        $pi_key = openssl_pkey_get_private($private_key);
        openssl_private_encrypt($data, $encrypted, $pi_key); //私钥加密
        
        $encrypted = base64_encode($encrypted);
        
        return $encrypted;
    }
    //公钥解密
    static public function decrypt($str, $public_key) {

        $decrypted = '';
        $pu_key = openssl_pkey_get_public($public_key);
        openssl_public_decrypt(base64_decode($str), $decrypted, $pu_key);//公钥解密
        
        return $decrypted;
    }
}
Copy after login

Summary: The above is the entire content of this article, I hope it can be useful for everyone’s learning help.

The above is the detailed content of How to encrypt and decrypt in PHP? PHP encryption and decryption methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template