Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
7 changes: 7 additions & 0 deletions lab2/consts.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"m": 8,
"pi": [0.2148, 0.3672, 0.2305, 0.1875],
"sequence_cpp": "sequence_cpp.txt",
"sequence_java": "sequence_java.txt",
"result": "result.json"
}
24 changes: 24 additions & 0 deletions lab2/gen_cpp.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#include <iostream>
#include <random>
#include <bitset>
#include <fstream>

void generate_bit_sequence() {
std::random_device rd;
std::mt19937_64 gen(rd());
std::uniform_int_distribution<int> dist(0, 1);

std::bitset<128> bits;
for (int i = 0; i < 128; ++i) {
bits[i] = dist(gen);
}

std::ofstream output_file("sequence_cpp.txt");
output_file << bits;
output_file.close();
}

int main() {
generate_bit_sequence();
return 0;
}
13 changes: 13 additions & 0 deletions lab2/gen_java.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import java.io.FileWriter;
import java.io.IOException;

public class Main {
public static void main(String[] args) {
StringBuilder bits = new StringBuilder(128);
for (int i = 0; i < 128; i++) {
bits.append((int) (Math.random() * 2));
}
String sequence = bits.toString();
System.out.println(sequence);
}
}
27 changes: 27 additions & 0 deletions lab2/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from tests import frequency_bit_test, identical_consecutive_bits_test, longest_sequence_of_ones_test
from work_with_files import read_file, read_json, write_json


def main():
try:
constants = read_json('consts.json')

sequence_cpp = read_file(constants['sequence_cpp'])
sequence_java = read_file(constants['sequence_java'])

stats = {
"C++ frequency bit test": frequency_bit_test(sequence_cpp),
"Java frequency bit test": frequency_bit_test(sequence_java),
"C++ identical bit sequence": identical_consecutive_bits_test(sequence_cpp),
"Java identical bit sequence": identical_consecutive_bits_test(sequence_java),
"C++ longest run of ones": longest_sequence_of_ones_test(sequence_cpp,constants['pi'],constants['m']),
"Java longest run of ones": longest_sequence_of_ones_test(sequence_java,constants['pi'],constants['m'])
}

write_json(constants['result'], stats)

except Exception as e:
print(e)

if __name__ == '__main__':
main()
8 changes: 8 additions & 0 deletions lab2/result.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"C++ frequency bit test": 0.8596837951986662,
"Java frequency bit test": 0.4795001221869535,
"C++ identical bit sequence": 0.2899841563937249,
"Java identical bit sequence": 0.39923839789091575,
"C++ longest run of ones": 0.26745460619217515,
"Java longest run of ones": 0.21815226058275772
}
1 change: 1 addition & 0 deletions lab2/sequence_cpp.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
11010011110110000011000011011001010000101001001000001100111101111101001011100011111011110111010110000011101100110000000100111011
1 change: 1 addition & 0 deletions lab2/sequence_java.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
10011101011001000111111110010010101100000100011011110011110001110001010000011111000110001100001110110001000110100010001001010010
80 changes: 80 additions & 0 deletions lab2/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import math

from scipy.special import gammainc


def frequency_bit_test(sequence: str) -> float:
"""
Frequency bit test
:param sequence: bit sequence
:return: p-value
"""
n = len(sequence)
x = 0
for i in sequence:
match i:
case '1':
x += 1
case '0':
x += -1

s_n = abs(x) / math.sqrt(n)
p_value = math.erfc(s_n / math.sqrt(2))
return p_value


def identical_consecutive_bits_test(sequence: str) -> float:
"""
Test for identical consecutive bits
:param sequence: bit sequence
:return: p-value
"""
n = len(sequence)
zeta = sequence.count('1') / n

if abs(zeta - 0.5) >= (2 / math.sqrt(n)):
return 0.0
else:
v_n = sum(1 for i in range(n - 1) if sequence[i] != sequence[i + 1])
p_value = math.erfc(abs(v_n - 2 * n * zeta * (1 - zeta)) / (2 * math.sqrt(2 * n) * zeta * (1 - zeta)))
return p_value


def longest_sequence_of_ones_test(sequence: str, pi: list, m: int) -> float:
"""
Test for the longest sequence of ones in a block
:param sequence: bit sequence
:param pi: list of probabilities
:param m: block size
:return: p-value
"""
v = [0, 0, 0, 0]

blocks = [sequence[i:i + m] for i in range(0, len(sequence), m)]

for block in blocks:
counter = 0
ones_count = 0

for i in block:
if i == '1':
counter += 1
ones_count = max(ones_count, counter)
else:
counter = 0
match ones_count:
case 0 | 1:
v[0] += 1
case 2:
v[1] += 1
case 3:
v[2] += 1
case _:
v[3] += 1

chi_square = 0
for i in range(0, 4):
chi_square += (((v[i] - 16 * pi[i]) ** 2) / (16 * pi[i]))

p_value = gammainc(3 / 2, chi_square / 2)
return p_value
51 changes: 51 additions & 0 deletions lab2/work_with_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import json


def read_file(file_name: str) -> str:
"""
Reads the contents of the file
:param file_name: file name
:return: file contents
"""
try:
with open(file_name, 'r', encoding='utf-8') as file:
return file.read()
except FileNotFoundError:
raise FileNotFoundError(f"File not found")
except IOError:
raise IOError(f"Error reading file")
except Exception as e:
raise Exception("Error: {e}")


def read_json(file_name: str) -> dict:
"""
Reads the contents of a json file
:param file_name: file name
:return: dictionary
"""
try:
with open(file_name, 'r', encoding='utf-8') as file:
return json.load(file)
except FileNotFoundError:
raise FileNotFoundError(f"File not found")
except IOError:
raise IOError(f"Error reading file")
except Exception as e:
raise Exception("Error: {e}")


def write_json(file_name: str, text:float)->None:
"""
Writes the content to a json file
:param file_name: file name
:param text: text
:return: None
"""
try:
with open(file_name, 'w', encoding='utf-8') as file:
json.dump(text, file, ensure_ascii=False, indent=4)
except IOError:
raise IOError(f"Couldn't write to a file")
except Exception as e:
raise Exception("Error: {e}")
80 changes: 80 additions & 0 deletions lab_3/asymmetric_cripto.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey


class AsymmetricEncryption:
""" Класс для асимметричного шифрования с использованием алгоритма RSA """

@staticmethod
def generate_rsa_keys() -> tuple[RSAPrivateKey, RSAPublicKey]:
"""
Генерирует пару RSA ключей
:return: кортеж из приватного и публичного ключей
"""
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
return private_key, private_key.public_key()

@staticmethod
def serialization_asymmetric_public_key(public_key: RSAPublicKey) -> bytes:
"""
Сериализует публичный RSA ключ в PEM формат
:param public_key: публичный ключ
:return: публичный ключ в PEM формате
"""
pem_public_key = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
return pem_public_key

@staticmethod
def serialization_asymmetric_private_key(private_key: RSAPrivateKey) -> bytes:
"""
Сериализует приватный RSA ключ в PEM формат
:param private_key: приватный ключ
:return: приватный ключ в PEM формате
"""
pem_private_key = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
return pem_private_key

@staticmethod
def rsa_encrypt(public_key: RSAPublicKey, data: bytes) -> bytes:
"""
Шифрует данные
:param public_key: публичный ключ
:param data: данные
:return: зашифрованные данные
"""
return public_key.encrypt(
data,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)

@staticmethod
def rsa_decrypt(private_key: RSAPrivateKey, encrypted_data: bytes) -> bytes:
"""
Расшифровывает данные
:param private_key: приватный ключ
:param encrypted_data: зашифрованные данные
:return: расшифрованные данные
"""
return private_key.decrypt(
encrypted_data,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
1 change: 1 addition & 0 deletions lab_3/decrypted_text.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
У него в пятнадцати верстах от постоялого дворика хорошее имение в двести душ, или, как он выражается с тех пор, как размежевался с крестьянами и завел «ферму», — в две тысячи десятин земли. Отец его, боевой генерал 1812 года, полуграмотный, грубый, но не злой русский человек, всю жизнь свою тянул лямку, командовал сперва бригадой, потом дивизией и постоянно жил в провинции, где в силу своего чина играл довольно значительную роль. Николай Петрович родился на юге России, подобно старшему своему брату Павлу, о котором речь впереди, и воспитывался до четырнадцатилетнего возраста дома, окруженный дешевыми гувернерами, развязными, но подобострастными адъютантами и прочими полковыми и штабными личностями. Родительница его, из фамилии Колязиных, в девицах Agathe, а в генеральшах Агафоклея Кузьминишна Кирсанова, принадлежала к числу «матушек-командирш», носила пышные чепцы и шумные шелковые платья, в церкви подходила первая ко кресту, говорила громко и много, допускала детей утром к ручке, на ночь их благословляла, — словом, жила в свое удовольствие. В качестве генеральского сына Николай Петрович — хотя не только не отличался храбростью, но даже заслужил прозвище трусишки — должен был, подобно брату Павлу, поступить в военную службу; но он переломил себе ногу в самый тот день, когда уже прибыло известие об его определении, и, пролежав два месяца в постели, на всю жизнь остался «хроменьким». Отец махнул на него рукой и пустил его по штатской. Он повез его в Петербург, как только ему минул восемнадцатый год, и поместил его в университет. Кстати, брат его о ту пору вышел офицером в гвардейский полк. Молодые люди стали жить вдвоем, на одной квартире, под отдаленным надзором двоюродного дяди с материнской стороны, Ильи Колязина, важного чиновника.
Binary file added lab_3/encrypted_symmetric_key.bin
Binary file not shown.
Loading