Skip to content

Instantly share code, notes, and snippets.

@escapewindow
Created February 25, 2016 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save escapewindow/435a5bd1f16783edfd11 to your computer and use it in GitHub Desktop.
Save escapewindow/435a5bd1f16783edfd11 to your computer and use it in GitHub Desktop.
this also fixes #154
diff --git a/pgpy/types.py b/pgpy/types.py
index 2cc4320..62d69fb 100644
--- a/pgpy/types.py
+++ b/pgpy/types.py
@@ -224,18 +224,33 @@ class PGPObject(six.with_metaclass(abc.ABCMeta, object)):
return i.to_bytes(blen, order)
@staticmethod
- def text_to_bytes(text):
+ def char_to_bytes(c, bin):
+ if c < 256:
+ bin.append(c)
+
+ else:
+ bin += PGPObject.int_to_bytes(c)
+
+ @staticmethod
+ def text_to_bytes(text, encoding='utf-8'):
bin = bytearray()
if text is None or isinstance(text, bytearray):
return text
for c in iter(ord(c) for c in text):
- if c < 256:
- bin.append(c)
+ PGPObject.char_to_bytes(c, bin)
- else:
- bin += PGPObject.int_to_bytes(c)
+ try:
+ bin.decode(encoding)
+ except UnicodeDecodeError:
+ bin = bytearray()
+ try:
+ byte_a = bytearray(text)
+ except TypeError:
+ byte_a = bytearray(text, encoding=encoding)
+ for c in byte_a:
+ PGPObject.char_to_bytes(c, bin)
return bytes(bin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment