Advertisement
Guest User

Untitled

a guest
Nov 19th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. import SocketServer
  3. import socket
  4. import Crypto.Random.random
  5. import random
  6. import gmpy2
  7. import hashlib
  8.  
  9. # from secrets import FLAG
  10.  
  11.  
  12. welcome = """Welcome to RSA sign and verify service.
  13. Due to high costs of generating prime numbers you need to provide them yourself.
  14. We are still secure because we will never disclose neither public nor private exponent to you.
  15. """
  16.  
  17. def send(s, t):
  18.     s.sendall(t)
  19.  
  20. def recv(s):
  21.     res = ''
  22.     while '\n' not in res :
  23.         x = s.recv(1)
  24.         if len(x) == 0:
  25.             break
  26.         res += x
  27.     return res
  28.  
  29. def main(s):
  30.     send(s, welcome)
  31.     send(s, "Please provide p=")
  32.     p = int(recv(s).strip())
  33.     send(s, "Please provide q=")
  34.     q = int(recv(s).strip())
  35.  
  36.     assert p>2 and gmpy2.is_prime(p), "p check failed"
  37.     assert q>2 and gmpy2.is_prime(q), "q check failed"
  38.     assert p != q, "p is equal to q"
  39.  
  40.     n = p*q
  41.  
  42.     assert 2**511 < n and 2**512 > n, "n is not 512 bit"
  43.  
  44.     e = Crypto.Random.random.getrandbits(512)
  45.     phi = (p-1)*(q-1)
  46.     d = gmpy2.invert(e, phi)
  47.  
  48.     for i in range(20):
  49.         plain = random.getrandbits(512)
  50.         cipher = pow(plain, e, n)
  51.         decipher = pow(cipher, d, n)
  52.         assert plain == decipher, "rsa doesn't work for this key"
  53.  
  54.  
  55.     send(s, "msg=")
  56.     msg = recv(s).strip().decode("hex")
  57.     send(s, "sign=")
  58.     sign = int(recv(s))
  59.  
  60.     assert pow(sign, e, n) == int(hashlib.sha512(msg).hexdigest(), 16), "failed to verify"
  61.     assert msg.strip() == "Give me the flag", "you don't want the flag"
  62.     send(s, "FLAG:")
  63.  
  64.  
  65. class TaskHandler(SocketServer.BaseRequestHandler):
  66.     def handle(self):
  67.         try:
  68.           main(self.request)
  69.         except Exception as err:
  70.             send(self.request, err.message)
  71.  
  72. if __name__ == '__main__':
  73.     SocketServer.ThreadingTCPServer.allow_reuse_address = True
  74.     server = SocketServer.ThreadingTCPServer(('0.0.0.0', 1337), TaskHandler)
  75.     server.serve_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement