1# This file is dual licensed under the terms of the Apache License, Version 2# 2.0, and the BSD License. See the LICENSE file in the root of this repository 3# for complete details. 4 5from __future__ import absolute_import, division, print_function 6 7import pytest 8 9from cryptography.exceptions import AlreadyFinalized, InvalidKey, _Reasons 10from cryptography.hazmat.primitives import hashes 11from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC 12 13from ...doubles import DummyHashAlgorithm 14from ...utils import raises_unsupported_algorithm 15 16 17class TestPBKDF2HMAC(object): 18 def test_already_finalized(self, backend): 19 kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend) 20 kdf.derive(b"password") 21 with pytest.raises(AlreadyFinalized): 22 kdf.derive(b"password2") 23 24 kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend) 25 key = kdf.derive(b"password") 26 with pytest.raises(AlreadyFinalized): 27 kdf.verify(b"password", key) 28 29 kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend) 30 kdf.verify(b"password", key) 31 with pytest.raises(AlreadyFinalized): 32 kdf.verify(b"password", key) 33 34 def test_unsupported_algorithm(self, backend): 35 with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH): 36 PBKDF2HMAC(DummyHashAlgorithm(), 20, b"salt", 10, backend) 37 38 def test_invalid_key(self, backend): 39 kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend) 40 key = kdf.derive(b"password") 41 42 kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend) 43 with pytest.raises(InvalidKey): 44 kdf.verify(b"password2", key) 45 46 def test_unicode_error_with_salt(self, backend): 47 with pytest.raises(TypeError): 48 PBKDF2HMAC(hashes.SHA1(), 20, u"salt", 10, backend) 49 50 def test_unicode_error_with_key_material(self, backend): 51 kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend) 52 with pytest.raises(TypeError): 53 kdf.derive(u"unicode here") 54 55 def test_buffer_protocol(self, backend): 56 kdf = PBKDF2HMAC(hashes.SHA1(), 10, b"salt", 10, backend) 57 data = bytearray(b"data") 58 assert kdf.derive(data) == b"\xe9n\xaa\x81\xbbt\xa4\xf6\x08\xce" 59 60 61def test_invalid_backend(): 62 pretend_backend = object() 63 64 with raises_unsupported_algorithm(_Reasons.BACKEND_MISSING_INTERFACE): 65 PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, pretend_backend) 66