初始化KMS实例SDK客户端后,您可以通过客户端调用Encrypt和Decrypt接口对数据进行加密解密。本文介绍加密解密的代码示例。
完整代码示例
集成KMS进行对称加密解密包含三个步骤:
源码github地址:AesEncryptDecrypt.php
代码示例解析
初始化客户端
关于初始化客户端的详细介绍,请参见初始化客户端。
<?php
use AlibabaCloud\Dkms\Gcs\Sdk\Client as AlibabaCloudDkmsGcsSdkClient;
use AlibabaCloud\Dkms\Gcs\OpenApi\Models\Config as AlibabaCloudDkmsGcsOpenApiConfig;
function getDkmsGcsSdkClient()
{
global $clientKeyContent, $password, $endpoint;
// 构建KMS实例SDK Client配置
$config = new AlibabaCloudDkmsGcsOpenApiConfig();
//连接协议请设置为"https"。KMS实例服务仅允许通过HTTPS协议访问。
$config->protocol = 'https';
//Client Key。
$config->clientKeyContent = $clientKeyContent;
//Client Key口令。
$config->password = $password;
//设置endpoint为<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
$config->endpoint = $endpoint;
// 实例CA证书
$config->caFilePath = 'path/to/caCert.pem';
// 构建KMS实例SDK Client对象
return new AlibabaCloudDkmsGcsSdkClient($config);
}
调用Encrypt接口使用对称密钥对数据加密
/**
* 加密示例
* @param AlibabaCloudDkmsGcsSdkClient $client
* @param string $keyId
* @param string $plaintext
* @param string $algorithm
* @return AesEncryptContext
*/
function aesEncryptSample($client, $keyId, $plaintext, $algorithm)
{
// 构建加密请求
$encryptRequest = new EncryptRequest();
$encryptRequest->keyId = $keyId;
$encryptRequest->algorithm = $algorithm;
$encryptRequest->plaintext = AlibabaCloudTeaUtils::toBytes($plaintext);
$runtimeOptions = new RuntimeOptions();
// 忽略服务端证书
//$runtimeOptions->ignoreSSL = true;
try {
// 调用加密接口进行加密
$encryptResponse = $client->encryptWithOptions($encryptRequest, $runtimeOptions);
// 密钥ID
$keyId = $encryptResponse->keyId;
// 主密钥是对称密钥时,decrypt接口需要加密返回的Iv
$iv = $encryptResponse->iv;
// 数据密文
$cipher = $encryptResponse->ciphertextBlob;
// 加密算法
$algorithm = $encryptResponse->algorithm;
var_dump($encryptResponse->toMap());
return new AesEncryptContext([
'keyId' => $keyId,
'iv' => $iv,
'ciphertextBlob' => $cipher,
'algorithm' => $algorithm
]);
} catch (\Exception $error) {
if ($error instanceof \AlibabaCloud\Tea\Exception\TeaError) {
var_dump($error->getErrorInfo());
}
var_dump($error->getMessage());
var_dump($error->getTraceAsString());
}
return null;
}
调用Decrypt接口使用对称密钥解密密文
/**
* 解密示例
* @param AlibabaCloudDkmsGcsSdkClient $client
* @param AesEncryptContext $ctx
* @return int[]|null
*/
function aesDecryptSample($client, $ctx)
{
// 构建解密请求对象
$decryptRequest = new DecryptRequest();
$decryptRequest->keyId = $ctx->keyId;
$decryptRequest->ciphertextBlob = $ctx->ciphertextBlob;
$decryptRequest->algorithm = $ctx->algorithm;
$decryptRequest->iv = $ctx->iv;
$runtimeOptions = new RuntimeOptions();
// 忽略证书
//$runtimeOptions->ignoreSSL = true;
try {
// 调用解密接口进行解密
$decryptResponse = $client->decryptWithOptions($decryptRequest, $runtimeOptions);
var_dump($decryptResponse->toMap());
return $decryptResponse->plaintext;
} catch (Exception $error) {
if ($error instanceof \AlibabaCloud\Tea\Exception\TeaError) {
var_dump($error->getErrorInfo());
}
var_dump($error->getMessage());
var_dump($error->getTraceAsString());
}
return null;
}
该文章对您有帮助吗?