Home Backend Development PHP Tutorial [PHP]利用openssl_random_pseudo_bytes跟base64_encode函数来生成随机字符串

[PHP]利用openssl_random_pseudo_bytes跟base64_encode函数来生成随机字符串

Jun 13, 2016 pm 12:17 PM
bytes length openssl random

[PHP]利用openssl_random_pseudo_bytes和base64_encode函数来生成随机字符串

openssl_random_pseudo_bytes函数本身是用来生成指定个数的随机字节,因此在使用它来生成随机字符串时,还需要配合使用函数base64_encode。如下所示:

<code class="php hljs "><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getRandomString</span><span class="hljs-params">(<span class="hljs-variable">$length</span> = <span class="hljs-number">42</span>)</span>    {</span>        <span class="hljs-comment">/*         * Use OpenSSL (if available)         */</span>        <span class="hljs-keyword">if</span> (function_exists(<span class="hljs-string">'openssl_random_pseudo_bytes'</span>)) {            <span class="hljs-variable">$bytes</span> = openssl_random_pseudo_bytes(<span class="hljs-variable">$length</span> * <span class="hljs-number">2</span>);            <span class="hljs-keyword">if</span> (<span class="hljs-variable">$bytes</span> === <span class="hljs-keyword">false</span>)                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">'Unable to generate a random string'</span>);            <span class="hljs-keyword">return</span> substr(str_replace([<span class="hljs-string">'/'</span>, <span class="hljs-string">'+'</span>, <span class="hljs-string">'='</span>], <span class="hljs-string">''</span>, base64_encode(<span class="hljs-variable">$bytes</span>)), <span class="hljs-number">0</span>, <span class="hljs-variable">$length</span>);        }        <span class="hljs-variable">$pool</span> = <span class="hljs-string">'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'</span>;        <span class="hljs-keyword">return</span> substr(str_shuffle(str_repeat(<span class="hljs-variable">$pool</span>, <span class="hljs-number">5</span>)), <span class="hljs-number">0</span>, <span class="hljs-variable">$length</span>);    }</code>
Copy after login

在调用base64_encode函数之后,还对结果进行了一次替换操作,目的是要去除随机生成的字符串中不需要的字符。

当然,在使用openssl_random_pseudo_bytes函数之前,最好使用function_exists来确保该函数在运行时是可用的。如果不可用,则使用Plan B:

<code class="php hljs ">substr(str_shuffle(str_repeat(<span class="hljs-variable">$pool</span>, <span class="hljs-number">5</span>)), <span class="hljs-number">0</span>, <span class="hljs-variable">$length</span>);</code>
Copy after login

这个函数的通用性很强,可以根据业务的需要进行适当修改然后当作静态方法进行调用。

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Nginx uses the OpenSSL library for more secure communication How Nginx uses the OpenSSL library for more secure communication Jun 10, 2023 pm 01:51 PM

Nginx is a software widely used in web servers, load balancers, reverse proxies and caches. During network transmission, data encryption and security have received increasing attention. In order to improve the security of communication, the OpenSSL library can be used to implement the SSL/TLS protocol to protect the transmission of sensitive data. This article will explain how to use Nginx and the OpenSSL library to achieve more secure communication. Install and configure the OpenSSL library. First, you need to install the OpenSSL library on the server. Can make

How to generate a MySQL SSL certificate using OpenSSL How to generate a MySQL SSL certificate using OpenSSL Sep 09, 2023 pm 02:12 PM

Introduction to how to use OpenSSL to generate a MySQL SSL certificate: MySQL is a widely used relational database system. It is very important to use the SSL (SecureSocketsLayer) protocol for encrypted communication in actual production environments. This article will introduce how to use the OpenSSL tool to generate a MySQL SSL certificate and provide corresponding code examples. Steps: Install OpenSSL: First, make sure you have OpenSSL installed on your computer

HWID V 2.2 manual activation methods and tutorials HWID V 2.2 manual activation methods and tutorials Oct 20, 2023 pm 07:17 PM

This is for users who want to perform manual activation. If you need help with a tool for you to do this, then check here. We can divide the manual activation process into two parts. 1- From the ready-made batch file make sure the internet is enabled. Open Windows Powershell as administrator and enter the following to list the commands in the order they are given. Enter the key, (replace with the key from the list above) Use the following command &lt;key&gt;slmgr/ipk&lt;key&gt; Download the universal ticket from here and extract the downloaded file. Now enter the following code in Powershell (Get-ItemProper

OpenBLAS installation under CentOS 7 and CentOS 7 OpenSSL installation OpenBLAS installation under CentOS 7 and CentOS 7 OpenSSL installation Feb 10, 2024 am 11:45 AM

As an open source operating system, LINUX has a wide range of applications and user groups. CentOS7 is a branch version of LINUX. It is built based on the RedHat Enterprise Linux (RHEL) source code and has a high degree of stability and security. It can be installed and configured on CentOS7 OpenBLAS and OpenSSL are common needs of many developers and system administrators. This article will detail how to install and configure OpenBLAS and OpenSSL on CentOS7. OpenBLAS is an open source high-performance mathematics library based on the BLAS (BasicLinearAlgebraSubprograms) interface.

Use java's String.length() function to get the length of a string Use java's String.length() function to get the length of a string Jul 25, 2023 am 09:09 AM

Use Java's String.length() function to get the length of a string. In Java programming, string is a very common data type. We often need to get the length of a string, that is, the number of characters in the string. In Java, we can use the length() function of the String class to get the length of a string. Here is a simple example code: publicclassStringLengthExample{publ

Java generates random double precision floating point numbers using nextDouble() function of Random class Java generates random double precision floating point numbers using nextDouble() function of Random class Jul 25, 2023 am 09:06 AM

Java uses the nextDouble() function of the Random class to generate random double-precision floating-point numbers. The Random class in Java is a pseudo-random number generator that can be used to generate different types of random numbers. Among them, the nextDouble() function is used to generate a random double-precision floating point number. Before using the Random class, we need to import the java.util package first. Next we can create a Random object and use the nextDouble() function

How to use demo of python random library How to use demo of python random library May 05, 2023 pm 08:13 PM

Simple use of pythonrandom library demo When we need to generate random numbers or randomly select elements from a sequence, we can use Python's built-in random library. The following is an annotated example that demonstrates how to use the random library: #Import random library importrandom #Generate a random decimal between 0 and 1 random_float=random.random()print(random_float)#Generate a random decimal within the specified range Random integer (including endpoints) random_int=random.randint(1,10)print(random_int)#

How to solve 'undefined: bytes.Split' error in golang? How to solve 'undefined: bytes.Split' error in golang? Jun 25, 2023 pm 02:02 PM

In the Go language, the bytes package is a package for manipulating byte types, and it contains many useful methods, such as the Split() method. However, when using the Split() method, you may encounter an "undefined: bytes.Split" error. This error is usually caused by incompatible Go versions or lack of necessary dependent libraries. This article will introduce some methods to solve this error. Method 1: Upgrade the Go version as follows

See all articles