feat: enable use of custom encryption_key in encrypt()/decrypt()
This commit is contained in:
parent
878ac658b2
commit
f15edd21d1
2 changed files with 18 additions and 8 deletions
|
|
@ -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`
|
||||
|
|
|
|||
|
|
@ -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():
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue