2 # -------------------------------------------------------------------------
3 # Copyright (C) 2020 Wipro Limited.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # -------------------------------------------------------------------------
19 from Crypto.Cipher import AES
20 from osdf.config.base import osdf_config
21 from Crypto.Util.Padding import unpad
22 from Crypto.Util.Padding import pad
25 class AESCipher(object):
29 def get_instance(key = None):
30 if AESCipher.__instance is None:
31 print("Creating the singleton instance")
33 return AESCipher.__instance
35 def __init__(self, key=None):
36 if AESCipher.__instance is not None:
37 raise Exception("This class is a singleton!")
39 AESCipher.__instance = self
43 key = osdf_config.deployment["appkey"]
45 self.key = key.encode()
47 def encrypt(self, data):
49 cipher = AES.new(self.key, AES.MODE_CBC)
50 ciphered_data = cipher.encrypt(pad(data, AES.block_size))
51 enc = (cipher.iv.hex())+(ciphered_data.hex())
54 def decrypt(self, enc):
55 iv = bytes.fromhex(enc[:32])
56 ciphered_data = bytes.fromhex(enc[32:])
57 cipher = AES.new(self.key, AES.MODE_CBC, iv=iv)
58 original_data = unpad(cipher.decrypt(ciphered_data), AES.block_size).decode()