Path: blob/master/Public Key/RSA/blinding.sage
336 views
import random12def generate_private_params(e=65537, bits=1024):3while 1:4p = random_prime(2^bits, proof=False)5q = random_prime(2^bits, proof=False)67N = p * q8phi = (p - 1) * (q - 1)910if gcd(phi, e) != 1:11continue1213d = inverse_mod(e, phi)14return N, d151617def sign_message(m, N, d, deny=range(0, 10000)):18# deny is the range of messages that the signer refuses to sign.19if m in deny:20raise ValueError("Wait that's illegal")21s = pow(m, d, N)22return s2324def test():25m = 1000126m2 = 1000227e = 6553728target_m = 22930N, d = generate_private_params()3132s1 = sign_message(m, N, d)33s2 = sign_message(m2, N, d)34r = random.randint(0, N)3536# Let's say the attacker wants to obtain a signature of m = 2. Obviously he can't do this directly since the sender won't allows a signature for 2.37# However, this does little to stop the attacker, who can pick an `r` in Z_n and request a signature $s$ for $r^e * m$.38# The signer doesn't know the attacker's intentions and assumes that because the message is not in a list of banned ones39# It is safe to sign. The attacker can then calculate the desired signature of $m$ by simply taking ((r^-1 mod N) * s) mod N.4041s_r = inverse_mod(r, N) * sign_message(pow(r, e, N) * target_m, N, d)42sig_of_2 = sign_message(2, N, d, deny=[])4344assert sig_of_2 == s_r4546return s_r4748if __name__ == "__main__":49test()505152