2

I'm trying to implement RSA encryption/decryption (a simple implementation of course, so there's no need for nitpicking) and it seems like the numbers (i.e. the keys) are fine, yet the final result is wrong.

Here's the problematic function:

def square_and_mult(base, k, mod):
    b = 1
    for ki in reversed(k):
        if ki == '0':
            b = (b**2) % mod
        else:
            b = ((b**2) * base) % mod
    return b
1

1 Answer 1

3

I suspect something is wrong with your modular exponentiation algorithm. As you're using python you can use the builtin pow(base, exp, mod) to do this, no need to implement it yourself.

In [1]: n = 48961353722289327881

In [2]: e = 7

In [3]: d = 6994479101184233143

In [4]: x = 12345678

In [5]: c = pow(x, e, n)

In [6]: c
Out[6]: 32225547235202030473

In [7]: m = pow(c, d, n)

In [8]: m
Out[8]: 12345678
Sign up to request clarification or add additional context in comments.

2 Comments

More concretely, the issue is in the line for ki in reversed(k): Simply removing the reversed makes it work.
Thanks puzzlepalace!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.