From c6d9969109c6a1ea00b3d93abaedf23b4d9d9aaf Mon Sep 17 00:00:00 2001 From: Guillaume BINET Date: Thu, 6 Dec 2012 17:04:09 -0800 Subject: [PATCH] basic crypto for paging --- flask_restful/paging.py | 0 flask_restful/utils/crypto.py | 26 ++++++++++++++++++++++++++ tests/test_crypto.py | 10 ++++++++++ 3 files changed, 36 insertions(+) create mode 100644 flask_restful/paging.py create mode 100644 flask_restful/utils/crypto.py create mode 100644 tests/test_crypto.py diff --git a/flask_restful/paging.py b/flask_restful/paging.py new file mode 100644 index 00000000..e69de29b diff --git a/flask_restful/utils/crypto.py b/flask_restful/utils/crypto.py new file mode 100644 index 00000000..1656512e --- /dev/null +++ b/flask_restful/utils/crypto.py @@ -0,0 +1,26 @@ + +from Crypto.Cipher import AES +from base64 import b64encode, b64decode + +BLOCK_SIZE = 16 +INTERRUPT = '\0' # something impossible to put in a string +PADDING = '\1' + +def pad(data): + return data + INTERRUPT + PADDING * (BLOCK_SIZE - (len(data) + 1) % BLOCK_SIZE) + +def strip(data): + return data.rstrip(PADDING).rstrip(INTERRUPT) + +def create_cipher(key, seed): + if len(seed) != 16: + raise ValueError("Choose a seed of 16 bytes") + if len(key) != 32: + raise ValueError("Choose a key of 32 bytes") + return AES.new(key, AES.MODE_CBC, seed) + +def encrypt(plaintext_data, key, seed): + return b64encode(create_cipher(key, seed).encrypt(pad(plaintext_data))) + +def decrypt(encrypted_data, key, seed): + return strip(create_cipher(key, seed).decrypt(b64decode(encrypted_data))) \ No newline at end of file diff --git a/tests/test_crypto.py b/tests/test_crypto.py new file mode 100644 index 00000000..55518d39 --- /dev/null +++ b/tests/test_crypto.py @@ -0,0 +1,10 @@ +import unittest +from flask_restful.utils.crypto import encrypt, decrypt + + +class CryptoTestCase(unittest.TestCase): + def test_encrypt_decrypt(self): + key = '0123456789abcdef0123456789abcdef' + seed = 'deadbeefcafebabe' + message = 'It should go through' + self.assertEqual(decrypt(encrypt(message, key, seed), key, seed), message) \ No newline at end of file