cleanpy 0.1.3

Python 3.12+ 最佳实践知识库 - MCP 服务器
Documentation
---
topic: owasp_sensitive_data
title: OWASP - 敏感数据暴露防护
when_to_use: 处理敏感数据和加密时
keywords:
  - OWASP
  - 敏感数据
  - 加密
  - 安全
---

# OWASP #3: 敏感数据暴露

## 环境变量管理

### ❌ 硬编码机密

```python
API_KEY = "sk_live_abcd1234"
DATABASE_URL = "postgresql://user:password@localhost/db"
```

### ✅ 使用环境变量

```python
import os
from dotenv import load_dotenv

load_dotenv()

API_KEY = os.getenv("API_KEY")
DATABASE_URL = os.getenv("DATABASE_URL")

if not API_KEY:
    raise ValueError("API_KEY must be set")
```

## 数据加密

### ✅ 加密敏感数据

```python
from cryptography.fernet import Fernet

# 生成密钥(仅一次,存储安全)
key = Fernet.generate_key()
cipher = Fernet(key)

# 加密
encrypted = cipher.encrypt(b"sensitive data")

# 解密
decrypted = cipher.decrypt(encrypted)
```

## 最佳实践

- 永远不要硬编码机密
- 使用环境变量或密钥管理服务
- 加密传输中的敏感数据(HTTPS)
- 加密静态敏感数据
- 不要在日志中记录敏感信息
- 使用 `.gitignore` 防止提交 `.env` 文件

## 相关链接

- [OWASP 密码存储备忘单]https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
- [python-dotenv 文档]https://pypi.org/project/python-dotenv/
- [cryptography 文档]https://cryptography.io/