From bf6aca39186b4bf9794f97d99c36fb1946cf4858 Mon Sep 17 00:00:00 2001 From: Dominik Jagosz Date: Tue, 18 Jun 2024 22:04:24 +0200 Subject: [PATCH] poczatek --- .idea/.gitignore | 8 + .idea/cw1.iml | 15 + .idea/inspectionProfiles/Project_Default.xml | 19 ++ .../inspectionProfiles/profiles_settings.xml | 6 + .idea/misc.xml | 4 + .idea/modules.xml | 8 + __pycache__/hmac.cpython-310.pyc | Bin 0 -> 909 bytes bezp.py.txt | 62 ++++ dsa.py | 190 ++++++++++++ ff.py | 1 + gcm.py | 266 +++++++++++++++++ haslo.txt | 1 + hmac.py | 36 +++ klient.py | 21 ++ main.py | 75 +++++ rsa.py | 282 ++++++++++++++++++ serwer.py | 28 ++ 17 files changed, 1022 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/cw1.iml create mode 100644 .idea/inspectionProfiles/Project_Default.xml create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 __pycache__/hmac.cpython-310.pyc create mode 100644 bezp.py.txt create mode 100644 dsa.py create mode 100644 ff.py create mode 100644 gcm.py create mode 100644 haslo.txt create mode 100644 hmac.py create mode 100644 klient.py create mode 100644 main.py create mode 100644 rsa.py create mode 100644 serwer.py diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..1c2fda5 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/cw1.iml b/.idea/cw1.iml new file mode 100644 index 0000000..941cd07 --- /dev/null +++ b/.idea/cw1.iml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..1e43b99 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,19 @@ + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..29aeebd --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..845600f --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/__pycache__/hmac.cpython-310.pyc b/__pycache__/hmac.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..825d78b07a5eeb160e0fe040eb2ac1433d2b0436 GIT binary patch literal 909 zcmZ8fL2uJg47T4(+BCFKO_e|h#Ml9;7o=S$G@uhshyQTAg`h23duSvWJGyEQzOT9b0q^$yQ)P|Zxhw9 zd9%j-E!@>qopP|QDb&4({f$h z&TshB+BQ!)zl@70ix-UKJu(h<(W9qF>X7M~ z*R%;Ezou`Rl(XI=Q?uyHTe^X~S|oS5IZ+atE~V%Ek1`KtLrflUiMkl?K5mh@E5Bj+ z`1SGG?%8IvD4Y~gn(V&QIROXD9>= najdluzszy_czas: + najdluzszy_czas = czas + najdluzszy = c + if url_response.status_code == 200: + odgadnieto = True + najdluzszy = c + haslo += c + print("weszlo") + print(haslo) + break + haslo = haslo + najdluzszy + if odgadnieto: + break + print(haslo) diff --git a/dsa.py b/dsa.py new file mode 100644 index 0000000..404adf1 --- /dev/null +++ b/dsa.py @@ -0,0 +1,190 @@ +import sys +from hashlib import sha256, sha384 +import os +import random + +byteorder = sys.byteorder + + +def get_power_2_factors(n: int) -> (int, int): + r = 0 + d = n + while n > 0 and d % 2 == 0: + d = d // 2 + r += 1 + return r, d + + +def miller_rabin_prime_test(n: int, k: int = 64) -> bool: + # Factor powers of 2 from n - 1 s.t. n - 1 = 2^r * d + r, d = get_power_2_factors(n - 1) + + for i in range(k): + a = get_random_bits(n.bit_length()) + while a not in range(2, n - 2 + 1): + a = get_random_bits(n.bit_length()) + x = pow(a, d, n) + if x == 1 or x == n - 1: + continue + n_1_found = False + for j in range(r - 1): + x = pow(x, 2, n) + if x == n - 1: + n_1_found = True + break + if not n_1_found: + return False + return True + + +def get_random_bits(bit_length: int) -> int: + return int.from_bytes(os.urandom((bit_length + 7) // 8), 'big') + + +def bezpieczny_randint(poczatek_inkluzywny, koniec_ekskluzywny): + dlugosc_przedzialu = koniec_ekskluzywny - poczatek_inkluzywny + maksymalna_liczba_bitow_zapisu = dlugosc_przedzialu.bit_length() + # liczba miedzy 0 a 2**maksymalna_liczba_bitow_zapisu + wyn = get_random_bits(maksymalna_liczba_bitow_zapisu) + # liczba miedzy 0 a dlugosc_przedzialu + while wyn >= dlugosc_przedzialu: + wyn = get_random_bits(maksymalna_liczba_bitow_zapisu) + # liczba miedzy poczatek_inkluzywny a koniec_ekskluzywny + wyn = poczatek_inkluzywny + wyn + return wyn + + +def generate_prime_number(bit_length: int) -> int: + # prime needs to be in range [2^(n-1), 2^n-1] + low = pow(2, bit_length - 1) + high = pow(2, bit_length) - 1 + + while True: + + # Generate odd prime candidate in range + candidate_prime = get_random_bits(bit_length) + while candidate_prime not in range(low, high + 1) or not candidate_prime % 2: + candidate_prime = get_random_bits(bit_length) + + # with k rounds, miller rabin test gives false positive with probability (1/4)^k = 1/(2^2k) + k = 64 + if miller_rabin_prime_test(candidate_prime, k): + return candidate_prime + + +def rozszerzony_algorytm_euklidesa(a0, b0): + a, b = a0, b0 + x, y = 1, 0 + r, s = 0, 1 + while b != 0: + c = a % b + q = a // b + a, b = b, c + r_pom, s_pom = r, s + r = x - q * r + s = y - q * s + x, y = r_pom, s_pom + nwd = x * a0 + y * b0 + return a, x, y, nwd + + +def NWD(a, b): + nwd1, _, _, nwd2 = rozszerzony_algorytm_euklidesa(a, b) + if nwd1 == nwd2: + return nwd1 + else: + return None + + +def odwrotnosc_modulo(a, n): + _, x, y, _ = rozszerzony_algorytm_euklidesa(a, n) + if a != 1 and x == 1: + odwrotnosc_a = "nie ma elementu odwrotnego" + elif x > 0: + odwrotnosc_a = x % n + else: + odwrotnosc_a = (n + x) % n + return odwrotnosc_a + + +def szybkie_potegowanie_modulo(podstawa, wykladnik, rzad): + pom = 1 + while wykladnik > 1: + ostatni_bit = wykladnik & 1 + wykladnik >>= 1 + if ostatni_bit == 1: + pom = (pom * podstawa) % rzad + podstawa = (podstawa * podstawa) % rzad + return (podstawa * pom) % rzad + + +def genDSA(): + q = generate_prime_number(160) + print("q", q.bit_length()) + t = bezpieczny_randint(0, 9) + print("t", t, 512 + 64 * t) + k = 2 ** (511 - 160 + 1 + 64 * t) + while True: + p = k * q + 1 + if miller_rabin_prime_test(p, 64): + break + k += 1 + print("p", p.bit_length()) + while True: + g = bezpieczny_randint(2 ** (p.bit_length() - 1), 2 ** (p.bit_length())) + alfa = szybkie_potegowanie_modulo(g, (p - 1) // q, p) + if alfa != 1: + break + print("g, alfa", g.bit_length(), alfa.bit_length()) + a = bezpieczny_randint(1, q) + y = szybkie_potegowanie_modulo(alfa, a, p) + # tlumaczenie symboli + p, q, g, y, x = p, q, alfa, y, a + klucz_publiczny_DSA = (p, q, g, y) + klucz_prywatny_DSA = x + return klucz_publiczny_DSA, klucz_prywatny_DSA + + +def sig_DSA(p, q, g, x, m): + byteorder = sys.byteorder + k = get_random_bits(q.bit_length()) + print("k", k) + r = szybkie_potegowanie_modulo(g, k, p) % q + print("r", r) + H_od_m = sha256(m).digest() + int_H_od_m = int.from_bytes(H_od_m, byteorder) + s = (odwrotnosc_modulo(k, q) * (int_H_od_m + x * r)) % q + print("s", s) + return r, s + + +def ver_DSA(p, q, g, y, m, r, s): + byteorder = sys.byteorder + if not (0 < r and s < q): + print("zle") + H_od_m = sha256(m).digest() + int_H_od_m = int.from_bytes(H_od_m, byteorder) + u1 = (odwrotnosc_modulo(s, q) * int_H_od_m) % q + u2 = (r * odwrotnosc_modulo(s, q)) % q + v = ((szybkie_potegowanie_modulo(g, u1, p) * szybkie_potegowanie_modulo(y, u2, p)) % p) % q + print("r", r) + print("v", v) + if v == r: + b = 1 + else: + b = 0 + return b + + +print("DSA") +klucz_publiczny_DSA, klucz_prywatny_DSA = genDSA() +print(klucz_publiczny_DSA, klucz_prywatny_DSA) +p, q, g, y = klucz_publiczny_DSA +x = klucz_prywatny_DSA + +m = "Thats my Kung Fu".encode("ASCII") +print(m) +r, s = sig_DSA(p, q, g, x, m) +print(r, s) +b = ver_DSA(p, q, g, y, m, r, s) +print(b) diff --git a/ff.py b/ff.py new file mode 100644 index 0000000..565c8fb --- /dev/null +++ b/ff.py @@ -0,0 +1 @@ +print("ddd") \ No newline at end of file diff --git a/gcm.py b/gcm.py new file mode 100644 index 0000000..95e597c --- /dev/null +++ b/gcm.py @@ -0,0 +1,266 @@ +import math +from cryptography.hazmat.primitives.ciphers import Cipher +from cryptography.hazmat.primitives.ciphers.algorithms import AES +from cryptography.hazmat.primitives.ciphers.modes import GCM, ECB +import os +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + +def aes_gcm_authenticated_decryption(key, iv, auth_tag, associated_data, ciphertext): + aes_gcm_decryptor = Cipher(AES(key), GCM(iv, auth_tag)).decryptor() + aes_gcm_decryptor.authenticate_additional_data(associated_data) + recovered_plaintext = aes_gcm_decryptor.update(ciphertext) + aes_gcm_decryptor.finalize() + return recovered_plaintext, auth_tag + + +def xor_bytes(bytes_a: bytes, bytes_b: bytes) -> bytes: + return bytes([a ^ b for (a, b) in zip(bytes_a, bytes_b)]) + + +def MUL(X_bytes, Y_bytes): + X = int.from_bytes(X_bytes, 'big') + Y = int.from_bytes(Y_bytes, 'big') + # Constant R defined for algorithm + R = 0xe1 << 120 + # Step 1 + x = [1 if X & (1 << i) else 0 for i in range(127, -1, -1)] + # Steps 2 and 3 + Z_i = 0 + V_i = Y + for i in range(128): + if x[i] == 0: + Z_i_1 = Z_i + else: + Z_i_1 = Z_i ^ V_i + if V_i % 2 == 0: + V_i_1 = V_i >> 1 + else: + V_i_1 = (V_i >> 1) ^ R + Z_i = Z_i_1 + V_i = V_i_1 + # Step 4 + return Z_i.to_bytes(16, 'big') + + +def GHASH(H, X): + # Input constraint: len(X) = 128m + # 128/8=16 bo bajty + m = len(X) // 16 + # Step 1 + X_blocks = [X[i * 16:(i + 1) * 16] for i in range(m)] + # Step 2 + # b'\x00' = 00000000 + Y_0 = b'\x00' * 16 + # Step 3 + Y_i_1 = Y_0 + for i in range(m): + X_i = X_blocks[i] + Y_i = MUL(xor_bytes(Y_i_1, X_i), H) + Y_i_1 = Y_i + # Step 4 + return Y_i_1 + + +def INC_32(Y_bytes): + Y = int.from_bytes(Y_bytes, 'big') + Y_inc = ((Y >> 32) << 32) ^ (((Y & 0xffffffff) + 1) & 0xffffffff) + return Y_inc.to_bytes(16, 'big') + + +def GCTR(K, ICB, X): + # Step 1 + if not X: + return b'' + + # Step 2 + n = math.ceil(len(X) / 16) + + # Step 3 + X_blocks = [X[i * 16:(i + 1) * 16] for i in range(n)] + + # Step 4 + CB = [ICB] + + # Step 5 + for i in range(1, n): + CB_i = INC_32(CB[i - 1]) + CB.append(CB_i) + + # Steps 6 and 7 + Y_blocks = [] + for i in range(n): + X_i = X_blocks[i] + CB_i = CB[i] + aes_encryptor = Cipher(AES(K), ECB()).encryptor() + ciphertext = aes_encryptor.update(CB_i) + aes_encryptor.finalize() + # Y_i = xor_bytes(X_i, aes_encryption(CB_i, K)) + Y_i = xor_bytes(X_i, ciphertext) + Y_blocks.append(Y_i) + + # Step 8 + Y = b''.join(Y_blocks) + + # Step 9 + return Y + + +def aes_gcm_encrypt(P, K, IV, A, t): + # Step 1 + data = (b'\x00' * 16) + aes_encryptor = Cipher(AES(K), ECB()).encryptor() + H = aes_encryptor.update(data) + aes_encryptor.finalize() + # Step 2 + len_IV = len(IV) * 8 + if len_IV == 96: + J_0 = IV + b'\x00\x00\x00\x01' + else: + s = 128 * math.ceil(len_IV / 128) - len_IV + O_s_64 = b'\x00' * ((s + 64) // 8) + len_IV_64 = int.to_bytes(len_IV, 8, 'big') + J_0 = GHASH(H, IV + O_s_64 + len_IV_64) + + # Step 3 + C = GCTR(K, INC_32(J_0), P) + + # Step 4 + len_C, len_A = len(C) * 8, len(A) * 8 + u = 128 * math.ceil(len_C / 128) - len_C + v = 128 * math.ceil(len_A / 128) - len_A + + # Step 5 + O_v = b'\x00' * (v // 8) + O_u = b'\x00' * (u // 8) + len_A_64 = int.to_bytes(len_A, 8, 'big') + len_C_64 = int.to_bytes(len_C, 8, 'big') + S = GHASH(H, A + O_v + C + O_u + len_A_64 + len_C_64) + + # Step 6 + T = GCTR(K, J_0, S)[:t // 8] # Assumes tag length multiple of 8 + + # Step 7 + return C, T + + +if __name__ == "__main__": + # NIST Special Publication 800-38D + + # NIST test vector 1 + key = bytearray.fromhex('11754cd72aec309bf52f7687212e8957') + iv = bytearray.fromhex('3c819d9a9bed087615030b65') + plaintext = bytearray.fromhex('') + associated_data = bytearray.fromhex('') + expected_ciphertext = bytearray.fromhex('') + expected_tag = bytearray.fromhex('250327c674aaf477aef2675748cf6971') + tag_length = 128 + + ciphertext, auth_tag = aes_gcm_encrypt(plaintext, key, iv, associated_data, tag_length) + + assert (ciphertext == expected_ciphertext) + assert (auth_tag == expected_tag) + + message, _ = aes_gcm_authenticated_decryption(key, iv, auth_tag, associated_data, ciphertext) + print("wiadomosc:") + print(plaintext) + print("otrzymana wiadomosc:") + print(message) + + # NIST test vector 2 + key = bytearray.fromhex('fe47fcce5fc32665d2ae399e4eec72ba') + iv = bytearray.fromhex('5adb9609dbaeb58cbd6e7275') + plaintext = bytearray.fromhex('7c0e88c88899a779228465074797cd4c2e1498d259b54390b85e3eef1c02df60e743f1b840382c4bccaf' + '3bafb4ca8429bea063') + associated_data = bytearray.fromhex('88319d6e1d3ffa5f987199166c8a9b56c2aeba5a') + expected_ciphertext = bytearray.fromhex('98f4826f05a265e6dd2be82db241c0fbbbf9ffb1c173aa83964b7cf5393043736365253ddb' + 'c5db8778371495da76d269e5db3e') + expected_tag = bytearray.fromhex('291ef1982e4defedaa2249f898556b47') + tag_length = 128 + + ciphertext, auth_tag = aes_gcm_encrypt(plaintext, key, iv, associated_data, tag_length) + + assert (ciphertext == expected_ciphertext) + assert (auth_tag == expected_tag) + + message, _ = aes_gcm_authenticated_decryption(key, iv, auth_tag, associated_data, ciphertext) + print("wiadomosc:") + print(plaintext) + print("otrzymana wiadomosc:") + print(message) + + # NIST test vector 3 + key = bytearray.fromhex('c7d9358af0fd737b118dbf4347fd252a') + iv = bytearray.fromhex('83de9fa52280522b55290ebe3b067286d87690560179554153cb3341a04e15c5f35390602fa07e5b5f16dc38cf0' + '82b11ad6dd3fab8552d2bf8d9c8981bbfc5f3b57e5e3066e3df23f078fa25bce63d3d6f86ce9fbc2c679655b958' + 'b09a991392eb93b453ba6e7bf8242f8f61329e3afe75d0f8536aa7e507d75891e540fb1d7e') + plaintext = bytearray.fromhex('422f46223fddff25fc7a6a897d20dc8af6cc8a37828c90bd95fa9b943f460eb0a26f29ffc483592efb64' + '835774160a1bb5c0cd') + associated_data = bytearray.fromhex('5d2b9a4f994ffaa03000149956c8932e85b1a167294514e388b73b10808f509ea73c075ecbf43c' + 'ecfec13c202afed62110dabf8026d237f4e765853bc078f3afe081d0a1f8d8f7556b8e42acc3cc' + 'e888262185048d67c55b2df1') + expected_ciphertext = bytearray.fromhex('86eba4911578ac72ac30c25fe424da9ab625f29b5c00e36d2c24a2733dc40123dc57a8c9f1' + '7a24a26c09c73ad4efbcba3bab5b') + expected_tag = bytearray.fromhex('492305190344618cab8b40f006a57186') + tag_length = 128 + + ciphertext, auth_tag = aes_gcm_encrypt(plaintext, key, iv, associated_data, tag_length) + + assert (ciphertext == expected_ciphertext) + assert (auth_tag == expected_tag) + + message, _ = aes_gcm_authenticated_decryption(key, iv, auth_tag, associated_data, ciphertext) + print("wiadomosc:") + print(plaintext) + print("otrzymana wiadomosc:") + print(message) + + print("\n" * 10) + # wlasne + key = AESGCM.generate_key(bit_length=128) # bytearray.fromhex('11754cd72aec309bf52f7687212e8957') + iv = bytearray.fromhex('3c819d9a9bed087615030b65') + + plaintext = "wiadomosc1".encode() + associated_data = "potwierdzenie".encode() + ciphertext, auth_tag = aes_gcm_encrypt(plaintext, key, iv, associated_data, tag_length) + + print(ciphertext) + print(auth_tag) + + message, _ = aes_gcm_authenticated_decryption(key, iv, auth_tag, associated_data, ciphertext) + print(message) + + data = b"wiadomosc1" + aad = b"potwierdzenie" + + aesgcm = AESGCM(key) + nonce = iv # os.urandom(12) + + ct = aesgcm.encrypt(nonce, data, aad) + print(ct) + + msg = aesgcm.decrypt(nonce, ct, aad) + print(msg) + + # przykladowe dane 10 + + print("\n" * 5) + # wlasne + key = bytearray.fromhex('feffe9928665731c6d6a8f9467308308feffe9928665731c') + iv = bytearray.fromhex('cafebabefacedbaddecaf888') + plaintext = bytearray.fromhex( + "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39") + associated_data = bytearray.fromhex("feedfacedeadbeeffeedfacedeadbeefabaddad2") + + # wlasne + ciphertext, auth_tag = aes_gcm_encrypt(plaintext, key, iv, associated_data, tag_length) + print(ciphertext.hex(), auth_tag.hex(), sep="") + + message, _ = aes_gcm_authenticated_decryption(key, iv, auth_tag, associated_data, ciphertext) + print(message.hex()) + + # gotowe + aesgcm = AESGCM(key) + + ciphertext = aesgcm.encrypt(iv, plaintext, associated_data) + print(ciphertext.hex()) + + message = aesgcm.decrypt(iv, ciphertext, associated_data) + print(message.hex()) diff --git a/haslo.txt b/haslo.txt new file mode 100644 index 0000000..6bd5de4 --- /dev/null +++ b/haslo.txt @@ -0,0 +1 @@ +p4ssw0rd \ No newline at end of file diff --git a/hmac.py b/hmac.py new file mode 100644 index 0000000..81fe563 --- /dev/null +++ b/hmac.py @@ -0,0 +1,36 @@ +def gcm_add(x, y): + return x ^ y + +def gcm_multiply(x, y, poly): + z = 0 + for _ in range(poly.bit_length()): + if y & 1: + z ^= x + hi_bit_set = x & (1 << poly.bit_length() - 1) + x <<= 1 + if hi_bit_set: + x ^= poly + y >>= 1 + return z + +def incr(x): + y=1%(2^32) + wyn = x+y + if wyn >= 2^32: + wyn=1%(2^32) + return wyn + +a = 0b0001 +b = 0b0101 +print(a,b) +print(bin(a),bin(b)) +polynomial = 0xE1000000000000000000000000000000 + +result = gcm_multiply(a, b, polynomial) +print("GCM Multiplication Result:", bin(result)) + +result = gcm_add(a, b) +print("GCM Addition Result:", bin(result)) + +print(incr(1)) +print(incr((2^32)-1)) \ No newline at end of file diff --git a/klient.py b/klient.py new file mode 100644 index 0000000..43c493d --- /dev/null +++ b/klient.py @@ -0,0 +1,21 @@ +# https://realpython.com/python-sockets/ +# echo-client.py +import socket + +HOST = "150.254.79.26" +PORT = 65432 # The port used by the server + +with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.connect((HOST, PORT)) + klucz_publiczny = s.recv(16384) + print(klucz_publiczny) + do_podpisania = b"Hello, world" + s.sendall(do_podpisania) + podpis = s.recv(4096) + +print(f"Received {podpis}") +p, q, g, y = klucz_publiczny_DSA +m = do_podpisania +r, s = podpis +weryfikacja_DSA = ver_DSA(p, q, g, y, m, r, s) +print(weryfikacja_DSA) diff --git a/main.py b/main.py new file mode 100644 index 0000000..f535c7e --- /dev/null +++ b/main.py @@ -0,0 +1,75 @@ +# r_podwojne = b"01001001001001000011101101101111011110" + +N = 8 +# r od n +r1 = b"11111111" +r2 = b"11111111" +r1 = (int(r1, 2)) + (1 << N) +r2 = (int(r2, 2)) + (1 << N) +# t od 1 +t1 = b"10001110" +t2 = b"10010101" +t1 = (int(t1, 2)) + (1 << N) +t2 = (int(t2, 2)) + (1 << N) +# +pdpkt_a = b"000011" +pdkpt_b = b"101001" +pdpkt_a = (int(pdpkt_a, 2)) + (1 << N) +pdkpt_b = (int(pdkpt_b, 2)) + (1 << N) + +def nastepny_bit(r, t): + rc = r + tc = t + wyn = None + #print(bin(rc)) + #print(bin(tc)) + for i in range(N): + bit = rc & 1 + bit_z_t = tc & 1 + if bit_z_t == 1: + if wyn == None: + wyn = bit + else: + wyn = wyn ^ bit + rc = rc >> 1 + tc = tc >> 1 + #print(bit) + #print(wyn) + #print(bin(rc)) + #print(bin(tc)) + #print("xor", bin(wyn)) + wywalane_z_r = r & 1 + #print("r", bin(r)) + r = r >> 1 + #print("podzielone", bin(r)) + r = r - (1 << N - 1) + r = r + (wyn << N - 1) + r = r + (1 << N) + #print("r dodane", bin(r)) + return r, wywalane_z_r + + +#r1, b = nastepny_bit(r1, t1) +#print(bin(r1)) +#print(b) + + +def shrinking_generator(r1, r2, t1, t2,rundy=10000): + wyn = [] + for i in range(rundy): + r1, l1 = nastepny_bit(r1, t1) + r2, l2 = nastepny_bit(r2, t2) + if l1 == 1: + wyn.append(l2) + print(l2, end="") + if i>0 and i%500==0: + print() + print() + return wyn + +wyn = shrinking_generator(r1,r2,t1,t2) +print(len(wyn)) + +wyn = shrinking_generator(pdpkt_a,pdkpt_b,pdpkt_a,pdkpt_b) +print(len(wyn)) +print(wyn) \ No newline at end of file diff --git a/rsa.py b/rsa.py new file mode 100644 index 0000000..22cca90 --- /dev/null +++ b/rsa.py @@ -0,0 +1,282 @@ +import sys +from hashlib import sha256, sha384 +import os +import random + +byteorder = sys.byteorder + + +def get_power_2_factors(n: int) -> (int, int): + r = 0 + d = n + while n > 0 and d % 2 == 0: + d = d // 2 + r += 1 + return r, d + + +def miller_rabin_prime_test(n: int, k: int = 64) -> bool: + # Factor powers of 2 from n - 1 s.t. n - 1 = 2^r * d + r, d = get_power_2_factors(n - 1) + + for i in range(k): + a = get_random_bits(n.bit_length()) + while a not in range(2, n - 2 + 1): + a = get_random_bits(n.bit_length()) + x = pow(a, d, n) + if x == 1 or x == n - 1: + continue + n_1_found = False + for j in range(r - 1): + x = pow(x, 2, n) + if x == n - 1: + n_1_found = True + break + if not n_1_found: + return False + return True + + +def get_random_bits(bit_length: int) -> int: + return int.from_bytes(os.urandom((bit_length + 7) // 8), 'big') + + +def bezpieczny_randint(poczatek_inkluzywny, koniec_ekskluzywny): + dlugosc_przedzialu = koniec_ekskluzywny-poczatek_inkluzywny + maksymalna_liczba_bitow_zapisu = dlugosc_przedzialu.bit_length() + # liczba miedzy 0 a 2**maksymalna_liczba_bitow_zapisu + wyn = get_random_bits(maksymalna_liczba_bitow_zapisu) + # liczba miedzy 0 a dlugosc_przedzialu + while wyn >= dlugosc_przedzialu: + wyn = get_random_bits(maksymalna_liczba_bitow_zapisu) + # liczba miedzy poczatek_inkluzywny a koniec_ekskluzywny + wyn = poczatek_inkluzywny + wyn + return wyn + + +def generate_prime_number(bit_length: int) -> int: + # prime needs to be in range [2^(n-1), 2^n-1] + low = pow(2, bit_length - 1) + high = pow(2, bit_length) - 1 + + while True: + + # Generate odd prime candidate in range + candidate_prime = get_random_bits(bit_length) + while candidate_prime not in range(low, high + 1) or not candidate_prime % 2: + candidate_prime = get_random_bits(bit_length) + + # with k rounds, miller rabin test gives false positive with probability (1/4)^k = 1/(2^2k) + k = 64 + if miller_rabin_prime_test(candidate_prime, k): + return candidate_prime + + +def rozszerzony_algorytm_euklidesa(a0, b0): + a, b = a0, b0 + x, y = 1, 0 + r, s = 0, 1 + while b != 0: + c = a % b + q = a // b + a, b = b, c + r_pom, s_pom = r, s + r = x - q * r + s = y - q * s + x, y = r_pom, s_pom + nwd = x * a0 + y * b0 + return a, x, y, nwd + + +def NWD(a, b): + nwd1, _, _, nwd2 = rozszerzony_algorytm_euklidesa(a, b) + if nwd1 == nwd2: + return nwd1 + else: + return None + + +def odwrotnosc_modulo(a, n): + _, x, y, _ = rozszerzony_algorytm_euklidesa(a, n) + if a != 1 and x == 1: + odwrotnosc_a = "nie ma elementu odwrotnego" + elif x > 0: + odwrotnosc_a = x % n + else: + odwrotnosc_a = (n + x) % n + return odwrotnosc_a + + +def szybkie_potegowanie_modulo(podstawa, wykladnik, rzad): + pom = 1 + while wykladnik > 1: + ostatni_bit = wykladnik & 1 + wykladnik >>= 1 + if ostatni_bit == 1: + pom = (pom * podstawa) % rzad + podstawa = (podstawa * podstawa) % rzad + return (podstawa * pom) % rzad + + +def genRSA(n=2048): + p = generate_prime_number(n) + # print(p.bit_length()) + q = p + while q == p: + q = generate_prime_number(n) + # print(q.bit_length()) + N = p * q + fi_N = (p - 1) * (q - 1) + print(N.bit_length(), fi_N.bit_length()) + e = bezpieczny_randint(2, fi_N) + while NWD(e, fi_N) != 1: + e = bezpieczny_randint(2, fi_N) + d = odwrotnosc_modulo(e, fi_N) + # print(e.bit_length(),d.bit_length()) + klucz_publiczny = (N, e) + klucz_prywatny = d + return klucz_publiczny, klucz_prywatny, p, q + + +def szyfrowanie_RSA_OAEP(N, e, m: bytes): + byteorder = sys.byteorder + # 256 + 128 = 384 + k = 256 + l = 128 + # G = sha384() + # H = sha256() + print("m", len(m) * 8) + print("m", m) + if len(m) * 8 != l: + return "wiadomosc usi byc dlugosci l =" + str(l) + m_prim = m.ljust(len(m) + k // 8, b"\0") + int_m_prim = int.from_bytes(m_prim, byteorder) + print("m'", len(m_prim) * 8) + print("m'", m_prim) + int_r = get_random_bits(k) + r = int_r.to_bytes(k // 8, byteorder) + print("r", len(r) * 8) + print("r", r) + int_G_od_r = int.from_bytes(sha384(r).digest(), byteorder) + int_t = int_m_prim ^ int_G_od_r + t = int_t.to_bytes((l + k) // 8, byteorder) + print("t", len(t) * 8) + print("t", t) + int_H_od_t = int.from_bytes(sha256(t).digest(), byteorder) + int_s = int_r ^ int_H_od_t + s = int_s.to_bytes(k // 8, byteorder) + print("s", len(s) * 8) + print("s", s) + m_prim_prim = s + t + print("m''", len(m_prim_prim) * 8) + print("m''", m_prim_prim) + int_m_prim_prim = int.from_bytes(m_prim_prim, byteorder) + c = szybkie_potegowanie_modulo(int_m_prim_prim, e, N) + return c + + +def deszyfrowanie_RSA_OAEP(N, d, c): + byteorder = sys.byteorder + # 256 + 128 = 384 + k = 256 + l = 128 + # G = sha384() + # H = sha256() + int_m_prim_prim = szybkie_potegowanie_modulo(c, d, N) + m_prim_prim = int_m_prim_prim.to_bytes((l + 2 * k) // 8, byteorder) + print("m''", len(m_prim_prim) * 8) + print("m''", m_prim_prim) + t = m_prim_prim[-((l + k) // 8):] + print("t", len(t) * 8) + print("t", t) + s = m_prim_prim[:(k // 8)] + print("s", len(s) * 8) + print("s", s) + int_H_od_t = int.from_bytes(sha256(t).digest(), byteorder) + int_s = int.from_bytes(s, byteorder) + int_r = int_H_od_t ^ int_s + r = int_r.to_bytes(k // 8, byteorder) + print("r", len(r) * 8) + print("r", r) + int_G_od_r = int.from_bytes(sha384(r).digest(), byteorder) + int_t = int.from_bytes(t, byteorder) + int_m_prim = int_G_od_r ^ int_t + m_prim = int_m_prim.to_bytes((l + k) // 8, byteorder) + print("m'", len(m_prim) * 8) + print("m'", m_prim) + koncowki = m_prim[-(k // 8):] + m = m_prim[:l // 8] + if koncowki != b"\0".ljust(k // 8, b"\0"): + print("kon") + print(koncowki) + print(b"\0".ljust(k // 8, b"\0")) + print("cowki") + return m + + +def efektywne_deszyfrowanie_RSA(N, d, c, p, q): + u = odwrotnosc_modulo(p, q) + c_p = c % p + c_q = c % q + d_p = d % (p - 1) + d_q = d % (q - 1) + m_p = szybkie_potegowanie_modulo(c_p, d_p, p) + m_q = szybkie_potegowanie_modulo(c_q, d_q, q) + m = (m_p + p * (m_q - m_p) * u) % N + return m + + +def deszyfrowanie_RSA_OAEP_efektywne(N, d, c, p, q): + byteorder = sys.byteorder + # 256 + 128 = 384 + k = 256 + l = 128 + # G = sha384() + # H = sha256() + int_m_prim_prim = efektywne_deszyfrowanie_RSA(N, d, c, p, q) + m_prim_prim = int_m_prim_prim.to_bytes((l + 2 * k) // 8, byteorder) + print("m''", len(m_prim_prim) * 8) + print("m''", m_prim_prim) + t = m_prim_prim[-((l + k) // 8):] + print("t", len(t) * 8) + print("t", t) + s = m_prim_prim[:(k // 8)] + print("s", len(s) * 8) + print("s", s) + int_H_od_t = int.from_bytes(sha256(t).digest(), byteorder) + int_s = int.from_bytes(s, byteorder) + int_r = int_H_od_t ^ int_s + r = int_r.to_bytes(k // 8, byteorder) + print("r", len(r) * 8) + print("r", r) + int_G_od_r = int.from_bytes(sha384(r).digest(), byteorder) + int_t = int.from_bytes(t, byteorder) + int_m_prim = int_G_od_r ^ int_t + m_prim = int_m_prim.to_bytes((l + k) // 8, byteorder) + print("m'", len(m_prim) * 8) + print("m'", m_prim) + koncowki = m_prim[-(k // 8):] + m = m_prim[:l // 8] + if koncowki != b"\0".ljust(k // 8, b"\0"): + print("kon") + print(koncowki) + print(b"\0".ljust(k // 8, b"\0")) + print("cowki") + return m + + +klucz_publiczny_RSA, klucz_prywatny_RSA, p, q = ( + 519761468615543605427347715703470532429938244355530617462517836775139947735532430649086044712389065327373881495341570956912263636228899450218205333731994709572385570226639327413165593530360209805759468603639857045256463923468775944877723831073218948735316969800684547536389344549931456857234306842372788643144370170015431494005792115059852604376019742040737720145831855341361995847454762357088678899180062704532000519408988445258760142165454104557986566507437171014234130588907895586535673103026294670410052684946543540355295153040713047596704353948168657913426604838668582082688505569615845354438639297748571125719945947883870935481915168118357450909437162890949276124288629273158626408730136153353280259385734094248099908877393332627830019602495378740189414275791739220123642063963148205857703085745460786497856110396863143452962185817050131451659771071779171468538379804253272573761890205034195675788656368202533040838395434243520115268109258521563259069746861504072033382067677548531381312853098367831348608517017347561078932501869038526817662345324458956129880592307734774686126383765519554521082281355928596367373896420049772278195723106268205519834478036673827492711851824231074849054234160240213942064673753130040021561496201, + 477381706395942701152074095578632486629565400458439476605265085853794121036702612260159616584121387309492215289565364823820329641787576027356541944084504070937525199582998228494161581256587963350479182569767709073476305942938578516914185238354982945951325610464183760057011556336116027667431478443971789852497566022190931964624926914512000465438808202901732238917670859079331357158287446481486109341772535642821404724625886765680916122532309926171425411343129633761470730490722435328973775404176016783739955436887938755254368532747248553601029668098763389748002919821495769996090735951060509426001668094204167013619340151559257016228800996225376949328480285921295583758343588892868414107256524587102802726669931221977934082695445776450539968355018778177567062955955188598370628274906129902341525667948146220455560650547385726862123568732001996709039776914328180353694837345124024464856436018138531057521237527151154874694659679915931307604482959674167927057989516514567590062270287113788435548631219164690228588947375243868674913030414096170014455884449983476702938473784682164922729359739421419438500787506002570332539986745630166359816334300274692876831789517660550946290972807224515579551609831535687760126827024718122063108706599), 351666562595755180375395684706241055066156015118305238714672681051882280187504041643434000791814441548607213636968471872699749514579264747751265631272256072725451071040601318567317130676266378472799425651993837557182657388293299120738132040687844779805705782033358582690112156036725659897429182523487027733035393136127607866012534194708593248355973043622949956480835065663676049584885243751590721741501965828757835520710448143589654198570646114663285241248290713467857410885600973553990582698560020712556891679552160547216847450959753723375562391525266281121596206287835239825464988412752920851291059488855778730214384761750487421888963628985845627716345194071713463878260961723623247223927256636464995367615914339908375807571549256908577125462826282135037163236879694999772105827399413764752262353954388137128091790174996148478228118409615917295349567618090677194660136786354642358341440475271809799562062575133857219513963659279640385931136925337147793582596685284559585465388622433797482322409875254412068070757284707921223037714540415540426945620781055610759002438036137835981012468827444588505213686787128969359012972104378460526475214473144375243797989638951510244270960646393807997876101642432170306423462852210882508497178399, 25135373776665590901202336545666836840803391456241601649197796217462555674052551470602221560430959564950903058760936416369952872220340695429584839910539112417172641186658957618681049568598438406515601629945861509808185343104246257658988353826830801833070838727357392230011787930325906736489581750024881433299826206439672753310114100220662748513681137812457302883579006216830084552049499018274245345348857361546260882853255668574117727827869922237413735566854945952091470823515266658679062817428979342500513620275531312300114575338687577827028450767856524439798014817991240510086446185465180093752648368250982692996851, 20678485756120477969749679171411892295363660397911095536909078058504743163718110463975943096121495385121226766215138672406087647843042984392942673880078680348165649479590165596137059916732118274875699928110613763860604584697412776630385407698849636163585027765534352995283408392656841447656433417025991247442767235071030016493820494123404672276837056547392384047230316759182798179296559194938230590081605300708541927122089496849298160531622588496007433560523950635471318918140715059942293286734964890852647775755004955456829006947025556582805868127595216838587483482482814544235364358121943295803510671636196385576851 +klucz_publiczny_RSA,klucz_prywatny_RSA, p, q = genRSA() +print(klucz_publiczny_RSA, klucz_prywatny_RSA, p, q) +N, e = klucz_publiczny_RSA +d = klucz_prywatny_RSA +m = "Thats my Kung Fu".encode("ASCII") +c = szyfrowanie_RSA_OAEP(N, e, m) +print("szyfrgr", c) +m = deszyfrowanie_RSA_OAEP(N, d, c) +print(m) +m = deszyfrowanie_RSA_OAEP_efektywne(N, d, c, p, q) +print(m) + diff --git a/serwer.py b/serwer.py new file mode 100644 index 0000000..4e32e46 --- /dev/null +++ b/serwer.py @@ -0,0 +1,28 @@ +# https://realpython.com/python-sockets/ +# echo-server.py +import socket + +PORT = 65432 # Port to listen on (non-privileged ports are > 1023) +ip_info = socket.getaddrinfo(socket.gethostname(), PORT) +# print(ip_info) +HOST = ip_info[-1][-1][0] + +print(HOST, ":", PORT) + +klucz_publiczny_DSA, klucz_prywatny_DSA = (126220152782999491712146716573647923575210663342203877875997463151103734117618780085961998496900968641688295271738389523168262437046367952410100230715977561698699865420228930481833546803155826687224437601550687821059803843460614018330735329864730711512369415813709177511423225057391814747172616206699791431113, 1026153776632400528836961826077414494924816203371, 33135294496110223909298149780807071663246150710874084366253067988796622596843824622279842916377597978486097816392781318387311279773566894876369811406237208448656803682244786284714051489351162528336310611509464319257937304463246532853715133677606472539203807274116025362212599140301963520366587373345549232664, 57789326082328055343244183952945963065038001008054371988423611501774965584951836084636408462704147650194354237953178434916234787575914934345509256412623906774868805317306029570637051066904576874737549979887847806955662502738986630454336931791238784800404714101190106940899556139200869987149012959023189160975) 601201094732353224640534306619895007746271908982 +p, q, g, y = klucz_publiczny_DSA +x = klucz_prywatny_DSA + +with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind((HOST, PORT)) + s.listen() + conn, addr = s.accept() + conn.send(b"klucz publiczny") + conn.sendall(klucz_publiczny_DSA) + with conn: + print(f"Connected by {addr}") + while True: + data = conn.recv(1024) + if not data: + break + conn.sendall(data)