From d1874763be18d2e04b3e8d0b75df0df746080206 Mon Sep 17 00:00:00 2001 From: "pixeebot[bot]" <104101892+pixeebot[bot]@users.noreply.github.com> Date: Sun, 23 Feb 2025 03:28:33 +0000 Subject: [PATCH] Secure Source of Randomness --- .../03_generators/generators.py | 6 ++-- .../10_Modules/09_random/01_random_numbers.py | 28 +++++++++---------- .../10_Modules/09_random/02_random_numbers.py | 22 +++++++-------- .../10_Modules/09_random/03_tossing_coin.py | 4 +-- .../09_random/04_random_name_generator.py | 10 +++---- python3/10_Modules/09_random/05_cards_game.py | 4 +-- .../09_random/06_password_generator.py | 16 +++++------ .../09_random/07_password_generator.py | 12 ++++---- .../09_random/08_random_gaussion_numbers.py | 4 +-- python3/10_Modules/09_random/cipherwheel.py | 4 +-- .../13_console_coloring/coloroma_ex3.py | 4 +-- .../10_Modules/15_turtle_module/08_spirals.py | 8 +++--- .../15_turtle_module/12_christmas_tree.py | 10 +++---- .../15_turtle_module/13_user_input_pattern.py | 4 +-- .../10_Modules/15_turtle_module/circlefill.py | 6 ++-- python3/10_Modules/15_turtle_module/new2.py | 12 ++++---- .../10_Modules/15_turtle_module/polysub.py | 10 +++---- .../15_turtle_module/turtleGraphics.py | 7 ++--- .../23_faker/e_psedoradom_fake_data.py | 6 ++-- python3/10_Modules/24_Tkinter/jitterplot.py | 6 ++-- .../28_MiscellaneousModules/memcach_ex.py | 5 ++-- python3/13_OOP/Practical/Execution_Time.py | 5 ++-- .../13_OOP/e_DataClasses/04_data_classes.py | 4 +-- python3/13_OOP/f_Advanced/04_shapes2.py | 8 ++---- .../09_autopy_module/move_cursor.py | 4 +-- .../c_number_guessing_game/server.py | 6 ++-- .../g_app_with_orm/tests/locustfile.py | 10 +++---- .../d_using_flask/e_webapps/QuizApp/a.py | 6 ++-- .../d_using_flask/e_webapps/QuizApp/c.py | 6 ++-- .../d_using_flask/e_webapps/QuizApp/d.py | 6 ++-- .../b_OpenTelemetry/d_OpenTelemetry.py | 5 ++-- .../petition_fake_data_generator.py | 4 +-- .../a_random_password_generator.py | 4 +-- .../a_function_based/a2_worker_threads.py | 4 +-- .../a_function_based/f_thread_local_data.py | 4 +-- .../a_function_based/f_thread_local_data2.py | 4 +-- .../i2_get_thread_return_val.py | 4 +-- .../b_class_based/a_writing_thread.py | 6 ++-- .../b_class_based/c_worker_thread_subclass.py | 4 +-- .../c_locks/b4_locks_access_to_resources.py | 4 +-- .../d_conditions/a_condition.py | 9 +++--- .../d_semaphores/a_semaphores.py | 11 ++++---- .../01_MultiThreading/e_events/a_event.py | 7 ++--- .../g_barriers/a_barriers.py | 5 ++-- .../01_MultiThreading/threading/Ch9.py | 4 +-- .../multi_threading_ex1.py | 4 +-- .../02_multiprocessing/b_process_pool.py | 4 +-- .../02_multiprocessing/c_worker_processes.py | 4 +-- .../d_worker_process_subclass.py | 4 +-- .../multiprocessing_queue.py | 4 +-- .../02_multiprocessing/mutiprocessing_pool.py | 4 +-- .../mutiprocessing_queue.py | 4 +-- .../03_asyncio_module/h_asyncio_wait.py | 4 +-- .../j_asyncio_as_completed.py | 4 +-- .../03_asyncio_module/n_asyncio_ex.py | 4 +-- 55 files changed, 175 insertions(+), 187 deletions(-) diff --git a/python3/09_Iterators_generators_coroutines/03_generators/generators.py b/python3/09_Iterators_generators_coroutines/03_generators/generators.py index fa260c1c..9dde816d 100644 --- a/python3/09_Iterators_generators_coroutines/03_generators/generators.py +++ b/python3/09_Iterators_generators_coroutines/03_generators/generators.py @@ -1,5 +1,5 @@ import itertools as it -import random +import secrets def squares(start, end): @@ -221,7 +221,7 @@ def tabu_generator(n, len_, recent=None): recent = n // 2 tabu = [] while len_ > 0: - v = random.randint(0, n - 1) + v = secrets.SystemRandom().randint(0, n - 1) if v not in tabu: yield v tabu.append(v) @@ -233,7 +233,7 @@ def tabu_generator(n, len_, recent=None): # Count how many permutations occur for different values of recent. for recent in range(0, 6): - itemgen = (random.randint(0, 7) for i in tabu_generator(8, 10**5, recent)) + itemgen = (secrets.SystemRandom().randint(0, 7) for i in tabu_generator(8, 10**5, recent)) total = 0 for _ in unique_permutations(itemgen, 8): total += 1 diff --git a/python3/10_Modules/09_random/01_random_numbers.py b/python3/10_Modules/09_random/01_random_numbers.py index 5385d6c6..51dea8bb 100644 --- a/python3/10_Modules/09_random/01_random_numbers.py +++ b/python3/10_Modules/09_random/01_random_numbers.py @@ -1,7 +1,7 @@ #!/usr/bin/python # -*- coding: utf-8 -*- import os -import random +import secrets """ Purpose: Demonstration of random module @@ -15,28 +15,28 @@ In Python3, 'secret' module is used for cryptographic purpose. """ # Generate a pseudo-random number between 0 and 1. -print("random.random() :", random.random()) +print("random.random() :", secrets.SystemRandom().random()) # Generate a large pseudo-random number -print("random.random() * 100:", random.random() * 100) -print("random.random() * 100:", random.random() * 100) +print("random.random() * 100:", secrets.SystemRandom().random() * 100) +print("random.random() * 100:", secrets.SystemRandom().random() * 100) # if we set the seed, we guarantee that we will get the same answer -random.seed(18485) +secrets.SystemRandom().seed(18485) # NOTE: only supported seed types are: None,int, float, str, bytes, and bytearray. -print(random.random()) # should give 0.6797936184081204 -print(random.random()) # should give 0.9122712611873796 -print(random.random()) # should give 0.12926723301605425 +print(secrets.SystemRandom().random()) # should give 0.6797936184081204 +print(secrets.SystemRandom().random()) # should give 0.9122712611873796 +print(secrets.SystemRandom().random()) # should give 0.12926723301605425 -random.seed("slartibartfast") -s = [random.random() for i in range(3)] +secrets.SystemRandom().seed("slartibartfast") +s = [secrets.SystemRandom().random() for i in range(3)] print(s) # should give [0.7725766895236029, 0.850635131875668, 0.11481894112205038] print() print("os.urandom(1024)", os.urandom(1024)) -random.seed(os.urandom(1024)) +secrets.SystemRandom().seed(os.urandom(1024)) -print(random.random()) # should give 0.7819713562511514 -print(random.random()) # should give 0.4669615948613485 -print(random.random()) # should give 0.6987920562874854 +print(secrets.SystemRandom().random()) # should give 0.7819713562511514 +print(secrets.SystemRandom().random()) # should give 0.4669615948613485 +print(secrets.SystemRandom().random()) # should give 0.6987920562874854 diff --git a/python3/10_Modules/09_random/02_random_numbers.py b/python3/10_Modules/09_random/02_random_numbers.py index bacb9d50..77b29c30 100644 --- a/python3/10_Modules/09_random/02_random_numbers.py +++ b/python3/10_Modules/09_random/02_random_numbers.py @@ -1,4 +1,4 @@ -import random +import secrets """ Purpose: demonstration of random module @@ -7,40 +7,40 @@ called the Mersenne Twister. """ # Pick a random number between 1 and 100. -print(random.randint(1, 100)) # 75 +print(secrets.SystemRandom().randint(1, 100)) # 75 # randint also includes the upper bound value # Pick a random floating point number between 1 and 10 # random.uniform(a,b) => a <= N <= b -print(random.uniform(1, 10)) +print(secrets.SystemRandom().uniform(1, 10)) # Generate a randomly selected element from range(start, stop, step) # random.randrange(start, stop[, step]) for i in range(3): - print(random.randrange(0, 101, 5)) + print(secrets.SystemRandom().randrange(0, 101, 5)) items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Pick a random item from the list -x = random.sample(items, 1) +x = secrets.SystemRandom().sample(items, 1) print(x) # Pick 4 random items from the list -y = random.sample(items, 4) +y = secrets.SystemRandom().sample(items, 4) print(y) mountains = ["Andes", "Himalayas", "Alphes", "Aplachein", "Ural", "Vindhya"] # Pick a random item from the list -x = random.sample(mountains, 1) +x = secrets.SystemRandom().sample(mountains, 1) print(x[0]) # Pick 3 random items from the list -y = random.sample(mountains, 3) +y = secrets.SystemRandom().sample(mountains, 3) print(y) # Pick a random item from the list -x = random.choice(mountains) +x = secrets.choice(mountains) print(x) print() @@ -49,7 +49,7 @@ def shuffler(mylist): new_list = [] while len(mylist): - rand_pos = random.randint(0, len(mylist)) + rand_pos = secrets.SystemRandom().randint(0, len(mylist)) new_list.append(mylist[rand_pos]) del mylist[rand_pos] return new_list @@ -58,5 +58,5 @@ def shuffler(mylist): print(shuffler(["a", "b", "c", "d", "e"])) numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -random.shuffle(numbers) +secrets.SystemRandom().shuffle(numbers) print("after shuffle", numbers) diff --git a/python3/10_Modules/09_random/03_tossing_coin.py b/python3/10_Modules/09_random/03_tossing_coin.py index 91a13309..e0b81e24 100644 --- a/python3/10_Modules/09_random/03_tossing_coin.py +++ b/python3/10_Modules/09_random/03_tossing_coin.py @@ -1,5 +1,5 @@ # coin -- head/tail -import random +import secrets outcomes = { "heads": 0, @@ -9,7 +9,7 @@ for i in range(10000): - outcome = random.choice(sides) + outcome = secrets.choice(sides) outcomes[outcome] += 1 print("In 10000 tosses,") diff --git a/python3/10_Modules/09_random/04_random_name_generator.py b/python3/10_Modules/09_random/04_random_name_generator.py index 23faa632..a65b684e 100644 --- a/python3/10_Modules/09_random/04_random_name_generator.py +++ b/python3/10_Modules/09_random/04_random_name_generator.py @@ -1,11 +1,11 @@ -import random +import secrets def random_name_generator(first, second, count): _names = [] for _ in range(count): - fst_name = random.choice(first) - lst_name = random.choice(second) + fst_name = secrets.choice(first) + lst_name = secrets.choice(second) name = f"{fst_name} {lst_name}" _names.append(name) return _names @@ -14,8 +14,8 @@ def random_name_generator(first, second, count): def random_name_generator(first, second, count): _names = set() while len(_names) < count: - fst_name = random.choice(first) - lst_name = random.choice(second) + fst_name = secrets.choice(first) + lst_name = secrets.choice(second) name = f"{fst_name} {lst_name}" _names.add(name) return _names diff --git a/python3/10_Modules/09_random/05_cards_game.py b/python3/10_Modules/09_random/05_cards_game.py index de01a9ab..d1d9851d 100644 --- a/python3/10_Modules/09_random/05_cards_game.py +++ b/python3/10_Modules/09_random/05_cards_game.py @@ -2,7 +2,7 @@ ## A deck of cards has 13 cards each of 4 suits: heart(♥), spade(♠), diamond(♦), club(♣). ## THOUGHT PROCESS: Construct an unshuffled deck by using two lists, one for suits, another for cardValues -> Shuffle the deck by iterating over all cards one by one using their indexes, and swapping the index with any random index. -import random +import secrets suits = ["♠", "♥", "♦", "♣"] cardValues = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"] @@ -21,7 +21,7 @@ # SHUFFLING CARDS: iterating over all cards one by one using their indexes, swapping the index with any random index # Iterate over all cards one by one using their indexes for index in range(0, len(deck)): - randomCardForSwitching = random.randrange(len(deck)) + randomCardForSwitching = secrets.SystemRandom().randrange(len(deck)) # Swapping indexes temporaryIndex = deck[index] deck[index] = deck[randomCardForSwitching] diff --git a/python3/10_Modules/09_random/06_password_generator.py b/python3/10_Modules/09_random/06_password_generator.py index 7c9dd2b5..be0050f6 100644 --- a/python3/10_Modules/09_random/06_password_generator.py +++ b/python3/10_Modules/09_random/06_password_generator.py @@ -1,29 +1,29 @@ -import random +import secrets alphabet = "abcdefghijklmnopqrstuvwxyz .,!@_-(*)-+/|$%&=?^" pw_length = 34 # can change the length of your password by changing this number -mypw = "".join(random.sample(alphabet, pw_length)) +mypw = "".join(secrets.SystemRandom().sample(alphabet, pw_length)) print(mypw) print() mypw = "" for i in range(pw_length): - next_index = random.randrange(len(alphabet)) + next_index = secrets.SystemRandom().randrange(len(alphabet)) mypw += alphabet[next_index] print(mypw) print() # replace 1 or 2 characters with a number -for i in range(random.randrange(1, 3)): - replace_index = random.randrange(len(mypw) // 2) - mypw = mypw[0:replace_index] + str(random.randrange(10)) + mypw[replace_index + 1 :] +for i in range(secrets.SystemRandom().randrange(1, 3)): + replace_index = secrets.SystemRandom().randrange(len(mypw) // 2) + mypw = mypw[0:replace_index] + str(secrets.SystemRandom().randrange(10)) + mypw[replace_index + 1 :] # replace 1 or 2 letters with an uppercase letter -for i in range(random.randrange(1, 3)): - replace_index = random.randrange(len(mypw) // 2, len(mypw)) +for i in range(secrets.SystemRandom().randrange(1, 3)): + replace_index = secrets.SystemRandom().randrange(len(mypw) // 2, len(mypw)) mypw = ( mypw[0:replace_index] + mypw[replace_index].upper() + mypw[replace_index + 1 :] ) diff --git a/python3/10_Modules/09_random/07_password_generator.py b/python3/10_Modules/09_random/07_password_generator.py index 155b9751..531634bc 100644 --- a/python3/10_Modules/09_random/07_password_generator.py +++ b/python3/10_Modules/09_random/07_password_generator.py @@ -1,20 +1,20 @@ import string -from random import choice, randint, randrange, sample +import secrets print("string.ascii_letters :", string.ascii_letters) print("string.digits :", string.digits) print("string.punctuation :", string.punctuation) characters = string.ascii_letters + string.punctuation + string.digits -password1 = "".join(choice(characters) for x in range(randint(8, 16))) +password1 = "".join(secrets.choice(characters) for x in range(secrets.SystemRandom().randint(8, 16))) print("password1 :", password1) -password2 = "".join(choice(characters) for x in range(randrange(8, 16))) +password2 = "".join(secrets.choice(characters) for x in range(secrets.SystemRandom().randrange(8, 16))) print("password2 :", password2) print( - "".join(sample(string.ascii_letters, 4)) - + "".join(sample(string.digits, 4)) - + "".join(sample(string.punctuation, 4)) + "".join(secrets.SystemRandom().sample(string.ascii_letters, 4)) + + "".join(secrets.SystemRandom().sample(string.digits, 4)) + + "".join(secrets.SystemRandom().sample(string.punctuation, 4)) ) diff --git a/python3/10_Modules/09_random/08_random_gaussion_numbers.py b/python3/10_Modules/09_random/08_random_gaussion_numbers.py index afebc862..febe8009 100644 --- a/python3/10_Modules/09_random/08_random_gaussion_numbers.py +++ b/python3/10_Modules/09_random/08_random_gaussion_numbers.py @@ -1,11 +1,11 @@ -import random +import secrets histogram = [0] * 20 # calculate histogram for gaussian # noise, using average=5, stddev=1 for i in range(1000): - i = int(random.gauss(5, 1) * 2) + i = int(secrets.SystemRandom().gauss(5, 1) * 2) histogram[i] = histogram[i] + 1 # print the histogram diff --git a/python3/10_Modules/09_random/cipherwheel.py b/python3/10_Modules/09_random/cipherwheel.py index 33986ff2..7872160a 100644 --- a/python3/10_Modules/09_random/cipherwheel.py +++ b/python3/10_Modules/09_random/cipherwheel.py @@ -1,6 +1,6 @@ # cipherwheel.py import string -from random import randrange +import secrets # functions for encryption and decryption @@ -11,7 +11,7 @@ def encrypt(m): outer_wheel = inner_wheel # calculate random secret key while True: - key = randrange(26) + key = secrets.SystemRandom().randrange(26) if key != 0: break cipher_dict = {} diff --git a/python3/10_Modules/13_console_coloring/coloroma_ex3.py b/python3/10_Modules/13_console_coloring/coloroma_ex3.py index 89252c95..a5af6e51 100644 --- a/python3/10_Modules/13_console_coloring/coloroma_ex3.py +++ b/python3/10_Modules/13_console_coloring/coloroma_ex3.py @@ -1,11 +1,11 @@ #!/usr/bin/env python import os -import random import sys import time from colorama import * +import secrets width, height = 80, 24 colors = [ @@ -33,7 +33,7 @@ def main(): position = middle_x - string_center while True: - color_seed = random.randint(0, len(colors)) + color_seed = secrets.SystemRandom().randint(0, len(colors)) color = colors[color_seed] print((pos(position, middle_y) + color + string)) time.sleep(1000) diff --git a/python3/10_Modules/15_turtle_module/08_spirals.py b/python3/10_Modules/15_turtle_module/08_spirals.py index 28142793..79c14b0d 100644 --- a/python3/10_Modules/15_turtle_module/08_spirals.py +++ b/python3/10_Modules/15_turtle_module/08_spirals.py @@ -1,16 +1,16 @@ #!/usr/bin/python -from random import randint from turtle import bgcolor, colormode, exitonclick, fd, pencolor, rt, speed +import secrets bgcolor("black") x = 1 speed(0) while x < 400: - r = randint(0, 255) - g = randint(0, 255) - b = randint(0, 255) + r = secrets.SystemRandom().randint(0, 255) + g = secrets.SystemRandom().randint(0, 255) + b = secrets.SystemRandom().randint(0, 255) colormode(255) pencolor(r, g, b) diff --git a/python3/10_Modules/15_turtle_module/12_christmas_tree.py b/python3/10_Modules/15_turtle_module/12_christmas_tree.py index 99a500d2..ff897bec 100644 --- a/python3/10_Modules/15_turtle_module/12_christmas_tree.py +++ b/python3/10_Modules/15_turtle_module/12_christmas_tree.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from random import randint from turtle import * +import secrets def create_rectangle(turtle, color, x, y, width, height): @@ -88,12 +88,12 @@ def create_circle(turtle, x, y, radius, color): # now add few stars in sky oogway.speed(10) -number_of_stars = randint(20, 30) +number_of_stars = secrets.SystemRandom().randint(20, 30) # print(number_of_stars) for _ in range(0, number_of_stars): - x_star = randint(-(screen.window_width() // 2), screen.window_width() // 2) - y_star = randint(tree_height, screen.window_height() // 2) - size = randint(5, 20) + x_star = secrets.SystemRandom().randint(-(screen.window_width() // 2), screen.window_width() // 2) + y_star = secrets.SystemRandom().randint(tree_height, screen.window_height() // 2) + size = secrets.SystemRandom().randint(5, 20) oogway.penup() oogway.color("white") oogway.goto(x_star, y_star) diff --git a/python3/10_Modules/15_turtle_module/13_user_input_pattern.py b/python3/10_Modules/15_turtle_module/13_user_input_pattern.py index f7d06d24..395af384 100644 --- a/python3/10_Modules/15_turtle_module/13_user_input_pattern.py +++ b/python3/10_Modules/15_turtle_module/13_user_input_pattern.py @@ -2,9 +2,9 @@ """ Purpose: User Input Pattern - Outside_In """ -import random import time import turtle +import secrets print("This program draws shapes based on the number you enter in a uniform pattern.") num_str = input("Enter the side number of the shape you want to draw: ") @@ -21,7 +21,7 @@ numshapes = 8 for x in range(numshapes): - turtle.color(random.random(), random.random(), random.random()) + turtle.color(secrets.SystemRandom().random(), secrets.SystemRandom().random(), secrets.SystemRandom().random()) x += 5 y += 5 turtle.forward(x) diff --git a/python3/10_Modules/15_turtle_module/circlefill.py b/python3/10_Modules/15_turtle_module/circlefill.py index cbef5829..08aa7337 100644 --- a/python3/10_Modules/15_turtle_module/circlefill.py +++ b/python3/10_Modules/15_turtle_module/circlefill.py @@ -1,8 +1,8 @@ # after http://paulbourke.net/texture_colour/randomtile/ -import random import turtle from math import sqrt +import secrets def dist(p1, p2): @@ -13,7 +13,7 @@ def circlefill(n): result = [] s = 400 while n > 0: - cp = (random.uniform(-s, s), random.uniform(-s, s)) + cp = (secrets.SystemRandom().uniform(-s, s), secrets.SystemRandom().uniform(-s, s)) rad = min(s / 10, s - cp[0], cp[0] + s, s - cp[1], cp[1] + s) for c in result: rad = min(rad, dist(c[0], cp) - c[1]) @@ -37,7 +37,7 @@ def render(circs): turtle.setheading(90) turtle.pendown() turtle.fillcolor( - random.randint(0, 255), random.randint(0, 255), random.randint(0, 255) + secrets.SystemRandom().randint(0, 255), secrets.SystemRandom().randint(0, 255), secrets.SystemRandom().randint(0, 255) ) turtle.begin_fill() turtle.circle(c[1]) diff --git a/python3/10_Modules/15_turtle_module/new2.py b/python3/10_Modules/15_turtle_module/new2.py index fc756e7c..8be9f375 100644 --- a/python3/10_Modules/15_turtle_module/new2.py +++ b/python3/10_Modules/15_turtle_module/new2.py @@ -1,11 +1,11 @@ import turtle as tt -from random import randint, sample +import secrets def draw(): - size = randint(40, 300) + size = secrets.SystemRandom().randint(40, 300) angles = (144, 150, 157.5, 160, 165) - angle = sample(angles, 1)[0] + angle = secrets.SystemRandom().sample(angles, 1)[0] colors = [ ("#922B21", "#E6B0AA"), @@ -17,11 +17,11 @@ def draw(): ("#F39C12", "#FDEBD0"), ("#BA4A00", "#F6DDCC"), ] - color = sample(colors, 1)[0] + color = secrets.SystemRandom().sample(colors, 1)[0] tt.color(color[0], color[1]) - x_pos = randint(-200, 200) - y_pos = randint(-200, 200) + x_pos = secrets.SystemRandom().randint(-200, 200) + y_pos = secrets.SystemRandom().randint(-200, 200) tt.pu() tt.setpos(x_pos, y_pos) start_position = tt.pos() diff --git a/python3/10_Modules/15_turtle_module/polysub.py b/python3/10_Modules/15_turtle_module/polysub.py index f2dee6cd..5eaeefbe 100644 --- a/python3/10_Modules/15_turtle_module/polysub.py +++ b/python3/10_Modules/15_turtle_module/polysub.py @@ -1,5 +1,5 @@ -import random import turtle +import secrets def interp(p1, p2, t): @@ -19,13 +19,13 @@ def subdivide(pts, depth): else: l1 = dist(pts[0], pts[1]) l2 = dist(pts[1], pts[2]) - r = random.uniform(0, l1 + l2) + r = secrets.SystemRandom().uniform(0, l1 + l2) if r < l1: i = 0 else: i = 1 - t1 = random.uniform(0.5 - width, 0.5 + width) - t2 = random.uniform(0.5 - width, 0.5 + width) + t1 = secrets.SystemRandom().uniform(0.5 - width, 0.5 + width) + t2 = secrets.SystemRandom().uniform(0.5 - width, 0.5 + width) pa = interp(pts[i], pts[i + 1], t1) pb = interp(pts[i + 2], pts[(i + 3) % 4], t2) subdivide((pts[i], pa, pb, pts[(i + 3) % 4]), depth - 1) @@ -45,7 +45,7 @@ def render(polys): turtle.goto(pts[3]) turtle.begin_fill() turtle.fillcolor( - random.randint(64, 192), random.randint(64, 192), random.randint(64, 192) + secrets.SystemRandom().randint(64, 192), secrets.SystemRandom().randint(64, 192), secrets.SystemRandom().randint(64, 192) ) turtle.pendown() for pt in pts: diff --git a/python3/10_Modules/15_turtle_module/turtleGraphics.py b/python3/10_Modules/15_turtle_module/turtleGraphics.py index bb1b8d95..a1064485 100644 --- a/python3/10_Modules/15_turtle_module/turtleGraphics.py +++ b/python3/10_Modules/15_turtle_module/turtleGraphics.py @@ -1,9 +1,8 @@ """ "Turtle Graphics """ - -import random import turtle +import secrets turtle.screensize(900, 900) c = (0.1, 0.01, 0.3) @@ -37,7 +36,7 @@ def fractal(a, length, size, angle, t): if size < 2: tup = (1 - t, 1 - t, 1 - t) tup2 = (1 - t, 1 - t, 1 - t) - k = random.randint(1, 100) + k = secrets.SystemRandom().randint(1, 100) if k < 45: a.pencolor(tup2) elif k > 45 & k <= 75: @@ -52,7 +51,7 @@ def fractal(a, length, size, angle, t): a.speed(0) tup2 = (1 - t, t, 1 - t) a.begin_fill() - k = random.randint(1, 100) + k = secrets.SystemRandom().randint(1, 100) if k < 70: a.pencolor(tup2) else: diff --git a/python3/10_Modules/23_faker/e_psedoradom_fake_data.py b/python3/10_Modules/23_faker/e_psedoradom_fake_data.py index ae2a336c..c0619bba 100644 --- a/python3/10_Modules/23_faker/e_psedoradom_fake_data.py +++ b/python3/10_Modules/23_faker/e_psedoradom_fake_data.py @@ -1,10 +1,10 @@ -import random import pandas as pd from faker import Faker +import secrets Faker.seed(0) -random.seed(0) +secrets.SystemRandom().seed(0) fake = Faker("de_DE") name, city_name, country, job, age = [[] for k in range(0, 5)] @@ -13,7 +13,7 @@ city_name.append(fake.city_name()) country.append(fake.country()) job.append(fake.job()) - age.append(random.randint(20, 100)) + age.append(secrets.SystemRandom().randint(20, 100)) d = {"Name": name, "Age": age, "City": city_name, "Country": country, "Job": job} df = pd.DataFrame(d) diff --git a/python3/10_Modules/24_Tkinter/jitterplot.py b/python3/10_Modules/24_Tkinter/jitterplot.py index 5dd2fc6a..be2a7e15 100644 --- a/python3/10_Modules/24_Tkinter/jitterplot.py +++ b/python3/10_Modules/24_Tkinter/jitterplot.py @@ -2,8 +2,8 @@ # Fredrik Lundh import math -import random from tkinter import * +import secrets GREY = "grey" GREEN = "green" @@ -48,14 +48,14 @@ def jitterplot(canvas, bbox, data): # draw markers for y in map(lambda y, ys=ystep, yb=ybase: y * ys + yb, data): - j = x + (y1 - y0) * 0.1 * (random.random() - 0.5) + j = x + (y1 - y0) * 0.1 * (secrets.SystemRandom().random() - 0.5) canvas.create_oval(j - 2, y - 2, j + 2, y + 2, fill=WHITE) ################################################################ # create some random data -data = [random.random() for a in range(200)] +data = [secrets.SystemRandom().random() for a in range(200)] # create a drawing canvas diff --git a/python3/10_Modules/28_MiscellaneousModules/memcach_ex.py b/python3/10_Modules/28_MiscellaneousModules/memcach_ex.py index 78e21778..be9ba134 100644 --- a/python3/10_Modules/28_MiscellaneousModules/memcach_ex.py +++ b/python3/10_Modules/28_MiscellaneousModules/memcach_ex.py @@ -4,12 +4,11 @@ pip install -U python-memcached --user """ - -import random import time import timeit import memcache +import secrets # starting the memcache client mc = memcache.Client(["127.0.0.1:11211"]) @@ -39,7 +38,7 @@ def compute_square(n): def make_request(): - compute_square(random.randint(0, 5000)) + compute_square(secrets.SystemRandom().randint(0, 5000)) print("Ten successive runs:") diff --git a/python3/13_OOP/Practical/Execution_Time.py b/python3/13_OOP/Practical/Execution_Time.py index d98df373..a7cd4aab 100644 --- a/python3/13_OOP/Practical/Execution_Time.py +++ b/python3/13_OOP/Practical/Execution_Time.py @@ -10,9 +10,8 @@ print 'Finished in {} seconds.'.format(timer.duration()) """ - -import random import time +import secrets class ExecutionTime: @@ -32,5 +31,5 @@ def duration(self): print(timer.start_time) sample_list = list() # [] -my_list = [random.randint(1, 888898) for num in range(1, 1000000) if num % 2 == 0] +my_list = [secrets.SystemRandom().randint(1, 888898) for num in range(1, 1000000) if num % 2 == 0] print("Finished in {} seconds.".format(timer.duration())) diff --git a/python3/13_OOP/e_DataClasses/04_data_classes.py b/python3/13_OOP/e_DataClasses/04_data_classes.py index 199615b7..d59d3e60 100644 --- a/python3/13_OOP/e_DataClasses/04_data_classes.py +++ b/python3/13_OOP/e_DataClasses/04_data_classes.py @@ -1,9 +1,9 @@ -import random from dataclasses import dataclass, field +import secrets def random_price(): - return random.randint(20, 100) + return secrets.SystemRandom().randint(20, 100) @dataclass diff --git a/python3/13_OOP/f_Advanced/04_shapes2.py b/python3/13_OOP/f_Advanced/04_shapes2.py index 5ef587bf..c5505979 100644 --- a/python3/13_OOP/f_Advanced/04_shapes2.py +++ b/python3/13_OOP/f_Advanced/04_shapes2.py @@ -10,6 +10,7 @@ """ from abc import ABC, abstractmethod +import secrets class Shape(ABC): @@ -102,11 +103,6 @@ def area(self): def perimeter(self): return self.other.perimeter() * self.scale - -# Demonstrate the previous classes in action. - -from random import randint - if __name__ == "__main__": # An abstract class cannot be instantiated. try: @@ -143,7 +139,7 @@ def perimeter(self): tmp1, tmp2 = c.name, c.area # Lambdas can be defined to take no parameters, thus behaving essentially as data. c.name = lambda: "Bob" - c.area = lambda: randint(1, 100) + c.area = lambda: secrets.SystemRandom().randint(1, 100) print(f"\nObject c is now: {c}") # Bob print(f"Object d is now: {d}") # behaves normally diff --git a/python3/14_Code_Quality/09_autopy_module/move_cursor.py b/python3/14_Code_Quality/09_autopy_module/move_cursor.py index dcf4a00e..f044a1c5 100644 --- a/python3/14_Code_Quality/09_autopy_module/move_cursor.py +++ b/python3/14_Code_Quality/09_autopy_module/move_cursor.py @@ -1,8 +1,8 @@ import math -import random import time import autopy +import secrets TWO_PI = math.pi * 2.0 @@ -18,7 +18,7 @@ def sine_mouse_wave(): for x in range(int(width)): y = round(height * math.sin((TWO_PI * x) / width) + height) autopy.mouse.move(float(x), float(y)) - time.sleep(random.uniform(0.001, 0.003)) + time.sleep(secrets.SystemRandom().uniform(0.001, 0.003)) sine_mouse_wave() diff --git a/python3/16_Web_Services/a_RPC/b_json_rpc/c_number_guessing_game/server.py b/python3/16_Web_Services/a_RPC/b_json_rpc/c_number_guessing_game/server.py index 110d2eb5..9af12506 100644 --- a/python3/16_Web_Services/a_RPC/b_json_rpc/c_number_guessing_game/server.py +++ b/python3/16_Web_Services/a_RPC/b_json_rpc/c_number_guessing_game/server.py @@ -1,10 +1,10 @@ import json -import random from http.server import BaseHTTPRequestHandler, HTTPServer +import secrets class NumberGuessingGame: def __init__(self): - self.target_number = random.randint(1, 100) + self.target_number = secrets.SystemRandom().randint(1, 100) self.guesses = 0 def guess(self, number): @@ -47,4 +47,4 @@ def run(server_class=HTTPServer, port=5000): httpd.serve_forever() if __name__ == "__main__": - run() \ No newline at end of file + run() diff --git a/python3/16_Web_Services/f_web_application/d_using_flask/c_APIs_with_db/g_app_with_orm/tests/locustfile.py b/python3/16_Web_Services/f_web_application/d_using_flask/c_APIs_with_db/g_app_with_orm/tests/locustfile.py index 6ace4f76..e8eaad16 100644 --- a/python3/16_Web_Services/f_web_application/d_using_flask/c_APIs_with_db/g_app_with_orm/tests/locustfile.py +++ b/python3/16_Web_Services/f_web_application/d_using_flask/c_APIs_with_db/g_app_with_orm/tests/locustfile.py @@ -1,7 +1,7 @@ import csv -import random from locust import HttpUser, between, task +import secrets # pip install locust @@ -20,7 +20,7 @@ def create_book(self): with open("books.csv", newline="") as csvfile: reader = csv.reader(csvfile) rows = list(reader) - title, author, description = random.choice(rows) + title, author, description = secrets.choice(rows) self.client.post( "/books", json={"title": title, "author": author, "description": description}, @@ -32,11 +32,11 @@ def get_books(self): @task(3) def update_book(self): - book_id = random.randint(1, 100) + book_id = secrets.SystemRandom().randint(1, 100) with open("books.csv", newline="") as csvfile: reader = csv.reader(csvfile) rows = list(reader) - title, author, description = random.choice(rows) + title, author, description = secrets.choice(rows) self.client.put( f"/books/{book_id}", json={"title": title, "author": author, "description": description}, @@ -44,7 +44,7 @@ def update_book(self): @task(4) def delete_book(self): - book_id = random.randint(1, 100) + book_id = secrets.SystemRandom().randint(1, 100) self.client.delete(f"/books/{book_id}") diff --git a/python3/16_Web_Services/f_web_application/d_using_flask/e_webapps/QuizApp/a.py b/python3/16_Web_Services/f_web_application/d_using_flask/e_webapps/QuizApp/a.py index e0e44a85..ac77cece 100644 --- a/python3/16_Web_Services/f_web_application/d_using_flask/e_webapps/QuizApp/a.py +++ b/python3/16_Web_Services/f_web_application/d_using_flask/e_webapps/QuizApp/a.py @@ -1,6 +1,6 @@ #!/usr/bin/python import copy -import random +import secrets original_questions = { # Format is 'question':[options] @@ -24,7 +24,7 @@ def shuffle(q): selected_keys = [] i = 0 while i < len(q): - current_selection = random.choice(q.keys()) + current_selection = secrets.choice(q.keys()) if current_selection not in selected_keys: selected_keys.append(current_selection) i += 1 @@ -35,7 +35,7 @@ def shuffle(q): for i in questions_shuffled: - random.shuffle(questions[i]) + secrets.SystemRandom().shuffle(questions[i]) print( f"""Where is {i} located? {questions[i]} diff --git a/python3/16_Web_Services/f_web_application/d_using_flask/e_webapps/QuizApp/c.py b/python3/16_Web_Services/f_web_application/d_using_flask/e_webapps/QuizApp/c.py index 06ee9044..c57bb927 100644 --- a/python3/16_Web_Services/f_web_application/d_using_flask/e_webapps/QuizApp/c.py +++ b/python3/16_Web_Services/f_web_application/d_using_flask/e_webapps/QuizApp/c.py @@ -1,7 +1,7 @@ import copy -import random from flask import Flask, render_template +import secrets app = Flask(__name__) @@ -27,7 +27,7 @@ def shuffle(q): selected_keys = [] i = 0 while i < len(q): - current_selection = random.choice(q.keys()) + current_selection = secrets.choice(q.keys()) if current_selection not in selected_keys: selected_keys.append(current_selection) i = i + 1 @@ -38,7 +38,7 @@ def shuffle(q): def quiz(): questions_shuffled = shuffle(questions) for i in questions.keys(): - random.shuffle(questions[i]) + secrets.SystemRandom().shuffle(questions[i]) return render_template("main.html", q=questions_shuffled, o=questions) diff --git a/python3/16_Web_Services/f_web_application/d_using_flask/e_webapps/QuizApp/d.py b/python3/16_Web_Services/f_web_application/d_using_flask/e_webapps/QuizApp/d.py index b52955f3..c7711458 100644 --- a/python3/16_Web_Services/f_web_application/d_using_flask/e_webapps/QuizApp/d.py +++ b/python3/16_Web_Services/f_web_application/d_using_flask/e_webapps/QuizApp/d.py @@ -1,7 +1,7 @@ import copy -import random from flask import Flask, render_template, request +import secrets app = Flask(__name__) @@ -27,7 +27,7 @@ def shuffle(q): selected_keys = [] i = 0 while i < len(q): - current_selection = random.choice(q.keys()) + current_selection = secrets.choice(q.keys()) if current_selection not in selected_keys: selected_keys.append(current_selection) i = i + 1 @@ -38,7 +38,7 @@ def shuffle(q): def quiz(): questions_shuffled = shuffle(questions) for i in questions.keys(): - random.shuffle(questions[i]) + secrets.SystemRandom().shuffle(questions[i]) return render_template("main.html", q=questions_shuffled, o=questions) diff --git a/python3/16_Web_Services/f_web_application/d_using_flask/i_telemetry_monitoring/b_OpenTelemetry/d_OpenTelemetry.py b/python3/16_Web_Services/f_web_application/d_using_flask/i_telemetry_monitoring/b_OpenTelemetry/d_OpenTelemetry.py index ad28f6d1..94be8919 100644 --- a/python3/16_Web_Services/f_web_application/d_using_flask/i_telemetry_monitoring/b_OpenTelemetry/d_OpenTelemetry.py +++ b/python3/16_Web_Services/f_web_application/d_using_flask/i_telemetry_monitoring/b_OpenTelemetry/d_OpenTelemetry.py @@ -8,13 +8,12 @@ """ -from random import randint - from flask import Flask, request from opentelemetry import trace from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter +import secrets provider = TracerProvider() processor = BatchSpanProcessor(ConsoleSpanExporter()) @@ -66,7 +65,7 @@ def roll_sum(sides, rolls): span = trace.get_current_span() sum = 0 for r in range(0, rolls): - result = randint(1, sides) + result = secrets.SystemRandom().randint(1, sides) span.add_event( "log", { diff --git a/python3/16_Web_Services/j_pyselenium/petition_fake_data_generator.py b/python3/16_Web_Services/j_pyselenium/petition_fake_data_generator.py index 4944ff26..ab545c4b 100644 --- a/python3/16_Web_Services/j_pyselenium/petition_fake_data_generator.py +++ b/python3/16_Web_Services/j_pyselenium/petition_fake_data_generator.py @@ -1,8 +1,8 @@ import csv -import random from faker import Faker from faker.providers import address +import secrets fake = Faker() fake.add_provider(address) @@ -43,7 +43,7 @@ def generate_postcode(country): # generate 10 records of dummy data data = [] for i in range(10): - country = random.choice(countries) + country = secrets.choice(countries) postcode = generate_postcode(country) record = { "first_name": fake.first_name(), diff --git a/python3/18_aws_cloud/a_AWS_Lambdas/d_practical_utility_functions/a_random_password_generator.py b/python3/18_aws_cloud/a_AWS_Lambdas/d_practical_utility_functions/a_random_password_generator.py index 0535746a..343f574b 100644 --- a/python3/18_aws_cloud/a_AWS_Lambdas/d_practical_utility_functions/a_random_password_generator.py +++ b/python3/18_aws_cloud/a_AWS_Lambdas/d_practical_utility_functions/a_random_password_generator.py @@ -1,10 +1,10 @@ -import random import string +import secrets def lambda_handler(event, context): length = int(event.get("password_length", 8)) - password = "".join(random.choices(string.ascii_letters + string.digits, k=length)) + password = "".join(secrets.SystemRandom().choices(string.ascii_letters + string.digits, k=length)) return {"statusCode": 200, "body": password} diff --git a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/a2_worker_threads.py b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/a2_worker_threads.py index 4c08d967..3c151bfc 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/a2_worker_threads.py +++ b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/a2_worker_threads.py @@ -1,11 +1,11 @@ -import random import threading import time +import secrets def worker(name: str) -> None: print(f"Started worker {name}") - worker_time = random.choice(range(1, 5)) + worker_time = secrets.choice(range(1, 5)) time.sleep(worker_time) print(f"{name} worker finished in {worker_time} seconds") diff --git a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/f_thread_local_data.py b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/f_thread_local_data.py index 9fe3beb2..fe9d228b 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/f_thread_local_data.py +++ b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/f_thread_local_data.py @@ -3,8 +3,8 @@ """ import logging -import random import threading +import secrets logging.basicConfig( level=logging.DEBUG, @@ -23,7 +23,7 @@ def show_value(data): def worker(data): show_value(data) - data.value = random.randint(1, 100) + data.value = secrets.SystemRandom().randint(1, 100) show_value(data) diff --git a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/f_thread_local_data2.py b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/f_thread_local_data2.py index 9b8ca918..703c9152 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/f_thread_local_data2.py +++ b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/f_thread_local_data2.py @@ -3,8 +3,8 @@ """ import logging -import random import threading +import secrets logging.basicConfig( level=logging.DEBUG, @@ -25,7 +25,7 @@ def show_value(data): def worker(data): logging.debug("worker - start") show_value(data) - data.value = random.randint(1, 100) + data.value = secrets.SystemRandom().randint(1, 100) show_value(data) diff --git a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/i2_get_thread_return_val.py b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/i2_get_thread_return_val.py index c9392eca..9e38f34b 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/i2_get_thread_return_val.py +++ b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/i2_get_thread_return_val.py @@ -1,6 +1,6 @@ -import random import threading import time +import secrets class ThreadWithResult(threading.Thread): @@ -19,7 +19,7 @@ def function_to_thread(n): print(f"still running thread {n}") count += 1 time.sleep(3) - result = random.random() + result = secrets.SystemRandom().random() print(f"Return value of thread {n} should be: {result}") return result diff --git a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/b_class_based/a_writing_thread.py b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/b_class_based/a_writing_thread.py index 8af35229..beaef4f6 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/b_class_based/a_writing_thread.py +++ b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/b_class_based/a_writing_thread.py @@ -1,6 +1,6 @@ -import random import time from threading import Thread +import secrets class WritingThread(Thread): @@ -26,7 +26,7 @@ def run(self) -> None: if __name__ == "__main__": files = [f"test{x}.txt" for x in range(1, 6)] for filename in files: - work_time = random.choice(range(1, 3)) - number_of_lines = random.choice(range(5, 20)) + work_time = secrets.choice(range(1, 3)) + number_of_lines = secrets.choice(range(5, 20)) thread = WritingThread(filename, number_of_lines, work_time) thread.start() diff --git a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/b_class_based/c_worker_thread_subclass.py b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/b_class_based/c_worker_thread_subclass.py index f9f2a9ce..e10cb4e4 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/b_class_based/c_worker_thread_subclass.py +++ b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/b_class_based/c_worker_thread_subclass.py @@ -1,7 +1,7 @@ #!/usr/bin/python3 -import random import threading import time +import secrets class WorkerThread(threading.Thread): @@ -19,7 +19,7 @@ def run(self): def worker(name: str, instance_id: int) -> None: print(f"Started worker {name} - {instance_id}") - worker_time = random.choice(range(1, 5)) + worker_time = secrets.choice(range(1, 5)) time.sleep(worker_time) print(f"{name} - {instance_id} worker finished in " f"{worker_time} seconds") diff --git a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/c_locks/b4_locks_access_to_resources.py b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/c_locks/b4_locks_access_to_resources.py index b3985142..0be959ce 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/c_locks/b4_locks_access_to_resources.py +++ b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/c_locks/b4_locks_access_to_resources.py @@ -3,9 +3,9 @@ """ import logging -import random import threading import time +import secrets logging.basicConfig( level=logging.DEBUG, @@ -30,7 +30,7 @@ def increment(self): def worker(c): for _ in range(2): - pause = random.random() + pause = secrets.SystemRandom().random() logging.debug("Sleeping %0.02f", pause) time.sleep(pause) c.increment() diff --git a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/d_conditions/a_condition.py b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/d_conditions/a_condition.py index cf1d0ebe..503e8cc6 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/d_conditions/a_condition.py +++ b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/d_conditions/a_condition.py @@ -16,10 +16,9 @@ Following code demonstrates the implementation of another simple producer-consumer problem with the help of the Condition object. """ - -import random import time from threading import Condition, Thread +import secrets # 'condition' variable will be used to represent the availability of a produced item. condition = Condition() @@ -30,8 +29,8 @@ def producer(ntimes): for i in range(ntimes): - val = f"Producer- { random.randint(1, 10)}" - time.sleep(random.randrange(2, 5)) # Sleeps for some time. + val = f"Producer- { secrets.SystemRandom().randint(1, 10)}" + time.sleep(secrets.SystemRandom().randrange(2, 5)) # Sleeps for some time. condition.acquire() values.append(val) # writing on shared object @@ -43,7 +42,7 @@ def producer(ntimes): def consumer(ntimes): for i in range(ntimes): - time.sleep(random.randrange(2, 5)) # Sleeps for some time. + time.sleep(secrets.SystemRandom().randrange(2, 5)) # Sleeps for some time. condition.acquire() condition.wait() # Blocks until an item is available for consumption. diff --git a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/d_semaphores/a_semaphores.py b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/d_semaphores/a_semaphores.py index 9b19e54b..739e9d4e 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/d_semaphores/a_semaphores.py +++ b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/d_semaphores/a_semaphores.py @@ -17,10 +17,9 @@ Following code demonstrates the use of semaphores in a simple producer-consumer problem. """ - -import random import time from threading import BoundedSemaphore, Thread +import secrets max_items = 5 @@ -33,7 +32,7 @@ def producer(nloops): for _ in range(nloops): - time.sleep(random.randrange(2, 5)) + time.sleep(secrets.SystemRandom().randrange(2, 5)) print(time.ctime(), end=": ") try: container.release() @@ -44,7 +43,7 @@ def producer(nloops): def consumer(nloops): for _ in range(nloops): - time.sleep(random.randrange(2, 5)) + time.sleep(secrets.SystemRandom().randrange(2, 5)) print(time.ctime(), end=": ") """ In the following if statement we disable the default @@ -57,11 +56,11 @@ def consumer(nloops): threads = [] -nloops = random.randrange(3, 6) +nloops = secrets.SystemRandom().randrange(3, 6) print("Starting with %s items." % max_items) threads.append(Thread(target=producer, args=(nloops,))) threads.append( - Thread(target=consumer, args=(random.randrange(nloops, nloops + max_items + 2),)) + Thread(target=consumer, args=(secrets.SystemRandom().randrange(nloops, nloops + max_items + 2),)) ) diff --git a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/e_events/a_event.py b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/e_events/a_event.py index 56f5847b..8336c8cf 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/e_events/a_event.py +++ b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/e_events/a_event.py @@ -8,10 +8,9 @@ Following snippet demonstrates how Events can be used to trigger actions. """ - -import random import time from threading import Event, Thread +import secrets event = Event() @@ -27,12 +26,12 @@ def waiter(event, nloops): def setter(event, nloops): for _ in range(nloops): - time.sleep(random.randrange(2, 5)) # Sleeps for some time. + time.sleep(secrets.SystemRandom().randrange(2, 5)) # Sleeps for some time. event.set() threads = [] -nloops = random.randrange(3, 6) +nloops = secrets.SystemRandom().randrange(3, 6) threads.append(Thread(target=waiter, args=(event, nloops))) threads[-1].start() diff --git a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/g_barriers/a_barriers.py b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/g_barriers/a_barriers.py index 1f6f9a53..2c84804c 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/g_barriers/a_barriers.py +++ b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/g_barriers/a_barriers.py @@ -11,10 +11,9 @@ Following snippet demonstrates the use of Barriers. """ - -from random import randrange from threading import Barrier, Thread from time import ctime, sleep +import secrets num = 4 # 4 threads will need to pass this barrier to get released. @@ -24,7 +23,7 @@ def player(): name = names.pop() - sleep(randrange(2, 10)) + sleep(secrets.SystemRandom().randrange(2, 10)) print("%s reached the barrier at: %s" % (name, ctime())) b.wait() diff --git a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/threading/Ch9.py b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/threading/Ch9.py index c47ffbd4..4e22c733 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/threading/Ch9.py +++ b/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/threading/Ch9.py @@ -1,8 +1,8 @@ import base64 import os -import random import sys from functools import reduce +import secrets # These examples are not in individual functions in the chapter, but # to isolate them, they are separated into individual functions here @@ -189,7 +189,7 @@ def os_system_sample(): def _gen_salt(): - salt = [chr(random.randint(0, 255)) for i in range(4)] + salt = [chr(secrets.SystemRandom().randint(0, 255)) for i in range(4)] return "".join(salt) diff --git a/python3/19_Concurrency_and_Parallel_Programming/02_Parallel_Processing/multi_threading_ex1.py b/python3/19_Concurrency_and_Parallel_Programming/02_Parallel_Processing/multi_threading_ex1.py index edd9dae5..e4edb350 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/02_Parallel_Processing/multi_threading_ex1.py +++ b/python3/19_Concurrency_and_Parallel_Programming/02_Parallel_Processing/multi_threading_ex1.py @@ -1,6 +1,6 @@ -import random import time from threading import Thread +import secrets class MyThread(Thread): @@ -9,7 +9,7 @@ def __init__(self, name): self.name = name def run(self): - amount = random.randint(3, 15) + amount = secrets.SystemRandom().randint(3, 15) time.sleep(amount) msg = "{} is running".format(self.name) print(msg) diff --git a/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/b_process_pool.py b/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/b_process_pool.py index 199e8b33..ef88fe29 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/b_process_pool.py +++ b/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/b_process_pool.py @@ -1,11 +1,11 @@ -import random import time from multiprocessing import Pool +import secrets def worker(name: str) -> None: print(f"Started worker {name}") - worker_time = random.choice(range(1, 5)) + worker_time = secrets.choice(range(1, 5)) time.sleep(worker_time) print(f"{name} worker finished in {worker_time} seconds") diff --git a/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/c_worker_processes.py b/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/c_worker_processes.py index 7d563af2..fd9e7653 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/c_worker_processes.py +++ b/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/c_worker_processes.py @@ -1,11 +1,11 @@ import multiprocessing -import random import time +import secrets def worker(name: str) -> None: print(f"Started worker {name}") - worker_time = random.choice(range(1, 5)) + worker_time = secrets.choice(range(1, 5)) time.sleep(worker_time) print(f"{name} worker finished in {worker_time} seconds") diff --git a/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/d_worker_process_subclass.py b/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/d_worker_process_subclass.py index acd2e29c..2fb17f79 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/d_worker_process_subclass.py +++ b/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/d_worker_process_subclass.py @@ -1,6 +1,6 @@ import multiprocessing -import random import time +import secrets class WorkerProcess(multiprocessing.Process): @@ -17,7 +17,7 @@ def run(self): def worker(name: str) -> None: print(f"Started worker {name}") - worker_time = random.choice(range(1, 5)) + worker_time = secrets.choice(range(1, 5)) time.sleep(worker_time) print(f"{name} worker finished in {worker_time} seconds") diff --git a/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/multiprocessing_queue.py b/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/multiprocessing_queue.py index 00a3c39a..128b690b 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/multiprocessing_queue.py +++ b/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/multiprocessing_queue.py @@ -7,12 +7,12 @@ for passing data between different processes without potentially corrupting data. """ -import random from multiprocessing import Process, Queue +import secrets def rand_num(queue): - num = random.random() + num = secrets.SystemRandom().random() queue.put(num) diff --git a/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/mutiprocessing_pool.py b/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/mutiprocessing_pool.py index a24fd3cb..dfed69d0 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/mutiprocessing_pool.py +++ b/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/mutiprocessing_pool.py @@ -2,15 +2,15 @@ # mutiprocessing_pool.py import os -import random import time from multiprocessing import Pool +import secrets def long_time_task(name): print("Run task %s (%s)..." % (name, os.getpid())) start = time.time() - time.sleep(random.random() * 3) + time.sleep(secrets.SystemRandom().random() * 3) end = time.time() print("Task %s runs %0.2f seconds." % (name, (end - start))) diff --git a/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/mutiprocessing_queue.py b/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/mutiprocessing_queue.py index 852e6336..11f8447c 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/mutiprocessing_queue.py +++ b/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/mutiprocessing_queue.py @@ -1,9 +1,9 @@ #!/usr/bin/env python # _*_ coding:utf-8 _*_ -import random import time from multiprocessing import Process, Queue +import secrets # 写数据进程执行的代码: @@ -11,7 +11,7 @@ def write(q): for value in ["A", "B", "C"]: print("Put %s to queue..." % value) q.put(value) - time.sleep(random.random()) + time.sleep(secrets.SystemRandom().random()) # 读数据进程执行的代码: diff --git a/python3/19_Concurrency_and_Parallel_Programming/03_asyncio_module/h_asyncio_wait.py b/python3/19_Concurrency_and_Parallel_Programming/03_asyncio_module/h_asyncio_wait.py index 5ad2e480..015e0e1d 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/03_asyncio_module/h_asyncio_wait.py +++ b/python3/19_Concurrency_and_Parallel_Programming/03_asyncio_module/h_asyncio_wait.py @@ -10,11 +10,11 @@ ALL_COMPLETED The function will return when all futures finish or are cancelled. """ import asyncio -from random import randrange +import secrets async def foo(n): - s = randrange(5) + s = secrets.SystemRandom().randrange(5) print(f"{n} will sleep for: {s} seconds") await asyncio.sleep(s) print(f"n: {n}!") diff --git a/python3/19_Concurrency_and_Parallel_Programming/03_asyncio_module/j_asyncio_as_completed.py b/python3/19_Concurrency_and_Parallel_Programming/03_asyncio_module/j_asyncio_as_completed.py index f540ad6d..5d49359b 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/03_asyncio_module/j_asyncio_as_completed.py +++ b/python3/19_Concurrency_and_Parallel_Programming/03_asyncio_module/j_asyncio_as_completed.py @@ -11,11 +11,11 @@ Takes an optional timeout. """ import asyncio -from random import randrange +import secrets async def foo(n): - s = randrange(10) + s = secrets.SystemRandom().randrange(10) print(f"{n} will sleep for: {s} seconds") await asyncio.sleep(s) return f"{n}!" diff --git a/python3/19_Concurrency_and_Parallel_Programming/03_asyncio_module/n_asyncio_ex.py b/python3/19_Concurrency_and_Parallel_Programming/03_asyncio_module/n_asyncio_ex.py index b6d35f12..17461992 100644 --- a/python3/19_Concurrency_and_Parallel_Programming/03_asyncio_module/n_asyncio_ex.py +++ b/python3/19_Concurrency_and_Parallel_Programming/03_asyncio_module/n_asyncio_ex.py @@ -1,7 +1,7 @@ import asyncio -import random from concurrent.futures import ThreadPoolExecutor from time import sleep +import secrets def return_after_5_secs(message): @@ -13,7 +13,7 @@ def return_after_5_secs(message): async def doit(): - identify = random.randint(1, 100) + identify = secrets.SystemRandom().randint(1, 100) future = pool.submit(return_after_5_secs, (f"result: {identify}")) awaitable = asyncio.wrap_future(future) print(f"waiting result: {identify}")