Fixes #1741: Fixed Unicode support for secret plaintexts

This commit is contained in:
Jeremy Stretch 2017-11-29 15:16:11 -05:00
parent 68f76465cf
commit 34d10f8db7
2 changed files with 7 additions and 6 deletions

View File

@ -303,6 +303,7 @@ class Secret(CreatedUpdatedModel):
|LL|MySecret|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| |LL|MySecret|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|
+--+--------+-------------------------------------------+ +--+--------+-------------------------------------------+
""" """
s = s.encode('utf8')
if len(s) > 65535: if len(s) > 65535:
raise ValueError("Maximum plaintext size is 65535 bytes.") raise ValueError("Maximum plaintext size is 65535 bytes.")
# Minimum ciphertext size is 64 bytes to conceal the length of short secrets. # Minimum ciphertext size is 64 bytes to conceal the length of short secrets.
@ -315,7 +316,7 @@ class Secret(CreatedUpdatedModel):
return ( return (
chr(len(s) >> 8).encode() + chr(len(s) >> 8).encode() +
chr(len(s) % 256).encode() + chr(len(s) % 256).encode() +
s.encode() + s +
os.urandom(pad_length) os.urandom(pad_length)
) )
@ -324,11 +325,11 @@ class Secret(CreatedUpdatedModel):
Consume the first two bytes of s as a plaintext length indicator and return only that many bytes as the Consume the first two bytes of s as a plaintext length indicator and return only that many bytes as the
plaintext. plaintext.
""" """
if isinstance(s[0], int): if isinstance(s[0], str):
plaintext_length = (s[0] << 8) + s[1]
elif isinstance(s[0], str):
plaintext_length = (ord(s[0]) << 8) + ord(s[1]) plaintext_length = (ord(s[0]) << 8) + ord(s[1])
return s[2:plaintext_length + 2].decode() else:
plaintext_length = (s[0] << 8) + s[1]
return s[2:plaintext_length + 2].decode('utf8')
def encrypt(self, secret_key): def encrypt(self, secret_key):
""" """

View File

@ -166,7 +166,7 @@ def secret_edit(request, pk):
# Create and encrypt the new Secret # Create and encrypt the new Secret
if master_key is not None: if master_key is not None:
secret = form.save(commit=False) secret = form.save(commit=False)
secret.plaintext = str(form.cleaned_data['plaintext']) secret.plaintext = form.cleaned_data['plaintext']
secret.encrypt(master_key) secret.encrypt(master_key)
secret.save() secret.save()
messages.success(request, "Modified secret {}.".format(secret)) messages.success(request, "Modified secret {}.".format(secret))