So I’m trying to encrypt my own message but its coming out in symbols instead of letters. Not sure What i’m overlooking. Not sure what is causing this issue. If anyone can give be a great direction to this issue, that would be very helpful. I think it has to do something with my Private Keys.
Here is my code below
def Euclidean_Alg(a, b):
while b != 0:
a, b = b, a % b
return a
def EEA(a, b):
s0, s1 = 1, 0
t0, t1 = 0, 1
while b != 0:
q = a // b
a, b = b, a % b
s0, s1 = s1, s0 - q * s1
t0, t1 = t1, t0 - q * t1
return a, (s0, t0)
def Find_Public_Key_e(p, q):
n = p * q
phi_n = (p - 1) * (q - 1)
e = 2
while e < phi_n:
if Euclidean_Alg(e, phi_n) == 1 and e != p and e != q:
break
e += 1
return n, e
def Find_Private_Key_d(e, p, q):
phi_n = (p - 1) * (q - 1)
gcd, (s, t) = EEA(e, phi_n)
if gcd != 1:
raise ValueError("e and phi(n) are not coprime, so the modular inverse does not exist")
d = t % phi_n
return d
def Convert_Text(_string):
return [ord(char) for char in _string]
def Convert_Num(_list):
return ''.join(chr(i) for i in _list)
def Encode(n, e, message):
integer_list = Convert_Text(message)
cipher_text = [pow(char, e, n) for char in integer_list]
return cipher_text
def Decode(n, d, cipher_text):
decrypted_values = [pow(char, d, n) for char in cipher_text]
original_message = Convert_Num(decrypted_values)
return original_message
if __name__ == "__main__":
p = 61
q = 53
n, e = Find_Public_Key_e(p, q)
d = Find_Private_Key_d(e, p, q)
print(f"Public Key (n, e): ({n}, {e})")
print(f"Private Key (n, d): ({n}, {d})")
# Encode the message
message = "What superpower would you have if you had the choice of one?"
cipher_text = Encode(n, e, message)
print("Encoded message:", cipher_text)
# Decode the message
decoded_message = Decode(n, d, cipher_text)
print("Decoded message:", decoded_message)
Here is what is coming out after running it:
Public Key (n, e): (3233, 7)
Private Key (n, d): (3233, 3)
Encoded message: [1298, 3052, 1818, 1762, 2774, 567, 1297, 96, 3071, 1797, 96, 3183, 863, 3071, 1797, 2774, 863, 3183, 1297, 1877, 2872, 2774, 731, 3183, 1297, 2774, 3052, 1818, 1794, 3071, 2774, 3020, 576, 2774, 731, 3183, 1297, 2774, 3052, 1818, 2872, 2774, 1762, 3052, 3071, 2774, 24, 3052, 3183, 3020, 24, 3071, 2774, 3183, 576, 2774, 3183, 1544, 3071, 2080]
Decoded message: !૾ʋӛөઅࡏజࡏпऋజऋпઅौ˟ŭпઅ૾ʋԊజఁŚŭпઅ૾ʋ˟ӛ૾జͼ૾пఁͼజпŚп̴జ߁
Lonkin_p is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.