Skip to content

Commit 40d8781

Browse files
committed
docs: add demo script with usage examples
- Demonstrates all random value generation functions - Shows entropy health monitoring - Includes password and token generator examples
1 parent 86dd42c commit 40d8781

1 file changed

Lines changed: 170 additions & 0 deletions

File tree

examples/demo.py

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
#!/usr/bin/env python3
2+
# =============================================================================
3+
# TrueEntropy - Example Usage
4+
# =============================================================================
5+
#
6+
# This script demonstrates the main features of the TrueEntropy library.
7+
# Run it to see true random numbers generated from real-world entropy sources.
8+
#
9+
# =============================================================================
10+
11+
"""
12+
Example script demonstrating TrueEntropy usage.
13+
14+
This script shows how to:
15+
1. Generate various types of random values
16+
2. Check entropy pool health
17+
3. Use the background collector
18+
4. Feed custom entropy
19+
"""
20+
21+
import trueentropy
22+
23+
24+
def main() -> None:
25+
"""Run the TrueEntropy demonstration."""
26+
27+
print("=" * 60)
28+
print(" TrueEntropy - True Randomness from the Real World")
29+
print("=" * 60)
30+
print()
31+
32+
# -------------------------------------------------------------------------
33+
# Basic Random Value Generation
34+
# -------------------------------------------------------------------------
35+
36+
print("[*] Basic Random Values")
37+
print("-" * 40)
38+
39+
# Random float between 0 and 1
40+
random_float = trueentropy.random()
41+
print(f" Random float [0, 1): {random_float:.10f}")
42+
43+
# Random integer in a range
44+
random_int = trueentropy.randint(1, 100)
45+
print(f" Random int [1, 100]: {random_int}")
46+
47+
# Random boolean (coin flip)
48+
coin_flip = trueentropy.randbool()
49+
print(f" Coin flip: {'Heads' if coin_flip else 'Tails'}")
50+
51+
# Random bytes
52+
random_bytes = trueentropy.randbytes(16)
53+
print(f" Random 16 bytes: {random_bytes.hex()}")
54+
55+
print()
56+
57+
# -------------------------------------------------------------------------
58+
# Sequence Operations
59+
# -------------------------------------------------------------------------
60+
61+
print("[*] Sequence Operations")
62+
print("-" * 40)
63+
64+
# Random choice from a list
65+
colors = ["Red", "Green", "Blue", "Yellow", "Purple"]
66+
chosen_color = trueentropy.choice(colors)
67+
print(f" Random color: {chosen_color}")
68+
69+
# Shuffle a list
70+
cards = ["A", "K", "Q", "J", "10"]
71+
print(f" Original cards: {cards}")
72+
trueentropy.shuffle(cards)
73+
print(f" Shuffled cards: {cards}")
74+
75+
# Sample without replacement
76+
lottery_numbers = trueentropy.sample(range(1, 50), 6)
77+
lottery_numbers.sort()
78+
print(f" Lottery (6 from 49): {lottery_numbers}")
79+
80+
print()
81+
82+
# -------------------------------------------------------------------------
83+
# Dice Rolling Demonstration
84+
# -------------------------------------------------------------------------
85+
86+
print("[*] Dice Rolling (100 rolls)")
87+
print("-" * 40)
88+
89+
# Roll a 6-sided die 100 times
90+
rolls = [trueentropy.randint(1, 6) for _ in range(100)]
91+
92+
# Count occurrences
93+
from collections import Counter
94+
counts = Counter(rolls)
95+
96+
for face in range(1, 7):
97+
bar = "#" * (counts[face] // 2)
98+
print(f" Face {face}: {counts[face]:2d} {bar}")
99+
100+
print()
101+
102+
# -------------------------------------------------------------------------
103+
# Entropy Health Check
104+
# -------------------------------------------------------------------------
105+
106+
print("[*] Entropy Pool Health")
107+
print("-" * 40)
108+
109+
health = trueentropy.health()
110+
111+
# Create visual health bar
112+
filled = health["score"] // 10
113+
bar = "#" * filled + "." * (10 - filled)
114+
115+
status_symbol = {
116+
"healthy": "[OK]",
117+
"degraded": "[WARN]",
118+
"critical": "[CRIT]"
119+
}
120+
121+
print(f" Score: [{bar}] {health['score']}/100")
122+
print(f" Status: {status_symbol.get(health['status'], '?')} {health['status'].upper()}")
123+
print(f" Entropy bits: {health['entropy_bits']}")
124+
print(f" Pool usage: {health['pool_utilization']:.1f}%")
125+
print()
126+
print(f" Tip: {health['recommendation']}")
127+
128+
print()
129+
130+
# -------------------------------------------------------------------------
131+
# Password Generator Example
132+
# -------------------------------------------------------------------------
133+
134+
print("[*] Password Generator")
135+
print("-" * 40)
136+
137+
# Generate a strong random password
138+
import string
139+
alphabet = string.ascii_letters + string.digits + "!@#$%^&*"
140+
password = "".join(trueentropy.choice(alphabet) for _ in range(16))
141+
print(f" Random password: {password}")
142+
143+
# Generate a passphrase
144+
words = ["apple", "banana", "cherry", "dragon", "eagle", "falcon",
145+
"garden", "harbor", "island", "jungle", "kingdom", "lemon"]
146+
passphrase = "-".join(trueentropy.sample(words, 4))
147+
print(f" Passphrase: {passphrase}")
148+
149+
print()
150+
151+
# -------------------------------------------------------------------------
152+
# UUID-like Token Generator
153+
# -------------------------------------------------------------------------
154+
155+
print("[*] Token Generator")
156+
print("-" * 40)
157+
158+
token = trueentropy.randbytes(16).hex()
159+
formatted = f"{token[:8]}-{token[8:12]}-{token[12:16]}-{token[16:20]}-{token[20:]}"
160+
print(f" Random token: {formatted}")
161+
162+
print()
163+
print("=" * 60)
164+
print(" All random values above were generated from real-world")
165+
print(" entropy sources: CPU timing, network latency, and more!")
166+
print("=" * 60)
167+
168+
169+
if __name__ == "__main__":
170+
main()

0 commit comments

Comments
 (0)