KeyPairCreator.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #!/usr/bin/env python
  2. import argparse
  3. from datetime import datetime
  4. import os
  5. import sys
  6. from typing import Tuple
  7. import zmq.auth
  8. # @brief Creates a new keypair for ZMQ encryption
  9. # @param[in] directory The location where to store the keys
  10. # @return The public and private key tuple
  11. def KeyPairCreator(directory: str, server: bool) -> Tuple[str, str]:
  12. if not server:
  13. target = 'client'
  14. else:
  15. target = 'server'
  16. public, private = zmq.auth.create_certificates(directory, target)
  17. return public, private
  18. def str2bool(value):
  19. if isinstance(value, bool):
  20. return value
  21. elif value.lower() in ('yes', 'true', 't', 'y', '1'):
  22. return True
  23. elif value.lower() in ('no', 'false', 'f', 'n', '0'):
  24. return False
  25. else:
  26. raise argparse.ArgumentTypeError('Boolean value expected')
  27. def findIdentificationKey(path, publicKey : bool):
  28. if True == publicKey:
  29. identifier = 'public-key = '
  30. else:
  31. identifier = 'secret-key = '
  32. with open(path) as file:
  33. key = ''
  34. for line in file:
  35. if identifier in line:
  36. elements = line.split('=')
  37. for idx in range(1, len(elements)):
  38. if 0 == len(key):
  39. key = elements[idx][2:-1]
  40. key = key + elements[idx][-1]
  41. else:
  42. key = key + '=' + elements[idx]
  43. return key[0:-2]
  44. return None
  45. if __name__ == '__main__':
  46. # create the commandline parser
  47. parser = argparse.ArgumentParser(description='Create a new key-value pair')
  48. parser.add_argument('--directory', type=str, help='Directory where to store the key pair')
  49. parser.add_argument('--publickey', nargs='?', type=str, default=os.getcwd(), help='Full path to the public key of the server')
  50. parser.add_argument('--server', default=False, action='store_true', help="Creates server key pair")
  51. args = parser.parse_args()
  52. # validate the arguments
  53. if False == args.server and not os.path.exists(args.publickey):
  54. sys.stderr.write('The public key of the server cannot be found')
  55. sys.exit(-1)
  56. # create the directory if it does not exist
  57. if not os.path.exists(args.directory):
  58. os.makedirs(args.directory)
  59. # create the keys
  60. _, private = KeyPairCreator(args.directory, args.server)
  61. if False == args.server:
  62. publicServer = findIdentificationKey(args.publickey, True)
  63. publicClient = findIdentificationKey(private, True)
  64. privateClient = findIdentificationKey(private, False)
  65. if None == publicServer:
  66. sys.stderr.write('The public key of the server cannot be found in the defined file')
  67. sys.exit(-1)
  68. if None == publicClient:
  69. sys.stderr.write('Unable to extract the created public key')
  70. sys.exit(-1)
  71. if None == privateClient:
  72. sys.stderr.write('Unable to extract the created private key')
  73. sys.exit(-1)
  74. # rename keys
  75. timestamp = str(datetime.now(tz=None))
  76. timestamp = timestamp.replace(' ', '_')
  77. timestamp = timestamp.replace(':', '-')
  78. os.rename(os.path.join(args.directory, 'client.key'), os.path.join(args.directory, timestamp + '.key'))
  79. os.rename(os.path.join(args.directory, 'client.key_secret'), os.path.join(args.directory, timestamp + '.key_secret'))
  80. print(publicServer)
  81. print(publicClient)
  82. print(privateClient)