pbkdf_pkcs12.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """A simple example how to use PBKDF PKCS #12 algorithm."""
  2. import wolfssl
  3. import os
  4. import random
  5. import string
  6. PASSWORD_LENGTH = 16
  7. SALT_LENGTH = 8
  8. KEY_LENGTH = 16
  9. ITERATIONS = 256
  10. SHA256 = 2 # Hashtype, stands for Sha256 in wolfssl.
  11. def to_c_byte_array(content):
  12. output = wolfssl.byteArray(len(content))
  13. for i, ch in enumerate(content):
  14. output[i] = ord(ch)
  15. return output
  16. password = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(PASSWORD_LENGTH))
  17. salt = os.urandom(SALT_LENGTH)
  18. key = wolfssl.byteArray(KEY_LENGTH)
  19. # params:
  20. # key :: bytearray output
  21. # passwd :: bytearray password that is used to derive the key
  22. # pLen :: password length
  23. # salt :: bytearray salt
  24. # sLen :: salt length
  25. # iterations :: number of iterations
  26. # kLen :: key length
  27. # hashType :: int, SHA256 stands for 2
  28. # purpose :: int, not really sure what it does, 1 was used in the tests
  29. wolfssl.wc_PKCS12_PBKDF(key, to_c_byte_array(password), PASSWORD_LENGTH, to_c_byte_array(salt), SALT_LENGTH, ITERATIONS,
  30. KEY_LENGTH, SHA256, 1)
  31. key = wolfssl.cdata(key, KEY_LENGTH)
  32. assert len(key) == KEY_LENGTH, "Generated key has length %s, whereas should have length %s" % (len(key), KEY_LENGTH)
  33. print 'Generated key: %s\nfor password: %s' % (key, password)
  34. print 'Bytes:'
  35. print [b for b in key]