You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

127 lines
4.9 KiB

7 years ago
  1. # Copyright 2013 Donald Stufft and individual contributors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import, division, print_function
  15. import nacl.bindings
  16. from nacl import encoding
  17. from nacl import exceptions as exc
  18. from nacl.utils import EncryptedMessage, StringFixer, random
  19. class SecretBox(encoding.Encodable, StringFixer, object):
  20. """
  21. The SecretBox class encrypts and decrypts messages using the given secret
  22. key.
  23. The ciphertexts generated by :class:`~nacl.secret.Secretbox` include a 16
  24. byte authenticator which is checked as part of the decryption. An invalid
  25. authenticator will cause the decrypt function to raise an exception. The
  26. authenticator is not a signature. Once you've decrypted the message you've
  27. demonstrated the ability to create arbitrary valid message, so messages you
  28. send are repudiable. For non-repudiable messages, sign them after
  29. encryption.
  30. :param key: The secret key used to encrypt and decrypt messages
  31. :param encoder: The encoder class used to decode the given key
  32. :cvar KEY_SIZE: The size that the key is required to be.
  33. :cvar NONCE_SIZE: The size that the nonce is required to be.
  34. """
  35. KEY_SIZE = nacl.bindings.crypto_secretbox_KEYBYTES
  36. NONCE_SIZE = nacl.bindings.crypto_secretbox_NONCEBYTES
  37. def __init__(self, key, encoder=encoding.RawEncoder):
  38. key = encoder.decode(key)
  39. if not isinstance(key, bytes):
  40. raise exc.TypeError("SecretBox must be created from 32 bytes")
  41. if len(key) != self.KEY_SIZE:
  42. raise exc.ValueError(
  43. "The key must be exactly %s bytes long" %
  44. self.KEY_SIZE,
  45. )
  46. self._key = key
  47. def __bytes__(self):
  48. return self._key
  49. def encrypt(self, plaintext, nonce=None, encoder=encoding.RawEncoder):
  50. """
  51. Encrypts the plaintext message using the given `nonce` (or generates
  52. one randomly if omitted) and returns the ciphertext encoded with the
  53. encoder.
  54. .. warning:: It is **VITALLY** important that the nonce is a nonce,
  55. i.e. it is a number used only once for any given key. If you fail
  56. to do this, you compromise the privacy of the messages encrypted.
  57. Give your nonces a different prefix, or have one side use an odd
  58. counter and one an even counter. Just make sure they are different.
  59. :param plaintext: [:class:`bytes`] The plaintext message to encrypt
  60. :param nonce: [:class:`bytes`] The nonce to use in the encryption
  61. :param encoder: The encoder to use to encode the ciphertext
  62. :rtype: [:class:`nacl.utils.EncryptedMessage`]
  63. """
  64. if nonce is None:
  65. nonce = random(self.NONCE_SIZE)
  66. if len(nonce) != self.NONCE_SIZE:
  67. raise exc.ValueError(
  68. "The nonce must be exactly %s bytes long" % self.NONCE_SIZE,
  69. )
  70. ciphertext = nacl.bindings.crypto_secretbox(plaintext,
  71. nonce, self._key)
  72. encoded_nonce = encoder.encode(nonce)
  73. encoded_ciphertext = encoder.encode(ciphertext)
  74. return EncryptedMessage._from_parts(
  75. encoded_nonce,
  76. encoded_ciphertext,
  77. encoder.encode(nonce + ciphertext),
  78. )
  79. def decrypt(self, ciphertext, nonce=None, encoder=encoding.RawEncoder):
  80. """
  81. Decrypts the ciphertext using the `nonce` (explicitly, when passed as a
  82. parameter or implicitly, when omitted, as part of the ciphertext) and
  83. returns the plaintext message.
  84. :param ciphertext: [:class:`bytes`] The encrypted message to decrypt
  85. :param nonce: [:class:`bytes`] The nonce used when encrypting the
  86. ciphertext
  87. :param encoder: The encoder used to decode the ciphertext.
  88. :rtype: [:class:`bytes`]
  89. """
  90. # Decode our ciphertext
  91. ciphertext = encoder.decode(ciphertext)
  92. if nonce is None:
  93. # If we were given the nonce and ciphertext combined, split them.
  94. nonce = ciphertext[:self.NONCE_SIZE]
  95. ciphertext = ciphertext[self.NONCE_SIZE:]
  96. if len(nonce) != self.NONCE_SIZE:
  97. raise exc.ValueError(
  98. "The nonce must be exactly %s bytes long" % self.NONCE_SIZE,
  99. )
  100. plaintext = nacl.bindings.crypto_secretbox_open(ciphertext,
  101. nonce, self._key)
  102. return plaintext

Powered by TurnKey Linux.