You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AWS Encryption SDK加密文件遇NoCredentialsError,求解决指引

解决 AWS Encryption SDK 中的 NoCredentialsError 问题

错误核心

botocore.exceptions.NoCredentialsError: Unable to locate credentials 说明代码无法获取AWS凭证,无法访问指定的KMS密钥。AWS SDK会按固定优先级查找凭证,只要让凭证能被SDK识别即可解决问题。

解决方法

1. 配置本地AWS凭证文件

在用户目录下创建.aws文件夹:

  • Windows路径:C:\Users\你的用户名\.aws
  • 在此文件夹内新建credentials文件,内容格式如下:
[default]
aws_access_key_id = 你的AWS访问密钥ID
aws_secret_access_key = 你的AWS秘密访问密钥

注意:确保该密钥对应的IAM用户拥有访问目标KMS密钥的权限(如kms:GenerateDataKey、kms:Encrypt等)。

2. 设置环境变量

运行代码前,通过环境变量注入凭证:

  • Windows命令行:
set AWS_ACCESS_KEY_ID=你的AWS访问密钥ID
set AWS_SECRET_ACCESS_KEY=你的AWS秘密访问密钥
  • Windows PowerShell:
$env:AWS_ACCESS_KEY_ID="你的AWS访问密钥ID"
$env:AWS_SECRET_ACCESS_KEY="你的AWS秘密访问密钥"

3. 代码中直接指定凭证(仅测试场景)

不推荐在生产环境硬编码凭证,但测试时可以直接传入:

kms_key_provider = aws_encryption_sdk.StrictAwsKmsMasterKeyProvider(
    key_ids=['arn:aws:kms:ap-south-1:588105036995:key/ad1e065c-b51c-76'],
    region='ap-south-1',
    aws_access_key_id='你的AWS访问密钥ID',
    aws_secret_access_key='你的AWS秘密访问密钥'
)

额外注意事项

  1. KMS密钥ARN完整性:你提供的KMS密钥ARN末尾ad1e065c-b51c-76看起来不完整,请确认是有效的完整KMS密钥ARN。
  2. 文件加密的正确写法:你的代码中把文件路径直接传给source参数,SDK会把它当成明文内容而非文件路径。正确的文件加密方式如下:
import aws_encryption_sdk
from aws_encryption_sdk.identifiers import CommitmentPolicy

client = aws_encryption_sdk.EncryptionSDKClient(commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT)
kms_key_provider = aws_encryption_sdk.StrictAwsKmsMasterKeyProvider(key_ids=['arn:aws:kms:ap-south-1:588105036995:key/完整的密钥ID'])

# 读取文件并加密
with open('D:\\test-2\\u_in220819.log', 'rb') as plaintext_file:
    plaintext = plaintext_file.read()
    ciphertext, encryptor_header = client.encrypt(source=plaintext, key_provider=kms_key_provider)

# 保存加密后的文件
with open('D:\\test-2\\u_in220819.log.encrypted', 'wb') as ciphertext_file:
    ciphertext_file.write(ciphertext)

或者使用流式加密处理大文件:

import aws_encryption_sdk
from aws_encryption_sdk.identifiers import CommitmentPolicy

client = aws_encryption_sdk.EncryptionSDKClient(commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT)
kms_key_provider = aws_encryption_sdk.StrictAwsKmsMasterKeyProvider(key_ids=['arn:aws:kms:ap-south-1:588105036995:key/完整的密钥ID'])

with open('D:\\test-2\\u_in220819.log', 'rb') as plaintext_file, open('D:\\test-2\\u_in220819.log.encrypted', 'wb') as ciphertext_file:
    with client.stream(source=plaintext_file, key_provider=kms_key_provider) as encryptor:
        for chunk in encryptor:
            ciphertext_file.write(chunk)

内容的提问来源于stack exchange,提问作者Rupesh Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 04:40:29