namespace ra :: RSA
To create a working RSA code, Using namespace ra::random_prime_engine
, Here the link GitHub repo!
The Rivest-Shamir-Adleman (RSA) is an asymmetric encryption algorithm. Asymmetric Encryption is when a box(data) can be locked by one key and unlocked by other. locking key cannot unlock the box and vice-versa. The locking key is the public key and the unlocking key is the private key, Public key is called so because we publicly distribute it, so anyone/everyone would send the user an encrypted msg, and the user can unlock it in private with the private key. By keeping private to the user-self, no hacker can get a method of unlocking it.
https://ra101.hashnode.dev/rsa-encryption-algorithm
-
Private Members:
-
private_key
-
public_key
-
create_key(long seed)
-
Public Members:
-
Constructor
&Constructor(seed)
-
std::size_t decrypt(std::size_t);
-
std::size_t decrypt_with_padding(std::string);
-
Key Getters
-
std::size_t sign(Message message)
-
Other Function within
namespace
but Outsideclass
(All the functions utilizing public key): -
std::size_t encrypt(std::size_t digest, public_key);
-
std::string encrypt_with_padding(std::size_t digest, public_key);
-
bool verify(Message message, size_t digest, public_key)
-
string padding(string)
The seed in the constructor is used in random prime engine
and the logic of the seed argument is as follow,
# pseudo code implemented in python
def constructor(seed=None):
if not seed:
seed = timestamp()
else:
seed = hash(seed)
return create_key(seed)
// Usage
ra::rsa_key_pair k1, k2("127.0.0.1");
I will not get into the mathematics of it all, but in the end, using 2 primary numbers we get
- public key: (n, e)
- private key: (n, d)
(n, e, d) all are integers.
To concatenate these two numbers (n, e/d) let us define a big number BIG_NO
, such that
- n = key / BIG_NO
- e = public_key % BIG_NO
- d = private_key % BIG_NO
#define BIG_NO 100000000000
public_key = n * BIG_NO + e;
private_key = n * BIG_NO + d;
return (digest ** e) % n
return (encrypted_data ** d) % n
#define PAD_SIZE 10
// 12345 -> 0000012345
while (str.length() < PAD_SIZE)
{
str = '0' + str; // add 0 in front of no.
}
return str;
# encrypt each digit
for each_digit in digest:
output = padding(encrypt(each_digit)) + output
return output
# cut the input string in chunks of length PAD_SIZE
# decrypt each chunk to digit and then form a output
for i_chunk in len(encrypted_data)/PAD_SIZE:
i = i_chunk * PAD_SIZE
digit = decrypt(int(encrypted_data[i: i + PAD_SIZE]))
output = digit + output * 10
return output
return decrypt(hash(message))
return ( hash(message) == encrypt(digest, others_public_key) )