Skip to content

Commit

Permalink
basic crypto for paging
Browse files Browse the repository at this point in the history
  • Loading branch information
gbin committed Dec 17, 2012
1 parent 7f7f3b1 commit c6d9969
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
Empty file added flask_restful/paging.py
Empty file.
26 changes: 26 additions & 0 deletions flask_restful/utils/crypto.py
Original file line number Diff line number Diff line change
@@ -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)))
10 changes: 10 additions & 0 deletions tests/test_crypto.py
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit c6d9969

Please sign in to comment.