Christopher Ek

How RSA Encryption works: With Math & Python implementation

Published 2021-02-2710 min read0 comments

There are three types of encryption, asymmetric, symmetric, and (hash functions. Even though hash functions are one-way functions and not considered encryption). Asymmetric encryption like RSA, Diffie-hellman, and DSA uses a public and a private key. In asymmetric encryption, only the receiver will know the private key. The sender will encrypt the message using the receiver's public key. Symmetric encryption like AES, 3DES, DES use the same key for encryption as for decryption. Hash functions will just scramble the text one way.

RSA is today's standard public-key encryption. The default key length for RSA is between 1,024-4096bits. RSA-768 was a while ago and that's because of refactoring. The security in RSA lies in prime number refactoring. This means if one would come up with a solution/algo that could refactor large prime numbers. RSA would be dead. You can read more about the "factoring problem" here. Disregarding that fact it would take about 300 trillion years for a normal pc to break RSA 2048 with today's methods.

Math Implementation

Explanation

First of all we need to pick two numbers these need to be prime numbers
\(P = 3\) and \(Q = 11\)
Next we have to get \(N\) which will be. \(N = P*Q\) and in this case that would be
\(N=33\).

Next up is \(F\) which is \(F = (P-1) * (Q-1)\) and in this case that would be
\(F=20\)

We also need to pick a new prime number \(E\) that fellow these rules \(1< E < F\) and I will pick \(E=7\)

We now have to find the \(D\) value. Which we do with this rule
\(D * E (mod F) = 1\).

This means that in this case \(D=3\) because 3*7 (Mod 20) = 1. The value of D can be quite hard to find so I wrote some python code to find it.

Now comes the fun part encryption and decryption.
To Encrypt a message we need \(E,N\)
To Decrypt a message we need \(D,N\)

Encryption

To encrypt a message we take the message which in this case in just the integer 13
Message = \(13\)
Encryption = \(message^E(modN)\)
Result = \(13^7(mod33) = 7\)
Encrypted message = \(7\)

Decryption

Encrypted message = \(7\)
Decryption = \(encrypted-message^D(modN)\)
Result = \(7^3(mod33) = 13\)
Decrypted Message = \(13\)
You have now sucessfully encrypted and decrypted using RSA(sort of). P & Q is has to be really long otherwise its not safe. I do not recommend implementing your own RSA encryption. Since most of the time its not keys length that is the problem but the implementation.

Python Implementation

Code

Simple version
Advanced version

Promo Section Heading

You can use this section to promote your side projects etc. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.

image