RSA Encryption | 03 | Encrypt Message

Data encryption is acheived using the public key and exponent value. These are known to anyone who wishes to send data to the private key holder.

Import Libraries

In [1]:
import obj
from time import clock

Create super-secret message

In [2]:
# Create secret message
message = 'Don\'t tell my secrets to anyone, please!'

# Save message
obj.save(message, 'data/message')
In [3]:
message
Out[3]:
"Don't tell my secrets to anyone, please!"

Load publicly available key values

In [4]:
keys = obj.load('data/keys')

#Publicly known values
exponent   = keys['exponent']
key_public = keys['key_public']

#Private values are unknown
key_private = 'Unknown'

Define encryption algorithm

Encrypting is a mathematic process that can only be achieved on numeric data. Our text string must be converted to a numeric representation before encryption can occur. Fortunately, computers have always needed numeric representations of text and therefore we have many options to choose from. Instead of creating our own translation system, we will use ASCII for our conversion which handles typical American letters and symbols.

In [5]:
def encrypt(message, key_public, exp):
    
    # Convert message to ASCII
    message_ascii = []
    for i in message:
        message_ascii.append(ord(i))
    
    # Encrypt message
    message_encrypted = []
    for i in message_ascii:
        message_encrypted.append((i**exp) % key_public)
        
    # Return encrypted message
    return message_encrypted

Encrypt message

In [6]:
begin = clock()
message_encrypted = encrypt(message, key_public, exponent)

print('Message encrypted in {:.6} seconds.'.format(clock()-begin))
print('\n')
print(message_encrypted)
Message encrypted in 0.000188 seconds.


[121594, 93357, 61872, 108890, 276169, 192972, 276169, 157025, 224506, 224506, 192972, 129465, 199230, 192972, 139819, 157025, 54924, 25146, 157025, 276169, 139819, 192972, 276169, 93357, 192972, 258683, 61872, 199230, 93357, 61872, 157025, 241873, 192972, 193704, 224506, 157025, 258683, 139819, 157025, 165657]
In [7]:
obj.save(message_encrypted, 'data/message_encrypted')