crypto.pyx 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. """A thin OpenSSL wrapper
  2. This could be replaced by PyCrypto or something similar when the performance
  3. of their PBKDF2 implementation is comparable to the OpenSSL version.
  4. """
  5. from libc.stdlib cimport malloc, free
  6. API_VERSION = 2
  7. cdef extern from "openssl/rand.h":
  8. int RAND_bytes(unsigned char *buf,int num)
  9. cdef extern from "openssl/evp.h":
  10. ctypedef struct EVP_MD:
  11. pass
  12. ctypedef struct EVP_CIPHER:
  13. pass
  14. ctypedef struct EVP_CIPHER_CTX:
  15. unsigned char *iv
  16. pass
  17. ctypedef struct ENGINE:
  18. pass
  19. const EVP_MD *EVP_sha256()
  20. const EVP_CIPHER *EVP_aes_256_ctr()
  21. void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *a)
  22. void EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *a)
  23. int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx,const EVP_CIPHER *cipher, ENGINE *impl,
  24. const unsigned char *key, const unsigned char *iv)
  25. int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
  26. int *outl, const unsigned char *in_, int inl)
  27. int PKCS5_PBKDF2_HMAC(const char *password, int passwordlen,
  28. const unsigned char *salt, int saltlen, int iter,
  29. const EVP_MD *digest,
  30. int keylen, unsigned char *out)
  31. import struct
  32. _int = struct.Struct('>I')
  33. _long = struct.Struct('>Q')
  34. bytes_to_int = lambda x, offset=0: _int.unpack_from(x, offset)[0]
  35. bytes_to_long = lambda x, offset=0: _long.unpack_from(x, offset)[0]
  36. long_to_bytes = lambda x: _long.pack(x)
  37. def num_aes_blocks(length):
  38. """Return the number of AES blocks required to encrypt/decrypt *length* bytes of data
  39. """
  40. return (length + 15) // 16
  41. def pbkdf2_sha256(password, salt, iterations, size):
  42. """Password based key derivation function 2 (RFC2898)
  43. """
  44. cdef unsigned char *key = <unsigned char *>malloc(size)
  45. if not key:
  46. raise MemoryError
  47. try:
  48. rv = PKCS5_PBKDF2_HMAC(password, len(password), salt, len(salt), iterations, EVP_sha256(), size, key)
  49. if not rv:
  50. raise Exception('PKCS5_PBKDF2_HMAC failed')
  51. return key[:size]
  52. finally:
  53. free(key)
  54. def get_random_bytes(n):
  55. """Return n cryptographically strong pseudo-random bytes
  56. """
  57. cdef unsigned char *buf = <unsigned char *>malloc(n)
  58. if not buf:
  59. raise MemoryError
  60. try:
  61. if RAND_bytes(buf, n) < 1:
  62. raise Exception('RAND_bytes failed')
  63. return buf[:n]
  64. finally:
  65. free(buf)
  66. cdef class AES:
  67. """A thin wrapper around the OpenSSL EVP cipher API
  68. """
  69. cdef EVP_CIPHER_CTX ctx
  70. def __cinit__(self, key, iv=None):
  71. EVP_CIPHER_CTX_init(&self.ctx)
  72. if not EVP_EncryptInit_ex(&self.ctx, EVP_aes_256_ctr(), NULL, NULL, NULL):
  73. raise Exception('EVP_EncryptInit_ex failed')
  74. self.reset(key, iv)
  75. def __dealloc__(self):
  76. EVP_CIPHER_CTX_cleanup(&self.ctx)
  77. def reset(self, key=None, iv=None):
  78. cdef const unsigned char *key2 = NULL
  79. cdef const unsigned char *iv2 = NULL
  80. if key:
  81. key2 = key
  82. if iv:
  83. iv2 = iv
  84. if not EVP_EncryptInit_ex(&self.ctx, NULL, NULL, key2, iv2):
  85. raise Exception('EVP_EncryptInit_ex failed')
  86. @property
  87. def iv(self):
  88. return self.ctx.iv[:16]
  89. def encrypt(self, data):
  90. cdef int inl = len(data)
  91. cdef int outl
  92. cdef unsigned char *out = <unsigned char *>malloc(inl)
  93. if not out:
  94. raise MemoryError
  95. try:
  96. if not EVP_EncryptUpdate(&self.ctx, out, &outl, data, inl):
  97. raise Exception('EVP_EncryptUpdate failed')
  98. return out[:inl]
  99. finally:
  100. free(out)
  101. decrypt = encrypt