алгоритм RSA на Python
Доброй ночи всем форумчанам! Мне 14 лет и я начал заниматься программированием на Python ровно полгода назад. В школе взял тему проекта: Шифрование данных с использованием закрытого ключа шифрования. Возникла идея написать шифр RSA. Но вот так не задача, исходные данные, которые необходимо зашифровать не совпадают с полученными после дешифрования. Ломаю голову, не могу понять что сделал не так. Прошу помощи разобраться в чём может быть ошибка (За код сильно не ругайте, писал сам). Делал по алгоритму молодого человека на видео: https://youtu.be/xqPgE-hPIfE. Список b с данными, которые были введены изначально, отличается от дешифрованного списка.
from sympy import randprime, primerange from math import gcd def find_two_primes(): p1 = randprime(1, 100) p2 = randprime(1, 100) while p1 == p2: p2 = randprime(1, 100) return (p1, p2) a = find_two_primes() print(f'(p, q) = ') mod = a[0] * a[1] print(f'mod = ') phi = (a[0] - 1) * (a[1] - 1) print(f'phi = ') spisok = list(primerange(1, phi)) for n in spisok: if gcd(n, phi) == 1: e = n break values = [x for x in range(1, phi + 1)] d = 0 for elem in values: if (int(elem) * e) % phi == 1: d += int(elem) break print(f'e = ') print(f'd = ') open_key = (e, mod) private_key = (d, mod) print(f'open_key = ') print(f'private_key = ') b = list(input()) b = [ord(elem) for elem in b] print(b) for i in range(len(b)): b[i] *= e b[i] %= mod print(b)
Отслеживать
задан 13 фев 2023 в 22:09
Азат Хайруллин Азат Хайруллин
23 4 4 бронзовых знака
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
Ну собственно ошибка в одном месте ‘b[i] *= e’ — вы умножаете элемент на число e , а в алгоритме нужно возводить в степень.
b = list("Hello Wold!") b = [ord(elem) for elem in b] print("Before encrypt:") print(b) for i in range(len(b)): # b[i] *= e # неправильно b[i] = b[i] ** e # нужно - возведение в степень b[i] %= mod print("After encrypt:") print(b) for i in range(len(b)): b[i] = b[i] ** d # и при дешифровке возведение в степень b[i] %= mod print("After decrypt:") print(b)
Ещё замечание — в вашей версии число e — почти всегда будет простым маленьким — 2,3,5,7. Имея эту информацию, злоумышленнику проще будет взломать шифр. Поскольку вы всё равно генерите список простых чисел, выбирайте число из этого списка случайным образом.
# вместо spisok = list(primerange(1, phi)) for n in spisok: if gcd(n, phi) == 1: e = n break # выберите случайный элемент из этого списка n = random.choice(spisok) while gcd(n, phi) != 1: n = random.choice(spisok) else: e = n
Аналогично выбор числа d — вы перебираете числа начиная с 1 — 1,2,3,4 . т.е. d это будет наименьшее число, удовлетворяющее условию. Попробуйте наоборот — от (phi — 1) уменьшать.
Pure Python RSA implementation
Python-RSA is a pure-Python RSA implementation. It supports encryption and decryption, signing and verifying signatures, and key generation according to PKCS#1 version 1.5. It can be used as a Python library as well as on the commandline. The code was mostly written by Sybren A. Stüvel.
Documentation can be found at the Python-RSA homepage.
Download and install using:
pip install rsa
or download it from the Python Package Index.
The source code is maintained at Github and is licensed under the Apache License, version 2.0
Plans for the future
Version 3.4 is the last version in the 3.x range. Version 4.0 will drop the following modules, as they are insecure:
- rsa._version133
- rsa._version200
- rsa.bigfile
- rsa.varblock
Those modules are marked as deprecated in version 3.4.
Furthermore, in 4.0 the I/O functions will be streamlined to always work with bytes on all supported versions of Python.
Version 4.0 will drop support for Python 2.6, and possibly for Python 3.3.
2. Installation¶
Installation can be done in various ways. The simplest form uses pip:
pip install rsa
Depending on your system you may need to use sudo pip if you want to install the library system-wide, or use pip install —user rsa to install the library in your home directory.
Installation from source is also quite easy. Download the source and then type:
python setup.py install
The sources are tracked in our Git repository at GitHub. It also hosts the issue tracker.
2.1. Dependencies¶
Python-RSA is compatible with Python versions 3.5 and newer. The last version with Python 2.7 support was Python-RSA 4.0.
Python-RSA has very few dependencies. As a matter of fact, to use it you only need Python itself. Loading and saving keys does require an extra module, though: pyasn1. If you used pip or easy_install like described above, you should be ready to go.
2.2. Development dependencies¶
In order to start developing on Python-RSA, use Git to get a copy of the source:
git clone https://github.com/sybrenstuvel/python-rsa.git
Use Pipenv to install the development requirements in a virtual environment:
cd python-rsa pipenv install --dev
rsa-python 0.1.1
This module implements the RSA encryption algorithm. Functions included are generate_key_pair(bits) which returns a dictionary containing p, q, phi, public, private, modulus, and the time it took to generate the key pair («time»). encrpyt(message, encryption_key, modulus) to encrypt a message, and decrypt(cipher, decryption_key, modulus) to decrypt a cipher. To install the module, run pip install rsa_python . Below is an example how to use the module.
Подробности проекта
Ссылки проекта
Статистика
Метаданные
Лицензия: MIT License
Автор: Toby Connor-Kebbell
Требует: Python >=3.6