andybeak/envelope_encryption

此软件包使得执行信封加密更加方便。

v1.0.0 2019-08-05 18:55 UTC

This package is auto-updated.

Last update: 2024-09-23 11:49:03 UTC


README

Build Status Maintainability Test Coverage

此软件包使得执行信封加密更加方便。

这种加密模式涉及使用一个安全密钥存储库来存储主密钥。每次加密数据时,都会生成一个新的随机密钥来使用。此密钥与主密钥加密并存储在数据旁边。

使用此模式意味着您永远不需要将主密钥部署到服务器上。主密钥保持在安全的密钥存储中。

请注意,这对于高速数据加密来说是一种反模式。每次加密时,您都会向密钥提供商发出HTTPS调用,这显然会增加您的响应时间的网络I/O。

另一种模式是使用相同的单个数据密钥对所有记录进行加密。您可以解密此密钥并将其存储在配置对象中,以避免反复调用KMS。

用法

使用KMS作为后端服务创建对象

使用工厂创建对象的实例。它接受一个枚举类型,表示提供程序的类型以及构建提供程序时要使用的设置。

use \AndyBeak\EnvelopeEncryption\EnvelopeEncryptionFactory; 
use \AndyBeak\EnvelopeEncryption\Enum\KeyStoresEnum;

$settings = [
    'keyId' => 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab',
    'region' => 'eu-west-2',
    'keySpec' => 'AES_256'
];   
$envelopeEncryption = EnvelopeEncryptionFactory::create(new KeystoresEnum(KeystoresEnum::AWS), $settings);

只有keyId是必需的,其他值如果省略,则默认为显示的值。

加密和解密

一旦您有了EnvelopeEncryption对象,您可以像以下这样调用encrypt方法

$envelopeEncrypted = $envelopeEncryption->encrypt('Hello World');    

此返回的关联数组格式如下

return [
    'ciphertext' => 'The encrypted string'
    'nonce' => 'A nonce that you must supply when decrypting',
    'encryptedDataKey' => 'The encrypted copy of the key that was used to encrypt the data'
]; 

您需要存储所有三份数据!

要解密,请调用decrypt并供应从encrypt返回的信息

$plaintext = $envelopeEncryption->decrypt(
    $envelopeEncrypted['ciphertext'],
    $envelopeEncrypted['nonce'],
    $envelopeEncrypted['encryptedDataKey']
);
var_dump($plaintext);
// string(11) "Hello World"

完整示例

<?php

require 'vendor/autoload.php';

use \AndyBeak\EnvelopeEncryption\EnvelopeEncryptionFactory;
use \AndyBeak\EnvelopeEncryption\Enum\KeyStoresEnum;

$settings = [
    'keyId' => 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab',
    'region' => 'eu-west-2',
    'keySpec' => 'AES_256'
];

$envelopeEncryption = EnvelopeEncryptionFactory::create(new KeystoresEnum(KeystoresEnum::AWS), $settings);

$envelopeEncrypted = $envelopeEncryption->encrypt('Hello World');

$plaintext = $envelopeEncryption->decrypt(
    $envelopeEncrypted['ciphertext'],
    $envelopeEncrypted['nonce'],
    $envelopeEncrypted['encryptedDataKey']
);

var_dump($plaintext);
// string(11) "Hello World"

后端服务

目前此软件包仅支持AWS KMS,但通过添加新的KeystoreProviderInterface实现,应该可以轻松设置其他服务,如Hashicorp Vault。

KMS

您需要在AWS KMS中设置一个密钥。

SDK应从以下之一检测凭据

更多信息可在AWS PHP SDK文档页面上找到。