PHP官方现代化核心加密库 Sodium

2024-08-19 16:09:25 浏览数 (1)

概述

Sodium crypto library是一个现代化的,易于使用的软件库,用于加密,解密,签名,密码散列等。

Sodium 出现的目的也是为了代替 Mcrypt 这个原来的加密扩展。在 PHP7.2 之后,Mcrypt 已经被移除,在 PHP7.1 时就已经被标记为过时。不过,Sodium 扩展的应用也并不是很多,大部分情况下我们都会使用 OpenSSL 来进行加密操作,同时,Sodium 扩展提供的函数也非常多

Sodium 扩展在 PHP7.2 后是跟随 PHP 源码一起发布的,只需要在编译的时候加上--with-sodium即可安装成功。如果是 PHP7.2 之前的版本,需要单独安装这个扩展。同时,操作系统中也需要安装 libsodium-devel 库.

安装

代码语言:javascript复制
sudo pecl install -f libsodium

以下表示安装成功

代码语言:javascript复制
Build process completed successfully
Installing '/usr/local/php-7.4/lib/php/extensions/no-debug-non-zts-20190902/sodium.so'
install ok: channel://pecl.php.net/libsodium-2.0.23
configuration option "php_ini" is not set to php.ini location
You should add "extension=sodium.so" to php.ini

安装错误

代码语言:javascript复制
checking for libsodium... configure: error: Please install libsodium - See https://github.com/jedisct1/libsodium
ERROR: `/tmp/pear/temp/libsodium/configure --with-php-config=/usr/local/php-7.4/bin/php-config' failed

请安装扩展系统扩展库libsodium-dev

代码语言:javascript复制
sudo apt install libsodium-dev

Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following NEW packages will be installed:
  libsodium-dev
0 upgraded, 1 newly installed, 0 to remove and 254 not upgraded.
Need to get 160 kB of archives.
After this operation, 760 kB of additional disk space will be used.
Get:1 http://mirrors.cloud.aliyuncs.com/ubuntu bionic/main amd64 libsodium-dev amd64 1.0.16-2 [160 kB]
Fetched 160 kB in 0s (1,514 kB/s) 
Selecting previously unselected package libsodium-dev:amd64.
(Reading database ... 161808 files and directories currently installed.)
Preparing to unpack .../libsodium-dev_1.0.16-2_amd64.deb ...
Unpacking libsodium-dev:amd64 (1.0.16-2) ...
Setting up libsodium-dev:amd64 (1.0.16-2) ...

修改php.ini

代码语言:javascript复制
extension=sodium.so

查看模块

代码语言:javascript复制
php -m |grep sodium
sodium

简单使用

加密

代码语言:javascript复制
<?php
/**
 * @desc libsodium
 * @author Tinywan(ShaoBo Wan)
 * @date 2024/8/14 22:45
 */
require '../vendor/autoload.php';

$secretKey = sodium_crypto_secretbox_keygen();
$message = 'Sensitive 开源技术小栈';

$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$encryptedMessage = sodium_crypto_secretbox($message, $nonce, $secretKey);
var_dump($encryptedMessage);

输出

代码语言:javascript复制
string(44) "�̥|}3�¢ҥ[zm


	

0 人点赞