~ubuntu-branches/ubuntu/wily/attic/wily

« back to all changes in this revision

Viewing changes to attic/crypto.py

  • Committer: Package Import Robot
  • Author(s): Clint Adams
  • Date: 2013-11-25 09:06:12 UTC
  • mfrom: (1.1.1)
  • Revision ID: package-import@ubuntu.com-20131125090612-hp1yitu1qnpbuaq7
Tags: 0.8.1-1
* New upstream version.
* Bump to Standards-Version 3.9.5.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""A thin ctypes based wrapper for OpenSSL 1.0
 
2
"""
1
3
import sys
2
4
from ctypes import cdll, c_char_p, c_int, c_uint, c_void_p, POINTER, create_string_buffer
3
5
from ctypes.util import find_library
7
9
# Default libcrypto on OS X is too old, try the brew version
8
10
if not hasattr(libcrypto, 'PKCS5_PBKDF2_HMAC') and sys.platform == 'darwin':
9
11
    libcrypto = cdll.LoadLibrary('/usr/local/opt/openssl/lib/libcrypto.dylib')
 
12
# Default libcrypto on FreeBSD is too old, try the ports version
10
13
if not hasattr(libcrypto, 'PKCS5_PBKDF2_HMAC') and sys.platform.startswith('freebsd'):
11
14
    libcrypto = cdll.LoadLibrary('/usr/local/lib/libcrypto.so')
 
15
 
12
16
libcrypto.PKCS5_PBKDF2_HMAC.argtypes = (c_char_p, c_int, c_char_p, c_int, c_int, c_void_p, c_int, c_char_p)
13
17
libcrypto.EVP_sha256.restype = c_void_p
14
18
libcrypto.AES_set_encrypt_key.argtypes = (c_char_p, c_int, c_char_p)
15
19
libcrypto.AES_ctr128_encrypt.argtypes = (c_char_p, c_char_p, c_int, c_char_p, c_char_p, c_char_p, POINTER(c_uint))
 
20
libcrypto.RAND_bytes.argtypes = (c_char_p, c_int)
 
21
libcrypto.RAND_bytes.restype = c_int
16
22
 
17
23
_int = struct.Struct('>I')
18
24
_long = struct.Struct('>Q')
22
28
long_to_bytes = lambda x: _long.pack(x)
23
29
 
24
30
 
 
31
def num_aes_blocks(length):
 
32
    """Return the number of AES blocks required to encrypt/decrypt *length* bytes of data
 
33
    """
 
34
    return (length + 15) // 16
 
35
 
 
36
 
25
37
def pbkdf2_sha256(password, salt, iterations, size):
 
38
    """Password based key derivation function 2 (RFC2898)
 
39
    """
26
40
    key = create_string_buffer(size)
27
41
    rv = libcrypto.PKCS5_PBKDF2_HMAC(password, len(password), salt, len(salt), iterations, libcrypto.EVP_sha256(), size, key)
28
42
    if not rv:
34
48
    """Return n cryptographically strong pseudo-random bytes
35
49
    """
36
50
    buf = create_string_buffer(n)
37
 
    if not libcrypto.RAND_bytes(buf, n):
 
51
    if libcrypto.RAND_bytes(buf, n) < 1:
38
52
        raise Exception('RAND_bytes failed')
39
53
    return buf.raw
40
54
 
41
55
 
42
56
class AES:
 
57
    """A thin wrapper around the OpenSSL AES CTR_MODE cipher
 
58
    """
43
59
    def __init__(self, key, iv=None):
44
60
        self.key = create_string_buffer(2000)
45
61
        self.iv = create_string_buffer(16)