Reputation:
I encoded an RSA decryption and encryption functions, like following:
def encrypt(m,e,n):
return pow(int(m.encode('hex'), 16), int(e, 10), int(n, 10) )
def decrypt(c,d,n):
p = pow(int(c, 10), int(d, 10), int(n, 10))
return hex(p)[2:].decode('hex')
When I want to use these functions like following, everything is ok
e = "65537"
n = "21856687"
d = "12096993"
m = "TH"
c = encrypt(m,e,n)
print decrypt(str(c),d,n)
But when I change the message to be encrypted (in this case m) I get wrong answer, actually they seem like garbage value. What I mean by changing the message is trying a message which has a length longer than 2, like the following.
e = "65537"
n = "21856687"
d = "12096993"
m = "THIS IS A HIDDEN MESSAGE"
c = encrypt(m,e,n)
print decrypt(str(c),d,n)
Upvotes: 0
Views: 408
Reputation: 33108
The message bytes, interpreted as a Big Endian number, must be less than n
for it to roundtrip. You'll need to crank up p
and q
or shrink your message. (Your "garbage" is an equivalent message modulo n, it should roundtrip just fine)
And while this is hopefully homework, I feel compelled to state that raw (unpadded) RSA is a bad idea, and DIY RSA is a bad idea. The former is susceptible to a variety of data attacks, and the latter likely has timing vulnerabilities leading to private key compromise.
Upvotes: 1