AWS Lambda为什么不自动解密加密的环境变量?

时间:2019-08-15 23:03:18

标签: encryption aws-lambda environment-variables aws-kms

据我在网上看到的那样,我必须包含一段代码片段来解密使用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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我想我找到了答案。加密密钥不会停留在lambda上。加密控制台上的值是一项一次性操作。重新整理页面后,到KMS的链接消失了,或者与另一个用户登录以仅在env var上看到加密的值,而没有附加加密密钥。