From f565c1120bc8f823ce2c6e21d5aeea412afaec6e Mon Sep 17 00:00:00 2001
From: Evangelos Foutras <evangelos@foutrelis.com>
Date: Thu, 3 Dec 2020 18:17:51 +0200
Subject: [PATCH] Use base64.decodebytes() and base64.encodebytes().  [Issue
 #338]

This commit also adds test coverage for tsigkeyring, and fixes to_text()
on python 3, which had never worked properly due to an extra .decode().

(cherry picked from commit f93c8c6ad41d38ccd19335a5a0a396cbaa409caf)
---
 dns/tsigkeyring.py        |  7 ++++---
 tests/test_tsigkeyring.py | 33 +++++++++++++++++++++++++++++++++
 2 files changed, 37 insertions(+), 3 deletions(-)
 create mode 100644 tests/test_tsigkeyring.py

diff --git a/dns/tsigkeyring.py b/dns/tsigkeyring.py
index 5e5fe1c..74ff667 100644
--- a/dns/tsigkeyring.py
+++ b/dns/tsigkeyring.py
@@ -32,7 +32,7 @@ def from_text(textring):
     keyring = {}
     for keytext in textring:
         keyname = dns.name.from_text(keytext)
-        secret = base64.decodestring(maybe_encode(textring[keytext]))
+        secret = base64.decodebytes(maybe_encode(textring[keytext]))
         keyring[keyname] = secret
     return keyring
 
@@ -44,7 +44,8 @@ def to_text(keyring):
 
     textring = {}
     for keyname in keyring:
-        keytext = maybe_decode(keyname.to_text())
-        secret = maybe_decode(base64.encodestring(keyring[keyname]))
+        keytext = keyname.to_text()
+        # rstrip to get rid of the \n encoding adds
+        secret = maybe_decode(base64.encodebytes(keyring[keyname])).rstrip()
         textring[keytext] = secret
     return textring
diff --git a/tests/test_tsigkeyring.py b/tests/test_tsigkeyring.py
new file mode 100644
index 0000000..ce8888d
--- /dev/null
+++ b/tests/test_tsigkeyring.py
@@ -0,0 +1,33 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+import base64
+import unittest
+
+import dns.tsigkeyring
+
+text_keyring = {
+    'keyname.' : 'NjHwPsMKjdN++dOfE5iAiQ=='
+}
+
+rich_keyring = {
+    dns.name.from_text('keyname.') : \
+    base64.decodebytes('NjHwPsMKjdN++dOfE5iAiQ=='.encode())
+}
+
+class TSIGKeyRingTestCase(unittest.TestCase):
+
+    def test_from_text(self):
+        """text keyring -> rich keyring"""
+        rkeyring = dns.tsigkeyring.from_text(text_keyring)
+        self.assertEqual(rkeyring, rich_keyring)
+
+    def test_to_text(self):
+        """text keyring -> rich keyring -> text keyring"""
+        tkeyring = dns.tsigkeyring.to_text(rich_keyring)
+        self.assertEqual(tkeyring, text_keyring)
+
+    def test_from_and_to_text(self):
+        """text keyring -> rich keyring -> text keyring"""
+        rkeyring = dns.tsigkeyring.from_text(text_keyring)
+        tkeyring = dns.tsigkeyring.to_text(rkeyring)
+        self.assertEqual(tkeyring, text_keyring)
