Add Nxi-Termination feature
[optf/osdf.git] / osdf / utils / cipherUtils.py
1 #
2 # -------------------------------------------------------------------------
3 #   Copyright (C) 2020 Wipro Limited.
4 #
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
8 #
9 #       http://www.apache.org/licenses/LICENSE-2.0
10 #
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.
16 #
17 # -------------------------------------------------------------------------
18
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
23
24
25 class AESCipher(object):
26     __instance = None
27
28     @staticmethod
29     def get_instance(key = None):
30         if AESCipher.__instance is None:
31             print("Creating the singleton instance")
32             AESCipher(key)
33         return AESCipher.__instance
34
35     def __init__(self, key=None):
36         if AESCipher.__instance is not None:
37             raise Exception("This class is a singleton!")
38         else:
39             AESCipher.__instance = self
40
41         self.bs = 32
42         if key is None:
43             key = osdf_config.deployment["appkey"]
44
45         self.key = key.encode()
46
47     def encrypt(self, data):
48         data = data.encode()
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())
52         return enc
53
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()
59         return original_data