test_nacl.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. # -*- coding: utf-8 -*-
  2. '''
  3. Tests for the nacl execution module
  4. '''
  5. # Import Python libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. # Import Salt libs
  8. import salt.utils.stringutils
  9. import salt.modules.nacl as nacl
  10. # Import Salt Testing libs
  11. from tests.support.mixins import LoaderModuleMockMixin
  12. from tests.support.unit import TestCase
  13. from tests.support.unit import skipIf
  14. try:
  15. import libnacl.secret # pylint: disable=unused-import
  16. import libnacl.sealed # pylint: disable=unused-import
  17. HAS_LIBNACL = True
  18. except ImportError:
  19. HAS_LIBNACL = False
  20. @skipIf(not HAS_LIBNACL, 'skipping test_nacl, libnacl is unavailable')
  21. class NaclTest(TestCase, LoaderModuleMockMixin):
  22. '''
  23. Test the nacl runner
  24. '''
  25. def setup_loader_modules(self):
  26. self.unencrypted_data = salt.utils.stringutils.to_bytes('hello')
  27. self.opts = salt.config.DEFAULT_MINION_OPTS
  28. utils = salt.loader.utils(self.opts)
  29. funcs = salt.loader.minion_mods(self.opts, utils=utils, whitelist=['nacl'])
  30. return {
  31. nacl: {
  32. '__opts__': self.opts,
  33. '__utils__': utils,
  34. '__salt__': funcs
  35. },
  36. }
  37. def setUp(self):
  38. # Generate the keys
  39. ret = nacl.keygen()
  40. self.assertIn('pk', ret)
  41. self.assertIn('sk', ret)
  42. self.pk = ret['pk']
  43. self.sk = ret['sk']
  44. def test_keygen(self):
  45. '''
  46. Test keygen
  47. '''
  48. self.assertEqual(len(self.pk), 44)
  49. self.assertEqual(len(self.sk), 44)
  50. def test_enc_dec(self):
  51. '''
  52. Generate keys, encrypt, then decrypt.
  53. '''
  54. # Encrypt with pk
  55. encrypted_data = nacl.enc(data=self.unencrypted_data, pk=self.pk)
  56. # Decrypt with sk
  57. decrypted_data = nacl.dec(data=encrypted_data, sk=self.sk)
  58. self.assertEqual(self.unencrypted_data, decrypted_data)
  59. def test_sealedbox_enc_dec(self):
  60. '''
  61. Generate keys, encrypt, then decrypt.
  62. '''
  63. # Encrypt with pk
  64. encrypted_data = nacl.sealedbox_encrypt(
  65. data=self.unencrypted_data, pk=self.pk)
  66. # Decrypt with sk
  67. decrypted_data = nacl.sealedbox_decrypt(
  68. data=encrypted_data, sk=self.sk)
  69. self.assertEqual(self.unencrypted_data, decrypted_data)
  70. def test_secretbox_enc_dec(self):
  71. '''
  72. Generate keys, encrypt, then decrypt.
  73. '''
  74. # Encrypt with sk
  75. encrypted_data = nacl.secretbox_encrypt(
  76. data=self.unencrypted_data, sk=self.sk)
  77. # Decrypt with sk
  78. decrypted_data = nacl.secretbox_decrypt(
  79. data=encrypted_data, sk=self.sk)
  80. self.assertEqual(self.unencrypted_data, decrypted_data)