[Math] How to work RSA encryption/decryption

cryptographynumber theoryprime numbers

I need an array populated with characters and integer keys for each, and I want to, using this set, encode messages, and then decode them later on . Essentially I am trying to write RSA algorithm for this. However, the maths of it is what I am still kind of lost on. In order to encode, I would have to encode bits of the input string, and this after reading the corresponding key for each character, M.

     Ciphertext=0

     for i from 1 to length(message) do
         M:= ltable[message[i]] // Read the number that corresponds to the Character
        ciphertext:= ciphertext * ((M^encryptionkey) mod modfactor);//encode the returned number and add to ciphertext
    Loop next
       return ciphertext;

//To Convert all the input message at once, and then encode I have this algorithm
 ** for i from 1 to length(message) do
         M:= ltable[message[i]]//get the number that corresponds to character
        ciphertext:= ciphertext * M;//perform operation to update
    Loop next
       return ((ciphertext^encryptionkey) mod modfactor);**

i.e
Ciphertext = M^e mod n where C is the resulting ciphertext, e is my encryption key and modfactor is the product of my primes.

The code above spews out my input message in an encrypted form. However, when I am to decode to resulting ciphertext, I run into some problem reversing the operations above to get the exact message that was sent as input to my encryption program. Essentially given a String of length 100, I encrypt each character of the input string with the above, but to reverse/decode, I don't seem to be getting the same message.

cipher = cyphertext;
while cipher> 0 do
rest = (cipher ^decryptionkey) mod modfactor
message = concatenate(ntable[rest],message):
wrk = (cipher/rest)/modfactor
End While

Return message

The code/algorithm above does not seem to work. Test primes used are p=263 and q=911, and encryptionkey= 27 How do I accomplish this please?

Best Answer

You're not supposed to encrypt one character at a time! You need to turn an entire message into a single number, and then perform the modulo exponentiation on that plaintext number to get the ciphertext number. Then you do the exponentiation with the private decryption key to reverse the process from the cipher to the plaintext, and then turn that number back into the message.