Added seed code for access-management.
[ta/access-management.git] / src / access_management / cryptohelper / encryptaaafiles.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 argparse
17 import json
18 import base64
19
20
21 class EncryptAAAFile(object):
22     def __init__(self, pem_file):
23         self.key = M2Crypto.RSA.load_pub_key(pem_file)
24
25
26     def encrypt_file(self, file_path):
27         with open(file_path,'r') as file:
28             jsoned_file = json.load(file)
29             for user in jsoned_file["users"]:
30                 encrypted_pass = self.key.public_encrypt(user[1], M2Crypto.RSA.pkcs1_oaep_padding)
31                 encoded_pass = base64.b64encode(encrypted_pass)
32                 user[1] = encoded_pass
33             encrypted_file_name = file_path + ".enc"
34             with open(encrypted_file_name, 'w') as encrypted_file:
35                 encrypted_file.write(json.dumps(jsoned_file))
36         return encrypted_file_name
37
38
39 if __name__ == '__main__':
40     parser = argparse.ArgumentParser()
41     parser.add_argument("key", help="Public key path")
42     parser.add_argument("file", help="Path of the file to encrypt")
43     args = parser.parse_args()
44     enc = EncryptAAAFile(args.key)
45     encrypted_file_name = enc.encrypt_file(args.file)
46     print "Encrypting file {0} for AAA done. New file name: {1}".format(args.file, encrypted_file_name)