module_aes.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from Crypto.Cipher import AES
  2. from binascii import b2a_hex, a2b_hex
  3. import wmi
  4. # pip install pycryptodome
  5. # pip install wmi
  6. class Aes(object):
  7. # 如果text不足16位的倍数就用空格补足为16位
  8. def add_to_16(self, text):
  9. if len(text.encode('utf-8')) % 16:
  10. add = 16 - (len(text.encode('utf-8')) % 16)
  11. else:
  12. add = 0
  13. text = text + ('\0' * add)
  14. return text.encode('utf-8')
  15. # 加密函数
  16. def encrypt(self, text, key, iv):
  17. mode = AES.MODE_CBC
  18. text = self.add_to_16(text)
  19. cryptos = AES.new(key=key.encode('utf-8'), mode=mode, iv=iv.encode('utf-8'))
  20. cipher_text = cryptos.encrypt(text)
  21. # 因为AES加密后的字符串不一定是ascii字符集的,输出保存可能存在问题,所以这里转为16进制字符串
  22. return b2a_hex(cipher_text)
  23. # 解密后,去掉补足的空格用strip() 去掉
  24. def decrypt(self, text, key, iv):
  25. mode = AES.MODE_CBC
  26. cryptos = AES.new(key=key.encode('utf-8'), mode=mode, iv=iv.encode('utf-8'))
  27. plain_text = cryptos.decrypt(a2b_hex(text))
  28. return bytes.decode(plain_text).rstrip('\0')
  29. def get_computer_key(self):
  30. c = wmi.WMI()
  31. system_info = c.Win32_ComputerSystem()[0]
  32. mac_address = c.Win32_NetworkAdapterConfiguration(IPEnabled=True)[0].MACAddress
  33. cpu_id = c.Win32_Processor()[0].ProcessorId
  34. machine_code = system_info.Manufacturer + '' + system_info.Model + '' + mac_address + '' + cpu_id
  35. machine_code = machine_code.replace(" ", "").replace(":", "")
  36. return machine_code
  37. def get_authorization(self, key_text, key, iv):
  38. machine_code = self.get_computer_key()
  39. try:
  40. text = self.decrypt(key_text, key, iv) # 解密
  41. except:
  42. return "false"
  43. try:
  44. _machine_code, authorization = text.split("_")
  45. if _machine_code != machine_code:
  46. return "false"
  47. except:
  48. return "false"
  49. return authorization
  50. def get_key(self, authorization, key, iv):
  51. machine_code = self.get_computer_key()
  52. key = self.encrypt("{}_{}".format(machine_code, authorization), key, iv) # 加密
  53. return key.decode()
  54. if __name__ == '__main__':
  55. print(Aes().get_computer_key())
  56. # e = Aes().encrypt("hellosadsasdasdas1111+ world", "8E5EC2AC2191167DF9B753BA93A1E7B1", "0112030405060701") # 加密
  57. # d = Aes().decrypt(e, "8E5EC2AC2191167DF9B753BA93A1E7B1", "0112030405060701") # 解密
  58. c = Aes().get_key("heldasdasdsdsadsadsadsadsadsadsdsadsadasdasds", "8E5EC2AC2191167DF9B753BA93A1E7B1", "0112030405060701")
  59. print(c)
  60. print(
  61. Aes().get_authorization(c, "8E5EC2AC2191167DF9B753BA93A1E7B1", "0112030405060701"))
  62. # print("加密:", e)
  63. # print("解密:", d)