云 API 密钥安全方案推荐

代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。建议不要在代码中使用持久 SecretId 和 SecretKey,为了提高密钥的安全性,推荐以下几种方案。

相关产品
云 API 产品页,含版本规格、价格与购买入口。

一、方案1:通过环境变量读取 SecretId 和 SecretKey

将 SecretId 和 SecretKey 预先配置到环境变量中,在代码运行时从环境变量中读取 SecretId 和 SecretKey 的值,代码示例如下:

import osfrom tencentcloud.common import credentialfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKExceptionfrom tencentcloud.cvm.v20170312 import cvm_client, modelstry: # 硬编码密钥到代码中有可能随代码泄露而暴露,有安全隐患,不推荐 # 为保护密钥安全,建议将密钥设置在环境变量中 # cred = credential.Credential("secretId", "secretKey") cred = credential.Credential( os.environ.get("TENCENTCLOUD_SECRET_ID"), os.environ.get("TENCENTCLOUD_SECRET_KEY")) client = cvm_client.CvmClient(cred, "ap-shanghai") req = models.DescribeInstancesRequest() resp = client.DescribeInstances(req) print(resp.to_json_string())except TencentCloudSDKException as err: print(err)

环境变量配置可参考以下方式:

·临时配置(当前终端会话中生效,关闭终端后失效)

Linux/macOS 系统Windows 系统export TENCENTCLOUD_SECRET_ID=你的SecretIdexport TENCENTCLOUD_SECRET_KEY=你的SecretKeyset TENCENTCLOUD_SECRET_ID=你的SecretIdset TENCENTCLOUD_SECRET_KEY=你的SecretKey

·永久配置(所有终端生效,重启终端或系统后仍有效)

Linux/macOS 系统Windows 系统

# 编辑环境变量文件echo 'export TENCENTCLOUD_SECRET_ID=你的SecretId' >> ~/.bashrcecho 'export TENCENTCLOUD_SECRET_KEY=你的SecretKey' >> ~/.bashrc# 使配置立即生效source ~/.bashrc

1. 右键点击此电脑,选择属性。

2. 单击高级系统设置,选择环境变量。

3. 在系统变量区域中,单击 新建,依次添加以下两个变量:

·变量名:TENCENTCLOUD_SECRET_ID

变量值:你的 SecretId。

·变量名:TENCENTCLOUD_SECRET_KEY

变量值:你的 SecretKey。

4. 添加完成后,单击确定保存配置。

·验证配置是否成功

Linux/macOS 系统Windows 系统echo $TENCENTCLOUD_SECRET_ID echo $TENCENTCLOUD_SECRET_KEYecho %TENCENTCLOUD_SECRET_ID%echo %TENCENTCLOUD_SECRET_KEY%

二、方案2:使用临时密钥

不在代码中使用持久 SecretId 和 SecretKey,而是使用通过 GetFederationToken 接口换取的用户临时密钥,同时根据权限最小化原则赋予相关权限。代码示例如下:

# 换取临时秘钥的 SDK 示例import jsonimport osfrom tencentcloud.common import credentialfrom tencentcloud.common.profile.client_profile import ClientProfilefrom tencentcloud.common.profile.http_profile import HttpProfilefrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKExceptionfrom tencentcloud.sts.v20180813 import sts_client, modelstry:# 实例化一个认证对象,入参需要传入腾讯云账户的secretId和secretKey,为了保护密钥安全,建议结合方案一,将密钥设置在环境变量中 cred = credential.Credential( os.environ.get("TENCENTCLOUD_SECRET_ID"), os.environ.get("TENCENTCLOUD_SECRET_KEY")) httpProfile = HttpProfile() httpProfile.endpoint = "sts.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = sts_client.StsClient(cred, "", clientProfile) req = models.GetFederationTokenRequest() params = { } req.from_json_string(json.dumps(params)) resp = client.GetFederationToken(req) print(resp.to_json_string())except TencentCloudSDKException as err: print(err)

三、方案3:使用 KMS 白盒密钥保护 SecretKey

操作指导请参见 密钥管理系统-使用 KMS 白盒密钥保护 SecretKey 实践教程。

赞 (0)
上一篇 4天前
下一篇 4天前