PHP 对 age 文件加密命令行工具的包装

1.1.0 2023-08-24 11:11 UTC

This package is auto-updated.

Last update: 2024-09-20 15:47:26 UTC


README

使用 PHP 通过 age 加密和解密文件。此库仅是命令行工具的包装,它不实现 PHP 中的 C2CP age 规范。

// Encrypt a file with a generated key
$age = new FileEncryption("hello.txt");
$keypair = $age->keygen("hello.key")->encrypt("hello.txt.age");

// Encrypt a file with a specific public key
$age->public_key("age1mrf8uana2kan6jsrnf04ywxycvl4nnkzzk3et8rdz6fe6vg7upssclnak7")->encrypt("hello.txt.age");
// Decrypt a file with a key file
$age = new FileEncryption("hello.txt.age");
$age->private_key("hello.key")->decrypt("decrypted-hello.txt");

安装

此库需要 PHP 8.1+ 和 age 命令行工具

  1. 安装 age 命令行工具
  2. 使用 composer 安装此库
    composer require victorwesterlund/php-age
    

如何使用

导入并使用库

require_once "vendor/autoload.php";

use \Age\FileEncryption;

加密文件

通过将文件传递给 FileEncryption 构造函数在磁盘上加密文件

// Relative or absolute path to a file that should be encrypted
$age = new FileEncryption("hello.txt");

注意 库不会为您存档文件夹。您必须在传递给 FileEncryption 之前使用 tar 对文件夹进行打包

生成的密钥对

您可以通过链式调用 keygen() 使用生成的密钥对(age-keygen)加密文件

// encrypt() will return the generated keypair as an assoc array
$keypair = $age->keygen()->encrypt("hello.txt.age"); // ["public" => "...", "private" => "..."]

您还可以通过将绝对或相对路径传递给 keygen() 将生成的密钥文件保存到磁盘

$keypair = $age->keygen("hello.key)->encrypt("hello.txt.age"); // ["public" => "...", "private" => "..."]

现有的公钥

通过链式调用 public_key() 方法使用现有的公钥加密文件

$keypair = $age->public_key("age1mrf8uana2kan6jsrnf04ywxycvl4nnkzzk3et8rdz6fe6vg7upssclnak7")->encrypt("hello.txt.age"); // ["public" => "age1mrf8uana2kan6jsrnf04ywxycvl4nnkzzk3et8rdz6fe6vg7upssclnak7", "private" => null]

解密文件

通过将文件传递给 FileEncryption 构造函数在磁盘上解密文件

// Relative or absolute path to a file that should be decrypted
$age = new FileEncryption("hello.txt.age");

通过与对应密钥文件的绝对或相对路径链式调用 private_key()

$age->private_key("hello.key")->decrypt("decrypted-hello.txt"); // true

可选功能

通过链式调用可选的 armor() 方法启用 PEM 编码

$keypair = $age->armor()->keygen()->encrypt("hello.txt.age");