Home Backend Development Python Tutorial python implements RSA algorithm

python implements RSA algorithm

Apr 19, 2018 pm 05:02 PM
python

The example in this article describes the implementation of RSA algorithm in python. Share it with everyone for your reference, the details are as follows:

1. Basic number theory

1. Reciprocal prime relationship

  • If two positive integers have no other common factors except 1, we call the two numbers coprime relationship (coprime). For example, 15 and 32 have no common factors, so they are mutually prime. This shows that even non-prime numbers can form a coprime relationship.

2. Euler function

  • Definition: given any positive integer n, Among the positive integers less than or equal to n, how many are relatively prime to n? (For example, among 1 to 8, how many numbers are in a mutually prime relationship with 8?) The method of calculating this value is called Euler function, represented by φ(n).

  • How to find the Euler function and its properties:

  1. For the prime number p, φ(p)=p-1, For two prime numbers p, q, φ(pq)=pq-1, The Euler function is the product sexual function, but not a complete product function.

  2. For the prime power decomposition of a positive integer N N=P1^q1*P2^q2* ...*Pn^qn, then φ(N)=N*(1-1/P1)*(1-1/P2)*…*(1-1/Pn).

  3. Except N=2, φ(N) are all even numbers.

  4. If n can be decomposed into two coprime The product of integers, n = p1 × p2, then φ(n) = φ(p1p2) = φ(p1)φ(p2)

2. RSA encryption

The first step is to randomly select two unequal prime numbers p and q.

Alice chose 61 and 53. (In practical applications, the larger these two prime numbers are, the more difficult it is to crack.)

The second step is to calculate the product n of p and q.

Alice multiplies 61 and 53.

 n = 61×53 = 3233

The length of n is the key length. 3233 written in binary is 110010100001, which has 12 digits in total, so the key is 12 digits. In practical applications, the RSA key is generally 1024 bits, and in important cases it is 2048 bits.

The third step is to calculate the Euler function φ(n) of n.

According to the formula:

 φ(n) = (p-1)(q-1)

Alice calculated that φ(3233) is equal to 60×52, which is 3120.

The fourth step is to randomly select an integer e, the condition is 1< e < φ(n), and e and φ(n) are relatively prime.

Alice was between 1 and 3120 and randomly selected 17. (In practical applications, 65537 is often chosen.)

The fifth step is to calculate the modular inverse element d of e with respect to φ(n).

The so-called "modular inverse element" means that there is an integer d that can make the remainder of ed divided by φ(n) equal to 1.

 ed ≡ 1 (mod φ(n))

This formula is equivalent to

 ed - 1 = kφ(n )

So, finding the modular inverse element d is essentially solving the following linear equation of two variables.

 ex φ(n)y = 1

It is known that e=17, φ(n)=3120,

 17x 3120y = 1

This equation can be solved using the "extended Euclidean algorithm", and the specific process is omitted here. In summary, Alice calculates a set of integer solutions as (x,y)=(2753,-15), which is d=2753.

Now all calculations are completed.

The sixth step is to encapsulate n and e into public keys, and encapsulate n and d into private keys.

In Alice’s example, n=3233, e=17, d=2753, so the public key is (3233,17) and the private key is (3233, 2753).

In actual applications, the data of public and private keys are expressed in ASN.1 format (example).

7. Reliability of RSA algorithm

Looking back at the above key generation steps, a total of six numbers appear:

p
q
n
φ(n)
e
d

Of these six numbers, two are used in the public key (n and e), the remaining four numbers are not public. The most critical one is d, because n and d form the private key. Once d is leaked, it means the private key is leaked.

So, is it possible to deduce d when n and e are known?

  (1) ed≡1 (mod φ(n)). Only by knowing e and φ(n) can we calculate d.

 (2)φ(n)=(p-1)(q-1). Only by knowing p and q can we calculate φ(n).

 (3)n=pq. Only by factoring n can we calculate p and q.

Conclusion: If n can be factored, d can be calculated, which means the private key has been cracked.

However, factoring large integers is a very difficult thing. At present, apart from brute force cracking, no other effective method has been found. Wikipedia writes:

"The difficulty of factoring a very large integer determines the reliability of the RSA algorithm. In other words, the more difficult it is to factor a very large integer, the more reliable the RSA algorithm is." .

If someone finds a fast factoring algorithm, then the reliability of RSA will be extremely reduced. But the possibility of finding such an algorithm is very small. Today it is only possible with short RSA keys Being cracked by brute force. As of 2008, there is no reliable way to attack the RSA algorithm in the world.

As long as the key length is long enough, information encrypted with RSA cannot actually be cracked."

For example, you can factor 3233 (61×53), but you cannot factor the following integer.

12301866845301177551304949
58384962720772853569595334
79219732245215172640050726
36575187452021997864 693899
56474942774063845925192557
32630345373154826850791702
61221429134616704292143116
022212404792747377940 80665
 351419597459856902143413

It is equal to the product of two prime numbers like this:

 33478071698956898786044169
 84821269081770479498371376
 85689124313889828837938780
022876147 11652531743087737
814467999489
# 76426760322838157396665112
79233373417143396810270092
798736308917

In fact, this is probably the largest integer that humans have factored into (232 decimal digits, 768 binary digits). Larger factorizations have not been reported, so the longest RSA key that has been cracked is 768 bits.

8. Encryption and decryption

With the public key and key, you can encrypt and decrypt.

(1) Encryption requires public key (n,e)

Assuming that Bob wants to send encrypted information m to Alice, he must use Alice’s Public key (n,e) encrypts m. It should be noted here that m must be an integer (the string can take an ascii value or unicode value), and m must be less than n.

The so-called "encryption" is to calculate c of the following formula:

me ≡ c (mod n)

爱利Silk's public key is (3233, 17), and Bob's m is assumed to be 65, then the following equation can be calculated:

 6517 ≡ 2790 (mod 3233)

So, c equals 2790, and Bob sends 2790 to Alice.

(2) Decryption requires the private key (n,d)

After Alice gets the 2790 sent by Bob, she uses her own private key (3233 , 2753) for decryption. It can be proved that the following equation must be true:

cd ≡ m (mod n)

That is to say, c divided by the dth power Let the remainder of n be m. Now, c is equal to 2790 and the private key is (3233, 2753). Then, Alice calculates

 27902753 ≡ 65 (mod 3233)

Therefore, Alice knows that Bob’s original text before encryption is 65.

At this point, the entire process of "encryption-decryption" is completed.

We can see that if d is not known, there is no way to find m from c. As mentioned before, to know d, you must decompose n, which is extremely difficult to do, so the RSA algorithm ensures communication security.

You may ask, the public key (n,e) can only encrypt an integer m less than n, so what should you do if you want to encrypt an integer greater than n? There are two solutions: one is to divide the long message into several short messages and encrypt each segment separately; the other is to first choose a "symmetric encryption algorithm" (such as DES) and use the key of this algorithm Encrypt the message and then use the RSA public key to encrypt the DES key.

9. Proof of private key decryption

Finally, we will prove why m can be obtained correctly by decrypting with private key. That is to prove the following formula:

 cd ≡ m (mod n)

Because, according to the encryption rules

 me ≡ c (mod n)

So, c can be written in the following form:

 c = me - kn

Substituting c into the decryption rule we want to prove:

 (me - kn)d ≡ m (mod n)

It is equivalent to verification

 med ≡ m (mod n)

Because

 ed ≡ 1 (mod φ(n))

So

 ed = hφ(n) 1

Substitute ed into:

mhφ(n) 1 ≡ m (mod n)

Next, prove the above formula in two cases.

(1) m and n are relatively prime.

According to Euler’s theorem, at this time

 mφ(n) ≡ 1 (mod n)

Get

 (mφ(n))h × m ≡ m (mod n)

Original formula Get proven.

(2) m and n are not mutually prime.

At this time, since n is equal to the product of prime numbers p and q, m must be equal to kp or kq.

Take m = kp as an example. Considering that k and q must be mutually prime at this time, according to Euler’s theorem, the following formula holds:

 (kp)q-1 ≡ 1 (mod q)

further get

 [(kp)q-1] h(p-1) × kp ≡ kp (mod q)

ie

 (kp)ed ≡ kp (mod q)

Rewrite it into the following equation

 (kp)ed = tq kp

At this time, t must be divisible by p, that is, t=t'p

 (kp)ed = t'pq kp

because m =kp, n=pq, so

med ≡ m (mod n)

The original formula is proved.



python implementation

Powerful python has a dedicated implementation The pycrypto third-party library of cryptographic technology. However, if we want to implement rsa, we do not need such a sophisticated tool. We only need to load a third-party library of rsa.

Show you the code, NO bb:

#实现公钥加密 RSA

import rsa
import time
#计算下时间

start_time = time.time()
key = rsa.newkeys(1024) #数字代表 p * q 产生的存储空间 bit 大小, 也就是密文长度,数字越大,时间越长
privateKey = key[1]
publicKey = key[0]
#print(privateKey)
#print(publicKey)
end_time = time.time()
print("make a key:", end_time - start_time)
#产生公钥和私钥

message = &#39;Taiyuan is the best city of China.&#39;
message = message.encode()

cryptedMessage = rsa.encrypt(message, publicKey)
print("crypted:", cryptedMessage)
print("length of cryptedMessage:", len(cryptedMessage))
# 加密的过程

decrypetdMessage = rsa.decrypt(cryptedMessage, privateKey)
print("decrypet:", decrypetdMessage)
# 解密的过程

now_time = time.time()
print("crypt and decrypt:", now_time - end_time)
Copy after login


Related recommendations:

Take you to thoroughly understand the principle of RSA algorithm

RSA encryption algorithm

25 lines of code to implement the complete RSA algorithm

Detailed explanation of RSA algorithm and C language implementation

The above is the detailed content of python implements RSA algorithm. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles