php-awsHow can I use AWS KMS with PHP?
Using AWS KMS with PHP is simple and straightforward. The following example shows how to encrypt a string using a customer master key (CMK) in AWS KMS and PHP:
<?php
// Include the AWS SDK using the Composer autoloader.
require 'vendor/autoload.php';
// Create an AWS KMS client using the shared credentials file.
$kms = new Aws\Kms\KmsClient([
'region' => 'us-east-1',
'version' => '2014-11-01',
]);
// Create an encryption context.
$context = [
'Example' => 'Encryption Context',
];
// Encrypt a string using a customer master key (CMK).
$result = $kms->encrypt([
'KeyId' => '1234abcd-12ab-34cd-56ef-1234567890ab',
'Plaintext' => 'This is the message to encrypt.',
'EncryptionContext' => $context,
]);
// Print the encrypted data.
echo $result['CiphertextBlob'];
// Output:
// AQICAHh4f4VFrXNmT4Tf+YdV6hVb3VkRX2TmY6y/eVVU/mhHVAAAAZjBkBgkqhkiG9w0BBwagVzBVAgEAMEsGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQM9zGd9a7J+E/E4C9AgEQgCJ+3v2C3hLhVdQ6YI9IyVj/rVf/9f4HhZV7P8KvXrA==
- Include the AWS SDK using the Composer autoloader:
require 'vendor/autoload.php';
- Create an AWS KMS client using the shared credentials file:
$kms = new Aws\Kms\KmsClient([ ... ]);
- Create an encryption context:
$context = [ 'Example' => 'Encryption Context', ];
- Encrypt a string using a customer master key (CMK):
$result = $kms->encrypt([ ... ]);
- Print the encrypted data:
echo $result['CiphertextBlob'];
The output of the example code is the encrypted string AQICAHh4f4VFrXNmT4Tf+YdV6hVb3VkRX2TmY6y/eVVU/mhHVAAAAZjBkBgkqhkiG9w0BBwagVzBVAgEAMEsGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQM9zGd9a7J+E/E4C9AgEQgCJ+3v2C3hLhVdQ6YI9IyVj/rVf/9f4HhZV7P8KvXrA==
.
Helpful links
More of Php Aws
- How do I use PHP to create a ZIP file on AWS?
- How can I use AWS and Zksync together with PHP?
- How can I use Yum to install PHP on an Amazon EC2 instance?
- How can I use an AWS SQS Worker with PHP?
- How can I use AWS WAF to secure my PHP application?
- How can I use AWS PHP SDK without credentials?
- How do I generate an AWS Signature Version 4 with PHP?
- How do I determine the version of PHP I am running on AWS?
- How can I use the AWS S3 S3Client library with PHP?
- How can I connect to an AWS MySQL database using PHP?
See more codes...