crypto.pyx 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. TAG_SIZE = 16 # bytes; 128 bits is the maximum allowed value. see "hack" below.
  8. IV_SIZE = 16 # bytes; 128 bits
  9. cdef extern from "openssl/rand.h":
  10. int RAND_bytes(unsigned char *buf, int num)
  11. cdef extern from "openssl/evp.h":
  12. ctypedef struct EVP_MD:
  13. pass
  14. ctypedef struct EVP_CIPHER:
  15. pass
  16. ctypedef struct EVP_CIPHER_CTX:
  17. unsigned char *iv
  18. pass
  19. ctypedef struct ENGINE:
  20. pass
  21. const EVP_MD *EVP_sha256()
  22. const EVP_CIPHER *EVP_aes_256_gcm()
  23. void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *a)
  24. void EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *a)
  25. int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl,
  26. const unsigned char *key, const unsigned char *iv)
  27. int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl,
  28. const unsigned char *key, const unsigned char *iv)
  29. int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
  30. const unsigned char *in_, int inl)
  31. int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
  32. const unsigned char *in_, int inl)
  33. int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
  34. int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
  35. int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, unsigned char *ptr)
  36. int PKCS5_PBKDF2_HMAC(const char *password, int passwordlen,
  37. const unsigned char *salt, int saltlen, int iter,
  38. const EVP_MD *digest,
  39. int keylen, unsigned char *out)
  40. int EVP_CTRL_GCM_GET_TAG
  41. int EVP_CTRL_GCM_SET_TAG
  42. int EVP_CTRL_GCM_SET_IVLEN
  43. import struct
  44. _int = struct.Struct('>I')
  45. _long = struct.Struct('>Q')
  46. bytes_to_int = lambda x, offset=0: _int.unpack_from(x, offset)[0]
  47. bytes_to_long = lambda x, offset=0: _long.unpack_from(x, offset)[0]
  48. long_to_bytes = lambda x: _long.pack(x)
  49. def num_aes_blocks(length):
  50. """Return the number of AES blocks required to encrypt/decrypt *length* bytes of data.
  51. Note: this is only correct for modes without padding, like AES-CTR.
  52. """
  53. return (length + 15) // 16
  54. def pbkdf2_sha256(password, salt, iterations, size):
  55. """Password based key derivation function 2 (RFC2898)
  56. """
  57. cdef unsigned char *key = <unsigned char *>malloc(size)
  58. if not key:
  59. raise MemoryError
  60. try:
  61. rv = PKCS5_PBKDF2_HMAC(password, len(password), salt, len(salt), iterations, EVP_sha256(), size, key)
  62. if not rv:
  63. raise Exception('PKCS5_PBKDF2_HMAC failed')
  64. return key[:size]
  65. finally:
  66. free(key)
  67. def get_random_bytes(n):
  68. """Return n cryptographically strong pseudo-random bytes
  69. """
  70. cdef unsigned char *buf = <unsigned char *>malloc(n)
  71. if not buf:
  72. raise MemoryError
  73. try:
  74. if RAND_bytes(buf, n) < 1:
  75. raise Exception('RAND_bytes failed')
  76. return buf[:n]
  77. finally:
  78. free(buf)
  79. cdef class AES:
  80. """A thin wrapper around the OpenSSL EVP cipher API
  81. """
  82. cdef EVP_CIPHER_CTX ctx
  83. cdef int is_encrypt
  84. def __cinit__(self, is_encrypt, key, iv=None):
  85. EVP_CIPHER_CTX_init(&self.ctx)
  86. self.is_encrypt = is_encrypt
  87. # Set cipher type and mode
  88. cipher_mode = EVP_aes_256_gcm()
  89. if self.is_encrypt:
  90. if not EVP_EncryptInit_ex(&self.ctx, cipher_mode, NULL, NULL, NULL):
  91. raise Exception('EVP_EncryptInit_ex failed')
  92. else: # decrypt
  93. if not EVP_DecryptInit_ex(&self.ctx, cipher_mode, NULL, NULL, NULL):
  94. raise Exception('EVP_DecryptInit_ex failed')
  95. self.reset(key, iv)
  96. def __dealloc__(self):
  97. EVP_CIPHER_CTX_cleanup(&self.ctx)
  98. def reset(self, key=None, iv=None):
  99. cdef const unsigned char *key2 = NULL
  100. cdef const unsigned char *iv2 = NULL
  101. if key:
  102. key2 = key
  103. if iv:
  104. iv2 = iv
  105. # Set IV length (bytes)
  106. if not EVP_CIPHER_CTX_ctrl(&self.ctx, EVP_CTRL_GCM_SET_IVLEN, IV_SIZE, NULL):
  107. raise Exception('EVP_CIPHER_CTX_ctrl SET IVLEN failed')
  108. # Initialise key and IV
  109. if self.is_encrypt:
  110. if not EVP_EncryptInit_ex(&self.ctx, NULL, NULL, key2, iv2):
  111. raise Exception('EVP_EncryptInit_ex failed')
  112. else: # decrypt
  113. if not EVP_DecryptInit_ex(&self.ctx, NULL, NULL, key2, iv2):
  114. raise Exception('EVP_DecryptInit_ex failed')
  115. def add(self, aad):
  116. cdef int aadl = len(aad)
  117. cdef int outl
  118. # Zero or more calls to specify any AAD
  119. if self.is_encrypt:
  120. if not EVP_EncryptUpdate(&self.ctx, NULL, &outl, aad, aadl):
  121. raise Exception('EVP_EncryptUpdate failed')
  122. else: # decrypt
  123. if not EVP_DecryptUpdate(&self.ctx, NULL, &outl, aad, aadl):
  124. raise Exception('EVP_DecryptUpdate failed')
  125. def compute_tag_and_encrypt(self, data):
  126. cdef int inl = len(data)
  127. cdef int ctl = 0
  128. cdef int outl = 0
  129. # note: modes that use padding, need up to one extra AES block (16B)
  130. cdef unsigned char *out = <unsigned char *>malloc(inl+16)
  131. cdef unsigned char *tag = <unsigned char *>malloc(TAG_SIZE)
  132. if not out:
  133. raise MemoryError
  134. try:
  135. if not EVP_EncryptUpdate(&self.ctx, out, &outl, data, inl):
  136. raise Exception('EVP_EncryptUpdate failed')
  137. ctl = outl
  138. if not EVP_EncryptFinal_ex(&self.ctx, out+ctl, &outl):
  139. raise Exception('EVP_EncryptFinal failed')
  140. ctl += outl
  141. # Get tag
  142. if not EVP_CIPHER_CTX_ctrl(&self.ctx, EVP_CTRL_GCM_GET_TAG, TAG_SIZE, tag):
  143. raise Exception('EVP_CIPHER_CTX_ctrl GET TAG failed')
  144. # hack: caller wants 32B tags (256b), so we give back that amount
  145. return (tag[:TAG_SIZE] + b'\x00'*16), out[:ctl]
  146. finally:
  147. free(tag)
  148. free(out)
  149. def check_tag_and_decrypt(self, tag, data):
  150. cdef int inl = len(data)
  151. cdef int ptl = 0
  152. cdef int outl = 0
  153. # note: modes that use padding, need up to one extra AES block (16B).
  154. # This is what the openssl docs say. I am not sure this is correct,
  155. # but OTOH it will not cause any harm if our buffer is a little bigger.
  156. cdef unsigned char *out = <unsigned char *>malloc(inl+16)
  157. if not out:
  158. raise MemoryError
  159. try:
  160. if not EVP_DecryptUpdate(&self.ctx, out, &outl, data, inl):
  161. raise Exception('EVP_DecryptUpdate failed')
  162. ptl = outl
  163. # Set expected tag value.
  164. if not EVP_CIPHER_CTX_ctrl(&self.ctx, EVP_CTRL_GCM_SET_TAG, TAG_SIZE, tag):
  165. raise Exception('EVP_CIPHER_CTX_ctrl SET TAG failed')
  166. if EVP_DecryptFinal_ex(&self.ctx, out+ptl, &outl) <= 0:
  167. # a failure here means corrupted / tampered tag or data
  168. raise Exception('EVP_DecryptFinal failed')
  169. ptl += outl
  170. return out[:ptl]
  171. finally:
  172. free(out)