forked from flask-restful/flask-restful
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
36 additions
and
0 deletions.
There are no files selected for viewing
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |