1

The function ConvertToInt(message) should convert a text message to an integer number so ciphertext in RSA can be produced using the formula M^e mod n. Here M is the message that must be encoded into a single number. Instead, my following function ConvertToInt returns an array with elements each of which is the ASCII value of the characters. So the result becomes a character by character encryption instead of a string.

Which is the proper way to convert the message to an integer and calculate the proper RSA encrypted result?

Here is my code:

def ConvertToInt(message):
    l = len(message)
    arra = []
    i = 0
    while(i<l):
        j=ord(message[i])
        arra.append(j)
        i += 1
    return arra

def mod_ex(b, k, m):

    i = 1
    j = 0
    while(j<=k):
        b = (b*i) % m
        i = b
        j += 1
    return b
def PowMod(s,modulo,exponent):

    bin_e = bin(exponent)
    bin_e = bin_e [::-1]
    ln = len(bin_e)
    result = 1
    slen = len(s)
    for i in range(0,slen,+1):
        for j in range(0,ln-2,+1):
            if(bin_e[j]=='1'):
                result *= mod_ex(s[i],j,modulo)
        s[i] = result%modulo
        result = 1
    return s

def Encrypt(message, modulo, exponent):

  s = ConvertToInt(message)
  return PowMod(s, modulo, exponent)

x = Encrypt("Aa",473,17)
print(x)
Sazzad
  • 176
  • 1
  • 9
  • 3
    "and I got this wrong" is not a proper error, what problem do you experience? – Maarten Bodewes Jul 25 '20 at 18:40
  • ops! I should clear it more.. What is the proper way of encoding text messages in case of RSA encryption so as to apply M^e mod n? and what would be the output looks like in integer after encryption. I desperately needed an example of input-output so to do like that.. – Sazzad Jul 26 '20 at 19:09
  • If my input is "Attack" the array would return "285, 19, 19, 213, ...." But if I return this as a string "2851919213...." then it wouldn't be possible to decrypt. But if I return as "285019019213.." now I can decrypt (n-1 = 472 = 3, take 3 by 3 digits to decrypt) But again if n is too large there is lots of 0 in the encrypted string. So what is the proper way – Sazzad Jul 26 '20 at 19:17

2 Answers2

0

Here is a ConvertToInt function that effectively calculated a number out of a string which can be used in RSA Encryption, cz RSA encryption must need a number to operate.

def ConvertToInt(message):
grd = 1
num = 0
message = message [::-1]
for i in range(0,len(message),+1):
    num = num+ord(message[i])*grd
    grd *= 256
return num

Get the full RSA Code in python here:

Sazzad
  • 176
  • 1
  • 9
-1

I think it depends on your application. But, as we are using encryption for communicating often, it is better to use Encoding that is more compatible with communication systems. For example, Base64 is one of the popular encodings used for encryption schemes(either Symmetric or Asymmetric).

SpongeBob
  • 383
  • 3
  • 16