【发布时间】:2019-12-22 08:07:31
【问题描述】:
据我在网上看到,我必须包含一段代码 sn-p 来解密使用 KMS 密钥加密的环境变量,但是有谁知道为什么必须在 lambda 函数时执行此步骤的理由已经可以访问密钥,可以即时解密值,并将解密的值传递给底层执行?
从 AWS 控制台上生成的代码复制到我的代码中:
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Amazon.KeyManagementService;
using Amazon.KeyManagementService.Model;
namespace AWSLambda
{
public class Function
{
private static string Key1Value;
// Read values once, in the constructor
public Function()
{
// Decrypt code should run once and variables stored outside of the
// function handler so that these are decrypted once per container
Key1Value = DecodeEnvVar("ConnString").Result;
}
private static async Task<string> DecodeEnvVar(string envVarName)
{
// Retrieve env var text
var encryptedBase64Text = Environment.GetEnvironmentVariable(envVarName);
// Convert base64-encoded text to bytes
var encryptedBytes = Convert.FromBase64String(encryptedBase64Text);
// Construct client
using (var client = new AmazonKeyManagementServiceClient())
{
// Construct request
var decryptRequest = new DecryptRequest
{
CiphertextBlob = new MemoryStream(encryptedBytes),
};
// Call KMS to decrypt data
var response = await client.DecryptAsync(decryptRequest);
using (var plaintextStream = response.Plaintext)
{
// Get decrypted bytes
var plaintextBytes = plaintextStream.ToArray();
// Convert decrypted bytes to ASCII text
var plaintext = Encoding.UTF8.GetString(plaintextBytes);
return plaintext;
}
}
}
public void FunctionHandler()
{
Console.WriteLine("Encrypted environment variable Key1 = " + Key1Value);
}
}
}
【问题讨论】:
标签: encryption aws-lambda environment-variables aws-kms