From dafd75f4e6f3c85624695cf314afbc67ff1c6998 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Borgstr=C3=B6m?= Date: Wed, 3 Nov 2010 19:46:21 +0100 Subject: [PATCH] Handle special case where RSA.encrypt returns cipher text shorter than 256 bytes. --- darc/helpers.py | 11 +++++++++++ darc/keychain.py | 6 +++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/darc/helpers.py b/darc/helpers.py index 28261b05a..676d79a0d 100644 --- a/darc/helpers.py +++ b/darc/helpers.py @@ -8,6 +8,17 @@ import stat +def zero_pad(data, length): + """Make sure data is `length` bytes long by prepending zero bytes + + >>> zero_pad('foo', 5) + '\\x00\\x00foo' + >>> zero_pad('foo', 3) + 'foo' + """ + return '\0' * (length - len(data)) + data + + def exclude_path(path, patterns): """Used by create and extract sub-commands to determine if an item should be processed or not diff --git a/darc/keychain.py b/darc/keychain.py index 7e6f040cf..be793b93d 100644 --- a/darc/keychain.py +++ b/darc/keychain.py @@ -11,7 +11,7 @@ from Crypto.Util import Counter from Crypto.Util.number import bytes_to_long -from .helpers import IntegrityError +from .helpers import IntegrityError, zero_pad from .oaep import OAEP @@ -51,9 +51,9 @@ def open(self, path): self.rsa_read = RSA.importKey(chain['rsa_read']) self.rsa_create = RSA.importKey(chain['rsa_create']) self.read_encrypted = OAEP(256, hash=SHA256).encode(self.read_key, os.urandom(32)) - self.read_encrypted = self.rsa_read.encrypt(self.read_encrypted, '')[0] + self.read_encrypted = zero_pad(self.rsa_read.encrypt(self.read_encrypted, '')[0], 256) self.create_encrypted = OAEP(256, hash=SHA256).encode(self.create_key, os.urandom(32)) - self.create_encrypted = self.rsa_create.encrypt(self.create_encrypted, '')[0] + self.create_encrypted = zero_pad(self.rsa_create.encrypt(self.create_encrypted, '')[0], 256) def encrypt(self, data, password): salt = os.urandom(32)