Added seed code for access-management.
[ta/access-management.git] / src / access_management / cryptohelper / decryptaaafiles.py
1 # Copyright 2019 Nokia
2
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import M2Crypto
16 import os
17 import argparse
18 import json
19 import base64
20
21
22 class DecryptAAAFile(object):
23     def __init__(self, pem_file):
24         self.key = M2Crypto.RSA.load_key(pem_file)
25
26     def decrypt_file(self, encrypted_file_path):
27         with open(encrypted_file_path,'r') as encrypted_file:
28             jsoned_file = json.load(encrypted_file)
29             for user in jsoned_file["users"]:
30                 if len(user[1]) != 0:
31                     decoded_pass = base64.b64decode(user[1])
32                     decrypted_pass = self.key.private_decrypt(decoded_pass, M2Crypto.RSA.pkcs1_oaep_padding)
33                     user[1] = decrypted_pass.decode('utf-32')
34         return jsoned_file
35
36
37 if __name__ == '__main__':
38     parser = argparse.ArgumentParser()
39     parser.add_argument("key", help="Private key path")
40     parser.add_argument("file", help="Path of the file to decrypt")
41     args = parser.parse_args()
42     dec = DecryptAAAFile(args.key)
43     jsoned_file = dec.decrypt_file(args.file)
44     if args.file.endswith(".enc"):
45         decrypted_filename = args.file[:-4]
46     else:
47         decrypted_filename = args.file + ".dec"
48     decrypted_file = open(os.path.join(decrypted_filename), 'w')
49     decrypted_file.write(json.dumps(jsoned_file))
50     decrypted_file.close()
51     print "Decrypting file {0} for AAA done. New file name: {1}".format(args.file, decrypted_filename)