Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolves #73: Adds binary secret support #184

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions credstash.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
DEFAULT_REGION = "us-east-1"
PAD_LEN = 19 # number of digits in sys.maxint
WILDCARD_CHAR = "*"
TEXT_CHARS = bytearray(set([7, 8, 9, 10, 12, 13, 27]) | set(range(0x20, 0x100)) - set([0x7f]))


class KeyService(object):
Expand Down Expand Up @@ -561,7 +562,11 @@ def open_aes_ctr_legacy(key_service, material):
hmac = codecs.decode(material['hmac'].value, "hex")
else:
hmac = codecs.decode(material['hmac'], "hex")
return _open_aes_ctr(key, LEGACY_NONCE, ciphertext, hmac, digest_method).decode("utf-8")
ret = _open_aes_ctr(key, LEGACY_NONCE, ciphertext, hmac, digest_method)
try:
return ret.decode("utf-8")
except:
return ret


def seal_aes_ctr_legacy(key_service, secret, digest_method=DEFAULT_DIGEST):
Expand Down Expand Up @@ -606,9 +611,15 @@ def _seal_aes_ctr(plaintext, key, nonce, digest_method):
backend=default_backend()
).encryptor()

ciphertext = encryptor.update(plaintext.encode("utf-8")) + encryptor.finalize()
try:
ciphertext = encryptor.update(plaintext.encode("utf-8")) + encryptor.finalize()
except UnicodeDecodeError as e:
if _is_binary_string(plaintext):
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
return ciphertext, _get_hmac(hmac_key, ciphertext, digest_method)

def _is_binary_string(plaintext):
return bool(plaintext.translate(None, TEXT_CHARS))

def _get_hmac(key, ciphertext, digest_method):
hmac = HMAC(
Expand Down