allow user to control encoding

This commit is contained in:
revsuine 2024-11-12 14:06:19 +00:00
parent edd8650c84
commit a2eaa913be
Signed by: revsuine
GPG key ID: 3F257B68F5BC9339
2 changed files with 21 additions and 12 deletions

View file

@ -39,7 +39,7 @@ import typing
import gnupg
# constants
ENCODING='utf-8' # default is latin-1 which fails w some unicode chars
DEFAULT_ENCODING='utf-8' # default is latin-1 which fails w some unicode chars
def is_message_encrypted(message: email.message.Message) -> bool:
"""Determines whether or not an email message is encrypted.
@ -53,7 +53,8 @@ def encrypt(
message: email.message.Message,
recipients: typing.List[str],
*,
unconditionally_encrypt: bool = False
unconditionally_encrypt: bool = False,
encoding: str = DEFAULT_ENCODING
) -> str:
"""Encrypt given message
@ -72,7 +73,7 @@ def encrypt(
return message.as_string()
gpg = gnupg.GPG()
gpg.encoding = ENCODING
gpg.encoding = encoding
encrypted_content = gpg.encrypt(message.as_string(), recipients, armor=True)
if not encrypted_content:
raise ValueError(encrypted_content.status)
@ -108,11 +109,10 @@ def encrypt(
return encmsg.as_string()
def decrypt(message: email.message.Message) -> str:
"""Decrypt the given message
Likely won't work on this server as I don't store private keys"""
def decrypt(message: email.message.Message, *, encoding: str = DEFAULT_ENCODING) -> str:
"""Decrypt the given message"""
gpg = gnupg.GPG()
gpg.encoding = ENCODING
gpg.encoding = encoding
return str(gpg.decrypt(message.as_string()))
def main() -> None:
@ -123,15 +123,18 @@ def main() -> None:
)
parser.add_argument('-d', '--decrypt', action="store_true",
help="Decrypt rather than encrypt")
parser.add_argument('--encoding', action="store", default=DEFAULT_ENCODING,
required=False,
help="Encoding to use for the gnupg.GPG object")
parser.add_argument('recipient', nargs='*',
help="Key ID or email of keys to encrypt for")
help="Key ID or email of keys to encrypt for")A
args = parser.parse_args()
msg = email.message_from_file(sys.stdin)
if args.decrypt:
sys.stdout.write(decrypt(msg))
sys.stdout.write(decrypt(msg), encoding=args.encoding)
else:
sys.stdout.write(encrypt(msg, args.recipient))
sys.stdout.write(encrypt(msg, args.recipient, encoding=args.encoding))
if __name__ == '__main__':
main()