Utility function for recursive password encryption/decription 93/8093/3
authordelacruzramo <pedro.delacruzramos@altran.com>
Fri, 25 Oct 2019 14:50:13 +0000 (16:50 +0200)
committerdelacruzramo <pedro.delacruzramos@altran.com>
Mon, 4 Nov 2019 08:19:09 +0000 (09:19 +0100)
Change-Id: I3cb00ad4f7d2bf78fd25911c650a1a723e593d37
Signed-off-by: delacruzramo <pedro.delacruzramos@altran.com>
osm_common/dbbase.py

index 1319fd8..95250c1 100644 (file)
@@ -17,6 +17,7 @@
 
 import yaml
 import logging
+import re
 from http import HTTPStatus
 from copy import deepcopy
 from Crypto.Cipher import AES
@@ -253,6 +254,28 @@ class DbBase(object):
                                   http_code=HTTPStatus.INTERNAL_SERVER_ERROR)
             return unpadded_private_msg
 
+    def encrypt_decrypt_fields(self, item, action, fields=None, flags=re.I, schema_version=None, salt=None):
+        if not fields:
+            return
+        actions = ['encrypt', 'decrypt']
+        if action.lower() not in actions:
+            raise DbException("Unknown action ({}): Must be one of {}".format(action, actions),
+                              http_code=HTTPStatus.INTERNAL_SERVER_ERROR)
+        method = self.encrypt if action.lower() == 'encrypt' else self.decrypt
+
+        def process(item):
+            if isinstance(item, list):
+                for elem in item:
+                    process(elem)
+            elif isinstance(item, dict):
+                for key, val in item.items():
+                    if any(re.search(f, key, flags) for f in fields) and isinstance(val, str):
+                        item[key] = method(val, schema_version, salt)
+                    else:
+                        process(val)
+
+        process(item)
+
 
 def deep_update_rfc7396(dict_to_change, dict_reference, key_list=None):
     """