Home Backend Development PHP7 How to encrypt php7.0 openssl_encrypt

How to encrypt php7.0 openssl_encrypt

Jun 04, 2019 pm 02:28 PM

php5.4版本mcrypt_encryp提升到php7.0 openssl_encrypt,加密字段不一样。

How to encrypt php7.0 openssl_encrypt

今天有个加密,使用的加密字段和key,加密模式都一样,可是加密后的数据不一样,
这是代码片段

<?php
     $privateKey = "qewrvxffbfdhsfdgh";
     $iv    = "234253454354352";
     $data  = "测试用的数据";
     $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateKey, $data, MCRYPT_MODE_CBC, $iv);
     echo(base64_encode($encrypted));
     echo "\n";
 >
Copy after login

加密后的数据是gHXA5vo5hEMxjthYNq/gborXWNETPw0rYEb2FspAYzc=

下面是使用php7.0版本以上不支持mcrypt_encryp函数进行加密的代码

<?php
     $privateKey = "qewrvxffbfdhsfdgh";
     $iv    = "234253454354352";
     $data  = "测试用的数据";
     $encrypted=  openssl_encrypt($data,&#39;aes-128-cbc&#39;, $privateKey, OPENSSL_RAW_DATA, $iv);
	 echo(base64_encode($encrypted));
     echo "\n";
 >
Copy after login

加密后是gHXA5vo5hEMxjthYNq/gbtwwm1TlRzsRBI64TrEo3P8=

1.gHXA5vo5hEMxjthYNq/gborXWNETPw0rYEb2FspAYzc=

2.gHXA5vo5hEMxjthYNq/gbtwwm1TlRzsRBI64TrEo3P8=

是不是不一样,这样加密出来的数据不仔细查看,会认为是一样的数据。

要想保证加密一样,将php7.0的代码修改如下

<?php
     $privateKey = "qewrvxffbfdhsfdgh";
     $iv    = "234253454354352";
     $data  = "测试用的数据";
		if (strlen($data) % 16) {
		            $data = str_pad($data,strlen($data) + 16 - strlen($data) % 16, "\0");
		        }
		 $encrypted=  openssl_encrypt($data, &#39;AES-128-CBC&#39;,$privateKey,OPENSSL_NO_PADDING,$iv);
     echo  (base64_encode($encrypted));
Copy after login

加密后的数据是gHXA5vo5hEMxjthYNq/gborXWNETPw0rYEb2FspAYzc=,这样就保持一致了。

本文来自php7教程栏目,欢迎学习。

The above is the detailed content of How to encrypt php7.0 openssl_encrypt. For more information, please follow other related articles on the PHP Chinese website!

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)