Posted By

ezik on 01/30/18


Tagged

hsm thales


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

ezik


thales_host_command_console.py


 / Published in: Python
 

Send HSM host commands to Thales HSM

  1. import socket
  2. import sys
  3. import argparse
  4.  
  5. parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  6. parser.add_argument("--host", help="HSM host/IP", default="10.57.6.250")
  7. parser.add_argument("--port", help="HSM port", default=1500)
  8. args = parser.parse_args()
  9.  
  10. print "Connecting to HSM %s:%s ...(press Ctrl+C to exit)" % (args.host, args.port)
  11. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  12. sock.connect((args.host, args.port))
  13.  
  14. def bin2hex(s):
  15. res = ''
  16. for c in s:
  17. x = ord(c)
  18. if x < 31 or x > 127:
  19. res = res + ('\\%02X' % x)
  20. else:
  21. res = res + c
  22. return res
  23.  
  24. def bin2hex_all(s):
  25. res = ''
  26. for c in s:
  27. x = ord(c)
  28. res = res + ('\\%02X' % x)
  29. return res
  30.  
  31. def hex2bin(s):
  32. res = ''
  33. i = 0
  34. while i < len(s):
  35. c = s[i]
  36. if c == '\\':
  37. if s[i + 1] == '\\':
  38. res = res + '\\'
  39. i = i + 2
  40. else:
  41. res = res + chr(int(s[i + 1: i + 3], 16))
  42. i = i + 3
  43. else:
  44. res = res + c
  45. i = i + 1
  46.  
  47. return res
  48.  
  49. def send(s):
  50. s = '0000' + hex2bin(s)
  51. length = len(s)
  52. msg = chr(length / 256) + chr(length % 256) + s
  53. sock.send(msg)
  54.  
  55. def recv():
  56. a = sock.recv(1)
  57. b = sock.recv(1)
  58. length = (ord(a) * 256) + ord(b)
  59. global resp
  60. resp = sock.recv(length)
  61. return bin2hex(resp[4:])
  62.  
  63. while True:
  64. try:
  65. req = raw_input('>>> ')
  66. resp=''
  67. send(req)
  68. print '<<< ' + recv()
  69. print 'full hex: '+ bin2hex_all(resp[4:])
  70. except KeyboardInterrupt:
  71. print " Exiting!"
  72. sys.exit()

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: ezik on January 30, 2018

Send HSM host commands to Thales HSM

You need to login to post a comment.