返回顶部
首页 > 资讯 > 后端开发 > PHP编程 >PHP AES 加密解密
  • 719
分享到

PHP AES 加密解密

2024-02-27 21:02:07 719人浏览 泡泡鱼
摘要

PHP 有一个使用 php 的 AES 方法加密和解密字符串的内置扩展。 函数 openssl_encrypt() 用于加密字符串,openssl_decrypt() 用于解密字符串。 在 P

PHP 有一个使用 phpAES 方法加密和解密字符串的内置扩展。

函数 openssl_encrypt() 用于加密字符串,openssl_decrypt() 用于解密字符串。


在 PHP 中使用 Open SSL 函数加密和解密字符串

openssl_encrypt()openssl_decrypt() 采用一组强制和可选参数,有关参数的信息如下表所示:

范围 描述
data 纯文本/字符串
cipher_alGo 密码方法,在我们的例子中,AES
passphrase 如果密码短语短于限制,则会用空字符静默填充,如果长则截断。
options 标志的按位分离。OPENSSL_RAW_DATAOPENSSL_ZERO_PADDING
iv 初始化向量,非空
tag 身份验证标签 CGMCCM
aad 额外的身份验证数据。
tag_length 身份验证标签的长度在 4 到 16 之间

openssl_encrypt() 采用上述所有参数,并在使用 openssl_decrypt() 时排除 aadtag_length


<?php
//Encryption
$original_string = "Hello! This is jiyik.com";  // Plain text/String
$cipher_algo = "AES-128-CTR"; //The cipher method, in our case, AES 
$iv_length = openssl_cipher_iv_length($cipher_algo); //The length of the initialization vector
$option = 0; //Bitwise disjunction of flags
$encrypt_iv = '8746376827619797'; //Initialization vector, non-null
$encrypt_key = "jiyik!"; // The encryption key
// Use openssl_encrypt() encrypt the given string
$encrypted_string = openssl_encrypt($original_string, $cipher_algo,
            $encrypt_key, $option, $encrypt_iv);

//Decryption
$decrypt_iv = '8746376827619797'; //Initialization vector, non-null
$decrypt_key = "jiyik!"; // The encryption key
// Use openssl_decrypt() to decrypt the string
$decrypted_string=openssl_decrypt ($encrypted_string, $cipher_algo,
        $decrypt_key, $option, $decrypt_iv);

//Display Strings
echo "The Original String is: <br>" . $original_string. "<br><br>" ;
echo "The Encrypted String is: <br>" . $encrypted_string . "<br><br>";
echo "The Decrypted String is: <br>" . $decrypted_string;

?>

上面的代码首先使用 AES 方法对字符串进行加密,然后对其进行解密。

输出:


The Original String is: 
Hello! This is jiyik.com

The Encrypted String is: 
JF1iHtW4I9qK8q9OwCL9Yh1ejtZofci5

The Decrypted String is: 
Hello! This is jiyik.com

AES 根据方法和位数具有不同的 cipher_algorithams,例如 aes-128-cbcaes-192-cfbaes-256-cbc

此处查看 AES 加密和其他方法的所有选项。

--结束END--

本文标题: PHP AES 加密解密

本文链接: https://www.lsjlt.com/news/569164.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作