diff --git a/frappe/tests/test_password.py b/frappe/tests/test_password.py index 98141072e2..9b68f3aace 100644 --- a/frappe/tests/test_password.py +++ b/frappe/tests/test_password.py @@ -3,7 +3,7 @@ from __future__ import unicode_literals import frappe import unittest -from frappe.utils.password import update_password, check_password, passlibctx +from frappe.utils.password import update_password, check_password, passlibctx, encrypt, decrypt class TestPassword(unittest.TestCase): def setUp(self): @@ -105,6 +105,16 @@ class TestPassword(unittest.TestCase): doc.save() self.assertEqual(doc.get_password(raise_exception=False), None) + def test_custom_encryption_key(self): + text = 'Frappe Framework' + custom_encryption_key = 'DFTBA' + + encrypted_text = encrypt(text, encryption_key=custom_encryption_key) + decrypted_text = decrypt(encrypted_text, encryption_key=custom_encryption_key) + + self.assertEqual(text, decrypted_text) + + pass def get_password_list(doc): return frappe.db.sql("""SELECT `password` diff --git a/frappe/utils/password.py b/frappe/utils/password.py index fbed3cd8e7..d97c788568 100644 --- a/frappe/utils/password.py +++ b/frappe/utils/password.py @@ -157,20 +157,20 @@ def create_auth_table(): frappe.db.create_auth_table() -def encrypt(pwd): - cipher_suite = Fernet(encode(get_encryption_key())) - cipher_text = cstr(cipher_suite.encrypt(encode(pwd))) +def encrypt(txt, encryption_key=None): + cipher_suite = Fernet(encode(encryption_key or get_encryption_key())) + cipher_text = cstr(cipher_suite.encrypt(encode(txt))) return cipher_text -def decrypt(pwd): +def decrypt(txt, encryption_key=None): try: - cipher_suite = Fernet(encode(get_encryption_key())) - plain_text = cstr(cipher_suite.decrypt(encode(pwd))) + cipher_suite = Fernet(encode(encryption_key or get_encryption_key())) + plain_text = cstr(cipher_suite.decrypt(encode(txt))) return plain_text except InvalidToken: # encryption_key in site_config is changed and not valid - frappe.throw(_('Encryption key is invalid, Please check site_config.json')) + frappe.throw(_('Encryption key is invalid' + '!' if encryption_key else ', please check site_config.json.')) def get_encryption_key():