def pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None): if not isinstance(hash_name, str): raise TypeError("expected 'str' for name, but got %s" % type(hash_name)) c_name = _str_to_ffi_buffer(hash_name) digest = lib.EVP_get_digestbyname(c_name) if digest == ffi.NULL: raise ValueError("unsupported hash type") if dklen is None: dklen = lib.EVP_MD_size(digest) if dklen < 1: raise ValueError("key length must be greater than 0.") if dklen >= sys.maxsize: raise OverflowError("key length is too great.") if iterations < 1: raise ValueError("iteration value must be greater than 0.") if iterations >= sys.maxsize: raise OverflowError("iteration value is too great.") buf = ffi.new("unsigned char[]", dklen) c_password = ffi.from_buffer(bytes(password)) c_salt = ffi.from_buffer(bytes(salt)) r = lib.PKCS5_PBKDF2_HMAC(c_password, len(c_password), ffi.cast("unsigned char*",c_salt), len(c_salt), iterations, digest, dklen, buf) if r == 0: raise ValueError return _bytes_with_len(buf, dklen)
def _certificate_to_der(certificate): buf_ptr = ffi.new("unsigned char**") buf_ptr[0] = ffi.NULL length = lib.i2d_X509(certificate, buf_ptr) if length < 0: raise ssl_error(None) try: return _bytes_with_len(ffi.cast("char*", buf_ptr[0]), length) finally: lib.OPENSSL_free(buf_ptr[0])
def _digest(self): ctx = lib.Cryptography_EVP_MD_CTX_new() if ctx == ffi.NULL: raise MemoryError try: with self.lock: if not lib.EVP_MD_CTX_copy_ex(ctx, self.ctx): raise ValueError digest_size = self.digest_size buf = ffi.new("unsigned char[]", digest_size) lib.EVP_DigestFinal_ex(ctx, buf, ffi.NULL) return _bytes_with_len(buf, digest_size) finally: lib.Cryptography_EVP_MD_CTX_free(ctx)