salesforce如何在系统里保存密码
在 Salesforce 中,保存密码或类似敏感信息时,不应以明文形式存储,而应采用安全的加密和存储机制。以下是一些最佳实践和实现方法:
1. 使用 Salesforce 提供的加密机制
Salesforce 提供了一些内置的加密工具,可以用来加密敏感数据:
Apex 加密库
Salesforce 的 Crypto
类允许开发者对数据进行加密和解密。
-
示例:加密密码
String secretKey = 'YourSecretKey1234567'; // 必须是 16 字符或 32 字符 Blob key = Crypto.generateAesKey(128); Blob dataToEncrypt = Blob.valueOf('YourPassword'); Blob encryptedData = Crypto.encryptWithManagedIV('AES128', key, dataToEncrypt); String encryptedString = EncodingUtil.base64Encode(encryptedData); System.debug('Encrypted Password: ' + encryptedString);
-
示例:解密密码
Blob encryptedData = EncodingUtil.base64Decode(encryptedString); Blob decryptedData = Crypto.decryptWithManagedIV('AES128', key, encryptedData); String decryptedString = decryptedData.toString(); System.debug('Decrypted Password: ' + decryptedString);
注意: 请将加密密钥安全地存储在 Salesforce 的 Protected Custom Settings 或 Custom Metadata 中,确保不暴露在代码中。
2. 使用 Protected Custom Settings 保存密钥
- Protected Custom Settings 是一种只允许管理员访问的存储机制,适合保存加密密钥。
- 步骤:
- 创建一个 Custom Setting 类型为 “Hierarchy” 的对象。
- 将密钥存储为一个字段,设置为 “Protected”。
- 在 Apex 代码中读取该 Custom Setting 中的密钥。
3. 使用 Salesforce Shield 平台加密
- Salesforce Shield 提供了一种透明加密机制,可以加密某些标准和自定义字段。
- 适用场景:
- 如果需要加密存储数据但不需要手动处理加密/解密逻辑。
- 设置方法:
- 启用 Shield Platform Encryption(需要额外许可)。
- 配置需要加密的字段,例如保存密码哈希的字段。
4. 使用哈希算法代替存储密码
如果不需要解密密码(例如,用于验证用户输入),可以使用单向哈希算法保存密码。
示例:生成密码哈希
String password = 'YourPassword';
Blob passwordBlob = Blob.valueOf(password);
Blob hash = Crypto.generateDigest('SHA-256', passwordBlob);
String hashedPassword = EncodingUtil.base64Encode(hash);
System.debug('Hashed Password: ' + hashedPassword);
验证密码
在验证密码时,重新计算哈希值并与存储的哈希值比较。
5. 使用外部安全服务
- 如果密码或敏感信息的存储和管理复杂,建议将其委托给外部服务,如:
- AWS Secrets Manager
- Azure Key Vault
- Google Cloud Secret Manager
- 使用 API 访问这些服务,避免将敏感数据直接存储在 Salesforce 中。
6. 遵循安全最佳实践
-
限制访问:
- 使用 Field-Level Security 限制对存储密码的字段的访问。
- 使用 Profiles 和 Permission Sets 管理对敏感数据的访问权限。
-
最小化存储:
- 如果可能,避免存储密码或敏感数据,直接集成 OAuth 或其他身份验证机制。
-
定期审计:
- 定期检查系统中存储的敏感数据,确保遵循安全合规要求。