encode.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import base64
  2. import hashlib
  3. from federatedml.util import LOGGER
  4. class Encode:
  5. def __init__(self, method, base64=0):
  6. self.method = method
  7. self.base64 = base64
  8. self.dist_encode_function = {
  9. "md5": self.__compute_md5,
  10. "sha1": self.__compute_sha1,
  11. "sha224": self.__compute_sha224,
  12. "sha256": self.__compute_sha256,
  13. "sha384": self.__compute_sha384,
  14. "sha512": self.__compute_sha512,
  15. }
  16. @staticmethod
  17. def is_support(method):
  18. support_encode_method = ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"]
  19. return method in support_encode_method
  20. def __compute_md5(self, value):
  21. if self.base64 == 1:
  22. return str(base64.b64encode(hashlib.md5(bytes(value, encoding='utf-8')).digest()), "utf-8")
  23. else:
  24. return hashlib.md5(bytes(value, encoding='utf-8')).hexdigest()
  25. def __compute_sha256(self, value):
  26. if self.base64 == 1:
  27. return str(base64.b64encode(hashlib.sha256(bytes(value, encoding='utf-8')).digest()), "utf-8")
  28. else:
  29. return hashlib.sha256(bytes(value, encoding='utf-8')).hexdigest()
  30. def __compute_sha1(self, value):
  31. if self.base64 == 1:
  32. return str(base64.b64encode(hashlib.sha1(bytes(value, encoding='utf-8')).digest()), "utf-8")
  33. else:
  34. return hashlib.sha1(bytes(value, encoding='utf-8')).hexdigest()
  35. def __compute_sha224(self, value):
  36. if self.base64 == 1:
  37. return str(base64.b64encode(hashlib.sha224(bytes(value, encoding='utf-8')).digest()), "utf-8")
  38. else:
  39. return hashlib.sha224(bytes(value, encoding='utf-8')).hexdigest()
  40. def __compute_sha512(self, value):
  41. if self.base64 == 1:
  42. return str(base64.b64encode(hashlib.sha512(bytes(value, encoding='utf-8')).digest()), "utf-8")
  43. else:
  44. return hashlib.sha512(bytes(value, encoding='utf-8')).hexdigest()
  45. def __compute_sha384(self, value):
  46. if self.base64 == 1:
  47. return str(base64.b64encode(hashlib.sha384(bytes(value, encoding='utf-8')).digest()), "utf-8")
  48. else:
  49. return hashlib.sha384(bytes(value, encoding='utf-8')).hexdigest()
  50. def compute(self, value, pre_salt=None, postfit_salt=None):
  51. if not Encode.is_support(self.method):
  52. LOGGER.warning("Encode module do not support method:{}".format(self.method))
  53. return value
  54. if pre_salt is not None:
  55. value = pre_salt + value
  56. if postfit_salt is not None:
  57. value = value + postfit_salt
  58. return self.dist_encode_function[self.method](value)