-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencrypt_secrets.py
More file actions
executable file
·181 lines (142 loc) · 5.51 KB
/
encrypt_secrets.py
File metadata and controls
executable file
·181 lines (142 loc) · 5.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#!/usr/bin/env python3
"""
PhishGuard M3 - Secrets Encryption CLI
Interactive CLI tool to encrypt API keys and secrets
"""
import os
import sys
import getpass
import secrets
from typing import Dict, Any
from crypto_simple import save_encrypted
def generate_signing_secret() -> str:
"""
Generate a cryptographically secure signing secret.
Returns:
64-character hex string (256 bits)
"""
return secrets.token_hex(32)
def prompt_passphrase() -> str:
"""
Prompt user for passphrase with confirmation.
Returns:
Validated passphrase
Raises:
SystemExit: If passphrases don't match or user cancels
"""
print("\n🔐 PhishGuard Secrets Encryption")
print("=" * 50)
print("\nYou will create a master passphrase to encrypt your secrets.")
print("⚠️ IMPORTANT: Store this passphrase securely!")
print(" Without it, you cannot decrypt your secrets.\n")
while True:
passphrase = getpass.getpass("Enter master passphrase: ")
if not passphrase:
print("❌ Passphrase cannot be empty. Try again.\n")
continue
if len(passphrase) < 8:
print("⚠️ Warning: Passphrase is short. Recommend 12+ characters.\n")
confirm = getpass.getpass("Confirm passphrase: ")
if passphrase == confirm:
print("✅ Passphrase confirmed.\n")
return passphrase
else:
print("❌ Passphrases do not match. Try again.\n")
def prompt_secrets() -> Dict[str, Any]:
"""
Interactively prompt user for all secrets.
Returns:
Dictionary containing all secrets
"""
print("📝 Enter your API keys and credentials")
print("=" * 50)
print("(Press Enter to skip optional fields)\n")
secrets_data = {}
# Gemini API Key
gemini_key = getpass.getpass("Gemini API Key: ").strip()
if gemini_key:
secrets_data['GEMINI_API_KEY'] = gemini_key
# MongoDB URI
mongo_uri = getpass.getpass("MongoDB URI (optional): ").strip()
if mongo_uri:
secrets_data['MONGO_URI'] = mongo_uri
# Twilio SID
twilio_sid = getpass.getpass("Twilio Account SID (optional): ").strip()
if twilio_sid:
secrets_data['TWILIO_SID'] = twilio_sid
# Twilio Auth Token
twilio_token = getpass.getpass("Twilio Auth Token (optional): ").strip()
if twilio_token:
secrets_data['TWILIO_TOKEN'] = twilio_token
# Generate signing secret automatically
print("\n🔑 Generating signing secret...")
secrets_data['SIGNING_SECRET'] = generate_signing_secret()
print("✅ Signing secret generated (256-bit)")
return secrets_data
def main():
"""
Main CLI workflow for encrypting secrets.
"""
try:
# Check if secrets.enc already exists
output_file = "secrets.enc"
if os.path.exists(output_file):
print(f"\n⚠️ Warning: {output_file} already exists!")
response = input("Overwrite? (yes/no): ").strip().lower()
if response not in ['yes', 'y']:
print("❌ Operation cancelled.")
sys.exit(0)
print()
# Step 1: Get passphrase
passphrase = prompt_passphrase()
# Step 2: Collect secrets
secrets_data = prompt_secrets()
if not secrets_data:
print("\n❌ No secrets provided. Exiting.")
sys.exit(1)
# Step 3: Encrypt and save
print(f"\n🔒 Encrypting secrets to {output_file}...")
try:
save_encrypted(secrets_data, output_file, passphrase)
print(f"✅ Secrets encrypted successfully!")
except Exception as e:
print(f"❌ Encryption failed: {e}")
sys.exit(1)
# Step 4: Display summary
print("\n" + "=" * 50)
print("📦 Encrypted Secrets Summary")
print("=" * 50)
secret_keys = list(secrets_data.keys())
for key in secret_keys:
if key == 'SIGNING_SECRET':
print(f" ✓ {key} (auto-generated)")
else:
print(f" ✓ {key}")
print(f"\n📁 File: {output_file}")
print(f"🔐 Encryption: AES-256-GCM with scrypt key derivation")
# Step 5: Usage instructions
print("\n" + "=" * 50)
print("📖 How to Load Secrets")
print("=" * 50)
print("\n1️⃣ In Python code:")
print(" from crypto_simple import load_encrypted")
print(f" secrets = load_encrypted('{output_file}', passphrase)")
print(" api_key = secrets['GEMINI_API_KEY']")
print("\n2️⃣ In Streamlit app:")
print(" - Go to the '🔐 Security' tab")
print(" - Click 'Load Secrets'")
print(" - Enter your passphrase")
print(" - Secrets will be loaded into session state")
print("\n3️⃣ Security reminders:")
print(" ⚠️ Never commit secrets.enc to git (already in .gitignore)")
print(" ⚠️ Store your passphrase securely (password manager)")
print(" ⚠️ Backup secrets.enc in a secure location")
print("\n✅ Setup complete!\n")
except KeyboardInterrupt:
print("\n\n❌ Operation cancelled by user.")
sys.exit(1)
except Exception as e:
print(f"\n❌ Unexpected error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()