aes_encryption.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright 2019 The FATE Authors. All Rights Reserved.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. #
  18. from Cryptodome.Cipher import AES
  19. from federatedml.secureprotol.symmetric_encryption.symmetric_encryption import SymmetricKey
  20. from federatedml.util import conversion
  21. class AESKey(SymmetricKey):
  22. """
  23. Note that a key cannot used for both encryption and decryption scenarios
  24. """
  25. def __init__(self, key, nonce=None):
  26. """
  27. :param key: bytes, must be 16, 24 or 32 bytes long
  28. """
  29. super(AESKey, self).__init__()
  30. if nonce is None:
  31. self.cipher_core = AES.new(key, AES.MODE_EAX)
  32. self.nonce = self.cipher_core.nonce # noise, generated by the encryptor, must be provided to the decryptor
  33. else:
  34. self.cipher_core = AES.new(key, AES.MODE_EAX, nonce=nonce)
  35. self.nonce = nonce
  36. class AESEncryptKey(AESKey):
  37. """
  38. AES encryption scheme
  39. Note that the ciphertext size is affected only by that of the plaintext, instead of the key length
  40. """
  41. def __init__(self, key):
  42. super(AESEncryptKey, self).__init__(key=key)
  43. def encrypt(self, plaintext):
  44. """
  45. :param plaintext: bytes/int/float/str
  46. :return: bytes
  47. """
  48. if not isinstance(plaintext, bytes):
  49. plaintext = self._all_to_bytes(plaintext)
  50. elif isinstance(plaintext, bytes):
  51. pass
  52. else:
  53. raise TypeError("AES encryptor supports bytes/int/float/str")
  54. return self.cipher_core.encrypt(plaintext)
  55. def get_nonce(self):
  56. return self.nonce
  57. @staticmethod
  58. def _all_to_bytes(message):
  59. """
  60. Convert an int/float/str to bytes, e.g., 1.65 -> b'1.65', 'hello -> b'hello'
  61. :param message: int/float/str
  62. :return: -1 if type error, otherwise str
  63. """
  64. if isinstance(message, int) or isinstance(message, float):
  65. return conversion.str_to_bytes(str(message))
  66. elif isinstance(message, str):
  67. return conversion.str_to_bytes(message)
  68. else:
  69. return -1
  70. class AESDecryptKey(AESKey):
  71. """
  72. AES decryption scheme
  73. """
  74. def __init__(self, key, nonce):
  75. super(AESDecryptKey, self).__init__(key=key, nonce=nonce)
  76. def decrypt(self, ciphertext):
  77. """
  78. :param ciphertext: bytes
  79. :return: str
  80. """
  81. if not isinstance(ciphertext, bytes):
  82. raise TypeError("AES decryptor supports bytes only")
  83. return conversion.bytes_to_str(self.cipher_core.decrypt(ciphertext))