Skip to content
Open
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
174 changes: 174 additions & 0 deletions lab_3/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

# Ruff stuff:
.ruff_cache/

# PyPI configuration file
.pypirc
88 changes: 88 additions & 0 deletions lab_3/asymmetric_cipher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import os
from typing import Tuple
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey, RSAPrivateKey
from cryptography.hazmat.primitives import serialization, hashes


def generate_rsa_keypair() -> Tuple[RSAPrivateKey, RSAPublicKey]:
"""
Generates a new RSA private-public key pair.

:returns: A tuple containing the RSA private key and corresponding public key.
"""
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
return private_key, private_key.public_key()


def encrypt(key: bytes, public_key: RSAPublicKey) -> bytes:
"""
Encrypts data using the given RSA public key with OAEP padding.

:param key: Symmetric key or data to encrypt.
:param public_key: RSA public key used for encryption.
:returns: Encrypted data as bytes.
"""
return public_key.encrypt(
key,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)


def decrypt(encrypted_key: bytes, private_key: RSAPrivateKey) -> bytes:
"""
Decrypts data using the given RSA private key with OAEP padding.

:param encrypted_key: Encrypted data to decrypt.
:param private_key: RSA private key used for decryption.
:returns: Decrypted data as bytes.
"""
return private_key.decrypt(
encrypted_key,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)


def serialize_public_key(public_key: RSAPublicKey) -> bytes:
"""
Serializes an RSA public key to PEM format.

:param public_key: RSA public key to serialize.
:returns: Serialized public key in PEM format.
"""
return public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)


def serialize_private_key(private_key: RSAPrivateKey) -> bytes:
"""
Serializes an RSA private key to PEM format without encryption.

:param private_key: RSA private key to serialize.
:returns: Serialized private key in PEM format.
"""
return private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)


def load_private_key(data: bytes) -> RSAPrivateKey:
"""
Loads an RSA private key from PEM-encoded data.

:param data: PEM-encoded private key bytes.
:returns: Deserialized RSA private key object.
"""
return serialization.load_pem_private_key(data, password=None)
99 changes: 99 additions & 0 deletions lab_3/data.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
Вы помните,
Вы всё, конечно, помните,
Как я стоял,
Приблизившись к стене,
Взволнованно ходили вы по комнате
И что-то резкое
В лицо бросали мне.
Вы говорили:
Нам пора расстаться,
Что вас измучила
Моя шальная жизнь,
Что вам пора за дело приниматься,
А мой удел —
Катиться дальше, вниз.
Любимая!
Меня вы не любили.
Не знали вы, что в сонмище людском
Я был как лошадь, загнанная в мыле,
Пришпоренная смелым ездоком.
Не знали вы,
Что я в сплошном дыму,
В развороченном бурей быте
С того и мучаюсь, что не пойму —
Куда несет нас рок событий.
Лицом к лицу
Лица не увидать.
Большое видится на расстоянье.
Когда кипит морская гладь —
Корабль в плачевном состоянье.
Земля — корабль!
Но кто-то вдруг
За новой жизнью, новой славой
В прямую гущу бурь и вьюг
Ее направил величаво.
Ну кто ж из нас на палубе большой
Не падал, не блевал и не ругался?
Их мало, с опытной душой,
Кто крепким в качке оставался.
Тогда и я,
Под дикий шум,
Но зрело знающий работу,
Спустился в корабельный трюм,
Чтоб не смотреть людскую рвоту.
Тот трюм был —
Русским кабаком.
И я склонился над стаканом,
Чтоб, не страдая ни о ком,
Себя сгубить
В угаре пьяном.
Любимая!
Я мучил вас,
У вас была тоска
В глазах усталых:
Что я пред вами напоказ
Себя растрачивал в скандалах.
Но вы не знали,
Что в сплошном дыму,
В развороченном бурей быте
С того и мучаюсь,
Что не пойму,
Куда несет нас рок событий…
Теперь года прошли.
Я в возрасте ином.
И чувствую и мыслю по-иному.
И говорю за праздничным вином:
Хвала и слава рулевому!
Сегодня я
В ударе нежных чувств.
Я вспомнил вашу грустную усталость.
И вот теперь
Я сообщить вам мчусь,
Каков я был,
И что со мною сталось!
Любимая!
Сказать приятно мне:
Я избежал паденья с кручи.
Теперь в Советской стороне
Я самый яростный попутчик.
Я стал не тем,
Кем был тогда.
Не мучил бы я вас,
Как это было раньше.
За знамя вольности
И светлого труда
Готов идти хоть до Ла-Манша.
Простите мне…
Я знаю: вы не та —
Живете вы
С серьезным, умным мужем;
Что не нужна вам наша маета,
И сам я вам
Ни капельки не нужен.
Живите так,
Как вас ведет звезда,
Под кущей обновленной сени.
С приветствием,
Вас помнящий всегда
Знакомый ваш
Сергей Есенин.
Binary file added lab_3/encrypted_data.txt
Binary file not shown.
4 changes: 4 additions & 0 deletions lab_3/encrypted_key.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/�S
pI
�����H�˻{֍9;3mUBfOa�9�����U2��A�zDDQp��[�� >g(1���UJrXFl��2��W-�����|����1�R9ztw��l�祷M��W7.'�z�f�٢������U���XI<+���лJ��z�I�׫F��s��]'.���{`4kwfn縃׈Ro9��"���ȍ4���M��7X|�x� �pZ\��}`��1���s��/ ~�83��
���^��
Loading