]> www.wagner.pp.ru Git - oss/ctypescrypto.git/blob - ctypescrypto/pbkdf2.py
Python 3 support for modules pbkdf2 pkey ec x509
[oss/ctypescrypto.git] / ctypescrypto / pbkdf2.py
1 """
2 PKCS5 PBKDF2 function.
3
4 """
5
6 from ctypes import c_char_p, c_int, c_void_p, create_string_buffer
7 from ctypescrypto import libcrypto, chartype
8 from ctypescrypto.digest import DigestType
9 from ctypescrypto.exception import LibCryptoError
10
11 __all__ = ['pbkdf2']
12
13 def pbkdf2(password, salt, outlen, digesttype="sha1", iterations=2000):
14     """
15     Interface to PKCS5_PBKDF2_HMAC function
16     Parameters:
17
18     @param password - password to derive key from
19     @param salt - random salt to use for key derivation
20     @param outlen - number of bytes to derive
21     @param digesttype - name of digest to use to use (default sha1)
22     @param iterations - number of iterations to use
23
24     @returns outlen bytes of key material derived from password and salt
25     """
26     dgst = DigestType(digesttype)
27     out = create_string_buffer(outlen)
28     if isinstance(password,chartype):
29         pwd = password.encode("utf-8")
30     else:
31         pwd = password
32     res = libcrypto.PKCS5_PBKDF2_HMAC(pwd, len(pwd), salt, len(salt),
33                                       iterations, dgst.digest, outlen, out)
34     if res <= 0:
35         raise LibCryptoError("error computing PBKDF2")
36     return out.raw
37
38 libcrypto.PKCS5_PBKDF2_HMAC.argtypes = (c_char_p, c_int, c_char_p, c_int, c_int,
39                                         c_void_p, c_int, c_char_p)
40 libcrypto.PKCS5_PBKDF2_HMAC.restupe = c_int