search
HomeBackend DevelopmentPHP TutorialPHP encryption and decryption method based on openssl

PHP encryption and decryption method based on openssl

Jul 12, 2017 am 10:03 AM
opensslphpencrypt and decode

openssl Introduction to OpenSSL
SSL is the abbreviation of Secure Socket Layer (Secure Socket Layer Protocol), which can provide confidential transmission on the Internet. When Netscape launched the first Web browser, it also proposed the SSL protocol standard, which currently has version 3.0. SSL uses public key technology. Its goal is to ensure the confidentiality and reliability of communication between two applications, and can be supported on both the server side and the user side. Currently, the SSL protocol using public key technology has become the industry standard for secure communications on the Internet. The Secure Socket Layer protocol prevents communication between user/server applications from being eavesdropped by attackers and always authenticates the server and optionally the user. The SSL protocol requires a reliable Transport Layer Protocol (TCP). The advantage of the SSL protocol is that it is independent of application layer protocols. High-level application layer protocols (such as HTTP, FTP, TELNET, etc.) can be transparently built on the SSL protocol. The SSL protocol has completed the encryption algorithm, communication key negotiation and server authentication before application layer protocol communication. After this, the data transmitted by the application layer protocol will be encrypted to ensure the privacy of communication. Through the above description, the secure channel provided by the SSL protocol has the following three characteristics: 1. Data confidentiality Information encryption is to convert the plain input file into an encrypted file using an encryption algorithm to achieve data confidentiality. The encryption process requires the use of a key to encrypt data and then decrypt it. Without the key, the encrypted data cannot be decrypted. After the data is encrypted, only the key needs to be transmitted using a secure method. Encrypted data can be transmitted publicly. 2. Data consistency Encryption can also ensure data consistency. For example: Message Verification Code (MAC) can verify the encrypted information provided by the user. The recipient can use MAC to verify the encrypted data to ensure that the data has not been tampered with during transmission. 3. Security verification Another use of encryption is as a personal identification, and the user's key can be used as his security verification identification. SSL uses public key encryption technology (RSA) as an encrypted communication protocol between the client and server when transmitting confidential information.
What is OpenSSL
There are many cryptographic algorithms, public key infrastructure standards, and SSL protocols. Perhaps these interesting features will give you the idea of ​​​​implementing all these algorithms and standards. If so, while I admire you, I can’t help but remind you: this is a daunting process. This job is no longer as simple as reading a few cryptography monographs and protocol documents, but understanding every detail of all these algorithms, standards and protocol documents, and using the C language## that you may be familiar with. The # characters implement these definitions and procedures one by one. We don't know how much time you're going to need to do this fun and scary job, but it's certainly not a matter of a year or two. First of all, we should thank Eric A. Young and Tim J. Hudson, who started writing the OpenSSL software package that later had a huge impact in 1995. What makes us even more happy is that this is an open source code without too many restrictions. software package, which allows us to do many things with this software package. Eric A. Young and Tim J. Hudson are Canadians. They later became famous by writing OpenSSL and then went to big companies to make a lot of money. In 1998, the OpenSSL project team took over the development of OpenSSL and launched OpenSSL version 0.9.1. So far, the OpenSSL algorithm has been very complete and supports SSL2.0, SSL3.0 and TLS1.0.
OpenSSL uses C language as the development language, which makes OpenSSL have excellent cross-platform performance. This is a very wonderful thing for the majority of technical personnel, who can use the same familiar things on different platforms. OpenSSL supports Linux, Windows, BSD, Mac, VMS and other platforms, which makes OpenSSL widely applicable. However, for the newly grown C++ programmers, they may not be very accustomed to C language code, but getting used to C language is much easier than using C++ to rewrite a software package with the same functions as OpenSSL.
The entire OpenSSL software package can be roughly divided into three main functional parts: cryptographic algorithm library, SSL protocol library and applications. OpenSSL's
directory structure is naturally planned around these three functional parts. As a security development kit based on cryptography, OpenSSL provides quite powerful and comprehensive functions, including major cryptographic algorithms, commonly used key and certificate encapsulation management functions, and SSL protocols, and provides a wealth of application programs. Used for testing or other purposes.
1.Symmetric encryption algorithm
OpenSSL provides a total of 8 symmetric encryption algorithms, 7 of which are block cipher algorithms, and the only stream cipher algorithm is RC4. These seven block encryption algorithms are AES, DES, Blowfish, CAST, IDEA, RC2, and RC5. They all support electronic codebook mode (ECB), encrypted block chaining mode (CBC), encryption feedback mode (CFB), and output feedback mode. (OFB) Four commonly used block cipher encryption modes. Among them, the encryption feedback mode (CFB) and output feedback mode (OFB) packet length used by AES is 128 bits, while other algorithms use 64 bits. In fact, the DES algorithm is not only the commonly used DES algorithm, but also supports three-key and two-key 3DES algorithms.
2. Asymmetric encryption algorithm
OpenSSL implements a total of 4 asymmetric encryption algorithms, including DH algorithm, RSA algorithm, DSA algorithm and elliptic curve algorithm (EC). DH algorithm general user key exchange. The RSA algorithm can be used for both key exchange and digital signatures, and of course, if you can tolerate its slow speed, it can also be used for data encryption. The DSA algorithm is generally only used for digital signatures.
3. Information digest algorithm
OpenSSL implements 5 information digest algorithms, namely MD2, MD5, MDC2, SHA (SHA1) and RIPEMD. The SHA algorithm actually includes two information digest algorithms, SHA and SHA1. In addition, OpenSSL also implements the two information digest algorithms DSS and DSS1 specified in the DSS standard.
4. Key and certificate management
Key and certificate management is an important part of PKI. OpenSSL provides rich functions and supports multiple standards.
First of all, OpenSSL implements the ASN.1 certificate and key related standards, providing DER, PEM and BASE64 encoding and decoding functions for certificates, public keys, private keys, certificate requests, CRL and other data objects. OpenSSL provides methods, functions and applications for generating various public key pairs and symmetric keys, and also provides DER encoding and decoding functions for public keys and private keys. And implements the PKCS#12 and PKCS#8 encoding and decoding functions of the private key. OpenSSL provides encryption protection for private keys in the standard, so that keys can be stored and distributed securely.
On this basis, OpenSSL implements the X.509 standard encoding and decoding of certificates, the encoding and decoding of PKCS#12 format, and the encoding and decoding of PKCS#7. It also provides a text database that supports certificate management functions, including certificate key generation, request generation, certificate issuance, revocation, and verification.
In fact, the CA application provided by OpenSSL is a small certificate management center (CA), which implements the entire process of certificate issuance and most of the mechanisms of certificate management.
5.SSL and TLS protocols
OpenSSL implements SSLv2 and SSLv3 of the SSL protocol and supports most of the algorithm protocols. OpenSSL also implements TLSv1.0. TLS is a standardized version of SSLv3. Although the difference is not big, there are many details that are different.
Although there are many software that have implemented the functions of OpenSSL, the SSL protocol implemented in OpenSSL can give us a clearer understanding of the SSL protocol, because there are at least two points: First, the SSL protocol implemented by OpenSSL is open For the source code, we can trace every detail of the SSL protocol implementation; secondly, the SSL protocol implemented by OpenSSL is a pure SSL protocol and is not combined with other protocols (such as HTTP), which clarifies the true nature of the SSL protocol.
6. Application
OpenSSL application has become an important part of OpenSSL, and its importance may not have been thought of by the developers of OpenSSL at first. Many of the current OpenSSL applications are based on OpenSSL applications rather than its API. For example, OpenCA is completely implemented using OpenSSL applications. OpenSSL applications are written based on OpenSSL's cryptographic algorithm library and SSL protocol library, so there are also some very good OpenSSL API usage examples. After reading all these examples, you will have a more comprehensive understanding of OpenSSL API usage. Of course, This is also a job that exercises your willpower.
OpenSSL applications provide relatively comprehensive functions. In the eyes of many people, OpenSSL has done everything for itself and does not need to do more development work. Therefore, they also put these applications Become an OpenSSL directive. OpenSSL applications mainly include key generation, certificate management, format conversion, data encryption and signature, SSL testing and other auxiliary configuration functions.
7. Engine Mechanism The Engine mechanism appeared in OpenSSL version 0.9.6. At first, the normal version was separated from the version that supports Engine. By OpenSSL version 0.9.7, the Engine mechanism was integrated into the OpenSSL kernel. , has become an indispensable part of OpenSSL. The purpose of the Engine mechanism is to enable OpenSSL to transparently use software encryption libraries or hardware encryption devices provided by third parties for encryption. OpenSSL's Engine mechanism successfully achieves this goal, which makes OpenSSL not just an encryption library, but provides a universal encryption interface that can coordinate with most encryption libraries or encryption devices. Of course, to make a specific encryption library or encryption device work with OpenSSL, you need to write a small amount of interface code, but the workload is not large, although it still requires a little knowledge of cryptography. The functions of the Engine mechanism are basically the same as the CSP function goals provided by Windows. Currently, OpenSSL version 0.9.7 supports eight types of embedded third-party encryption devices, including: CryptoSwift, nCipher, Atalla, Nuron, UBSEC, Aep, SureWare, and IBM 4758 CCA hardware encryption devices. There is also an Engine interface that supports the PKCS#11 interface, and an interface that supports Microsoft CryptoAPI is also being developed. Of course, support for all the above Engine interfaces may not be comprehensive. For example, one or two public key algorithms may be supported.
8. Auxiliary functions
The BIO mechanism is a high-level IO interface provided by OpenSSL. This interface encapsulates almost all types of IO interfaces, such as memory access, file access, Socket, etc. This greatly improves the reusability of code and reduces the complexity of the API provided by OpenSSL.
OpenSSL also provides a complete set of solutions and supporting API functions for the generation and management of random numbers. The quality of random numbers is an important prerequisite for determining whether a key is secure.
OpenSSL also provides other auxiliary functions, such as the API for generating keys from passwords, the configuration file mechanism in certificate issuance and management, etc. If you are patient enough, you will slowly discover many such small functions during the in-depth use of OpenSSL, giving you constant new surprises.

This article mainly introduces the implementation of encryption and decryption methods based on openssl in php, and analyzes the relevant techniques of phpcustom functionsimplementation of encryption and decryption operations based on openssl in the form of examples. Friends who need it can Refer to the following

The example of this article describes the encryption and decryption method based on openssl in PHP. Share it with everyone for your reference, the details are as follows:

Encryption and decryption method through openssl

1. openssl encryption method:

function encrypt($id){
  $id=serialize($id);
  $key="1112121212121212121212";
  $data['iv']=base64_encode(substr('fdakinel;injajdji',0,16));
  $data['value']=openssl_encrypt($id, 'AES-256-CBC',$key,0,base64_decode($data['iv']));
  $encrypt=base64_encode(json_encode($data));
  return $encrypt;
}

2. openssl decryption method:

function decrypt($encrypt)
{
  $key = '1112121212121212121212';//解密钥匙
  $encrypt = json_decode(base64_decode($encrypt), true);
  $iv = base64_decode($encrypt['iv']);
  $decrypt = openssl_decrypt($encrypt['value'], 'AES-256-CBC', $key, 0, $iv);
  $id = unserialize($decrypt);
  if($id){
    return $id;
  }else{
    return 0;
  }
}

The above is the detailed content of PHP encryption and decryption method based on openssl. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

See all articles

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!