Skip to content
This repository has been archived by the owner on Feb 1, 2023. It is now read-only.

Commit

Permalink
Catch wrong key exception, document
Browse files Browse the repository at this point in the history
  • Loading branch information
amercader committed Feb 24, 2017
1 parent 29071c8 commit a429e1c
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
9 changes: 9 additions & 0 deletions README.md
Expand Up @@ -42,6 +42,15 @@ $ editor .env # edit your vars

```

*Note*: `GTIO_SECRET_KEY` must be a 32 bit URL-safe base64 string. You can obtain it by running the followig:

```python
import base64

base64.urlsafe_b64encode(os.urandom(32))
```


### Migrations

```bash
Expand Down
13 changes: 11 additions & 2 deletions goodtablesio/crypto.py
@@ -1,11 +1,20 @@
import binascii
from cryptography.fernet import Fernet

from goodtablesio import settings


def _get_crypto_instance(key):
try:
return Fernet(key)
except binascii.Error:
raise ValueError('Wrong secret key provided, it must be a 32 bit '
'URL-safe base64 string')


def encrypt_string(value, key=settings.GTIO_SECRET_KEY):

f = Fernet(key)
f = _get_crypto_instance(key)

# Ensure we are working with bytes
if not hasattr(value, 'decode'):
Expand All @@ -17,7 +26,7 @@ def encrypt_string(value, key=settings.GTIO_SECRET_KEY):

def decrypt_string(token, key=settings.GTIO_SECRET_KEY):

f = Fernet(key)
f = _get_crypto_instance(key)

# Ensure we are working with bytes
if not hasattr(token, 'decode'):
Expand Down
23 changes: 23 additions & 0 deletions goodtablesio/tests/test_crypto.py
@@ -1,9 +1,21 @@
import pytest
from cryptography.fernet import Fernet

from goodtablesio import settings
from goodtablesio.crypto import encrypt_string, decrypt_string


def test_incorrect_key_encrypt():

value = b'some-text'
key = b'incorrect-key'

with pytest.raises(ValueError) as exc:
encrypt_string(value, key=key)

assert 'Wrong secret key' in str(exc)


def test_encrypt_string():

value = b'some-text'
Expand Down Expand Up @@ -39,6 +51,17 @@ def test_encrypt_string_transforms_to_bytes():
assert f.decrypt(token.encode('utf-8')) == value.encode('utf-8')


def test_incorrect_key_decrypt():

token = b'some-token'
key = b'incorrect-key'

with pytest.raises(ValueError) as exc:
decrypt_string(token, key=key)

assert 'Wrong secret key' in str(exc)


def test_decrypt_string():

value = b'some-text'
Expand Down

0 comments on commit a429e1c

Please sign in to comment.