AWS.Cryptography.EncryptionSDK.AwsEncryptionSdkException:无法构建标头正文

问题描述 投票:0回答:1

我尝试使用适用于 .NET 的 AWS 加密开发工具包通过 KMS 加密和解密纯文本。加密字符串时,我在标题中看到错误。我不确定我做错了什么,因为我基本上遵循 AWS 提供的示例代码保存指定凭据,以便 SDK 可以访问 KMS 密钥(如果我不指定凭据,我会得到以下信息错误“Amazon.Runtime.AmazonServiceException:无法从 EC2 实例元数据服务获取 IAM 安全凭证。”)。我已经检查过 AccessKeyId 和 SecretKey 是否具有对使用 _options.KmsKeyArn 指定的 KMS 密钥的完全访问权限。该错误消息根本没有帮助。当我尝试将 SessionCredentials 与尚未过期的令牌一起使用时,会引发相同的错误。

`

public class CryptographyService : ICryptographyService
{

    private readonly ESDK _cryptoClient;
    private readonly MaterialProviders _materialProviders;
    private readonly CryptographyOptions _options;
    private readonly IKeyring _keyRing;

    public CryptographyService(IOptions<CryptographyOptions> options)
    {
        _options = options.Value;

        var credentials = new BasicAWSCredentials(_options.AccessKey, _options.SecretKey);

        _cryptoClient = new ESDK(new AwsEncryptionSdkConfig());
        _materialProviders = new MaterialProviders(new MaterialProvidersConfig());

        var keyringInput = new CreateAwsKmsKeyringInput
        {
            KmsClient = new AmazonKeyManagementServiceClient(credentials, RegionEndpoint.GetBySystemName(_options.RegionEndpoint)),
            KmsKeyId = _options.KmsKeyArn
        };

        _keyRing = _materialProviders.CreateAwsKmsKeyring(keyringInput);

        var createCmmInput = new CreateRequiredEncryptionContextCMMInput
        {
            UnderlyingCMM = _materialProviders.CreateDefaultCryptographicMaterialsManager(new CreateDefaultCryptographicMaterialsManagerInput { Keyring = _keyRing }),
            RequiredEncryptionContextKeys = new List<string>(_options.GetEncryptionContext().Keys)
        };

        _ = _materialProviders.CreateRequiredEncryptionContextCMM(createCmmInput);
    }

    public async ValueTask<string> EncryptPlainText(string plainText)
    {
        EncryptOutput encryptOutput;
        await using (var stream = MemoryStreamFromString(plainText))
        {
            var encryptInput = new EncryptInput()
            {
                Plaintext = stream,
                Keyring = _keyRing,
                EncryptionContext = _options.GetEncryptionContext()
            };
            encryptOutput = _cryptoClient.Encrypt(encryptInput);
        }
        return StringFromMemoryStream(encryptOutput.Ciphertext);
    }

    private static MemoryStream MemoryStreamFromString(string s) => new(Encoding.ASCII.GetBytes(s));
}`

我尝试使用带有有效令牌的会话凭据,指定加密算法,不使用加密上下文,不指定 CMM。所有这些都会导致相同的错误消息。不指定凭证会导致错误消息“Amazon.Runtime.AmazonServiceException:无法从 EC2 实例元数据服务获取 IAM 安全凭证。”

c# .net encryption aws-sdk amazon-kms
1个回答
0
投票

您使用什么操作系统/平台?如果您使用的是基于 ARM 的 Mac(M1、M2 等),那么您将需要遵循此处详细说明的一些额外说明:https://github.com/aws/aws-encryption-sdk-dafny/tree /mainline/AwsEncryptionSDK/runtimes/net#additional-setup-for-macos-only

谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.