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.
 
 
 
 
 

307 lines
8.8 KiB

  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2017 John-Mark Gurney.
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. # 1. Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. # notice, this list of conditions and the following disclaimer in the
  13. # documentation and/or other materials provided with the distribution.
  14. #
  15. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  16. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  19. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  21. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  22. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  23. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  24. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  25. # SUCH DAMAGE.
  26. #
  27. #
  28. '''This is a wrapper around Ed448-Goldilocks.
  29. This module does not follow the standard Crypto modular method
  30. of signing due to the complexity of integration w/ the library, and
  31. that things should be more simple to use.'''
  32. __author__ = 'John-Mark Gurney'
  33. __copyright__ = 'Copyright 2017 John-Mark Gurney'''
  34. __license__ = 'BSD'
  35. __version__ = '0.1'
  36. __status__ = 'alpha'
  37. import array
  38. import os
  39. import os.path
  40. import sys
  41. import unittest
  42. import warnings
  43. from ctypes import *
  44. try:
  45. _dname = os.path.dirname(__file__)
  46. if not _dname:
  47. _dname = '.'
  48. _path = os.path.join(_dname, 'libdecaf.so')
  49. decaf = CDLL(_path)
  50. except OSError as e: # pragma: no cover
  51. import warnings
  52. warnings.warn('libdecaf.so not installed.')
  53. raise ImportError(str(e))
  54. DECAF_EDDSA_448_PUBLIC_BYTES = 57
  55. DECAF_EDDSA_448_PRIVATE_BYTES = DECAF_EDDSA_448_PUBLIC_BYTES
  56. DECAF_EDDSA_448_SIGNATURE_BYTES = DECAF_EDDSA_448_PUBLIC_BYTES + DECAF_EDDSA_448_PRIVATE_BYTES
  57. # Types
  58. ed448_pubkey_t = c_uint8 * DECAF_EDDSA_448_PUBLIC_BYTES
  59. ed448_privkey_t = c_uint8 * DECAF_EDDSA_448_PRIVATE_BYTES
  60. ed448_sig_t = c_uint8 * DECAF_EDDSA_448_SIGNATURE_BYTES
  61. c_uint8_p = POINTER(c_uint8)
  62. decaf_error_t = c_int
  63. # Data
  64. try:
  65. DECAF_ED448_NO_CONTEXT = POINTER(c_uint8).in_dll(decaf, 'DECAF_ED448_NO_CONTEXT')
  66. except ValueError:
  67. DECAF_ED448_NO_CONTEXT = None
  68. funs = {
  69. 'decaf_ed448_derive_public_key': (None, [ ed448_pubkey_t, ed448_privkey_t]),
  70. 'decaf_ed448_sign': (None, [ ed448_sig_t, ed448_privkey_t, ed448_pubkey_t, c_uint8_p, c_size_t, c_uint8, c_uint8_p, c_uint8 ]),
  71. 'decaf_ed448_verify': (decaf_error_t, [ ed448_sig_t, ed448_pubkey_t, c_uint8_p, c_size_t, c_uint8, c_uint8_p, c_uint8 ]),
  72. }
  73. for i in funs:
  74. f = getattr(decaf, i)
  75. f.restype, f.argtypes = funs[i]
  76. def _makeba(s):
  77. r = (c_ubyte * len(s))()
  78. r[:] = array.array('B', s)
  79. return r
  80. def _makestr(a):
  81. # XXX - because python3 sucks, and unittest doesn't offer
  82. # ability to silence stupid warnings, hide the tostring
  83. # DeprecationWarning.
  84. with warnings.catch_warnings():
  85. warnings.simplefilter('ignore')
  86. return array.array('B', a).tostring()
  87. def _ed448_privkey():
  88. return _makeba(os.urandom(DECAF_EDDSA_448_PRIVATE_BYTES))
  89. class EDDSA448(object):
  90. _PUBLIC_SIZE = DECAF_EDDSA_448_PUBLIC_BYTES
  91. _PRIVATE_SIZE = DECAF_EDDSA_448_PRIVATE_BYTES
  92. _SIG_SIZE = DECAF_EDDSA_448_SIGNATURE_BYTES
  93. def __init__(self, priv=None, pub=None):
  94. '''Generate a new sign or verify object. At least one
  95. of priv or pub MUST be specified.
  96. If pub is not specified, it will be generated from priv.
  97. If both are specified, there is no verification that pub
  98. is the public key for priv.
  99. It is recommended that you use the generate method to
  100. generate a new key.'''
  101. if priv is None and pub is None:
  102. raise ValueError('at least one of priv or pub must be specified.')
  103. if priv is not None:
  104. try:
  105. priv = _makeba(priv)
  106. except Exception as e:
  107. raise ValueError('priv must be a byte string', e)
  108. self._priv = priv
  109. if self._priv is not None and pub is None:
  110. self._pub = ed448_pubkey_t()
  111. decaf.decaf_ed448_derive_public_key(self._pub, self._priv)
  112. else:
  113. self._pub = _makeba(pub)
  114. @classmethod
  115. def generate(cls):
  116. '''Generate a signing object w/ a newly generated key.'''
  117. return cls(priv=_ed448_privkey())
  118. def has_private(self):
  119. '''Returns True if object has private key.'''
  120. return self._priv is not None
  121. def public_key(self):
  122. '''Returns a new object w/o the private key. This new
  123. object will have the public part and can be used for
  124. verifying messages'''
  125. return self.__class__(pub=self._pub)
  126. def export_key(self, format):
  127. '''Export the key. The only format supported is 'raw'.
  128. If has_private is True, then the private part will be
  129. exported. If it is False, then the public part will be.
  130. There is no indication on the output if the key is
  131. public or private. It must be tracked independantly
  132. of the data.'''
  133. if format == 'raw':
  134. if self._priv is None:
  135. return _makestr(self._pub)
  136. else:
  137. return _makestr(self._priv)
  138. else:
  139. raise ValueError('unsupported format: %s' % repr(format))
  140. @staticmethod
  141. def _makectxargs(ctx):
  142. if ctx is None:
  143. ctxargs = (DECAF_ED448_NO_CONTEXT, 0)
  144. else:
  145. ctxargs = (_makeba(ctx), len(ctx))
  146. return ctxargs
  147. def sign(self, msg, ctx=None):
  148. '''Returns a signature over the message. Requires that has_private returns True.'''
  149. sig = ed448_sig_t()
  150. ctxargs = self._makectxargs(ctx)
  151. decaf.decaf_ed448_sign(sig, self._priv, self._pub, _makeba(msg), len(msg), 0, *ctxargs)
  152. return _makestr(sig)
  153. def verify(self, sig, msg, ctx=None):
  154. '''Raises an error if sig is not valid for msg.'''
  155. _sig = ed448_sig_t()
  156. _sig[:] = array.array('B', sig)
  157. ctxargs = self._makectxargs(ctx)
  158. if not decaf.decaf_ed448_verify(_sig, self._pub, _makeba(msg), len(msg), 0, *ctxargs):
  159. raise ValueError('signature is not valid')
  160. def generate(curve='ed448'):
  161. return EDDSA448.generate()
  162. class TestEd448(unittest.TestCase):
  163. def test_init(self):
  164. self.assertRaises(ValueError, EDDSA448)
  165. def test_gen(self):
  166. key = generate(curve='ed448')
  167. self.assertIsInstance(key, EDDSA448)
  168. self.assertTrue(key.has_private())
  169. pubkey = key.public_key()
  170. self.assertFalse(pubkey.has_private())
  171. def test_keyexport(self):
  172. # Generate key and export
  173. key = generate(curve='ed448')
  174. privkey = key.export_key('raw')
  175. # Generate signature
  176. message = b'sdlkfjsdf'
  177. sig = key.sign(message)
  178. # Verify that the key can be imported and verifies
  179. key2 = EDDSA448(privkey)
  180. key2.verify(sig, message)
  181. # Export the public key
  182. keypub = key.public_key()
  183. pubkey = keypub.export_key('raw')
  184. # Verify that the public key can be imported and verifies
  185. key3 = EDDSA448(pub=pubkey)
  186. key3.verify(sig, message)
  187. self.assertRaises(ValueError, key.export_key, 'PEM')
  188. def test_keyimportexport(self):
  189. privkey = b'1' * DECAF_EDDSA_448_PRIVATE_BYTES
  190. key = EDDSA448(privkey)
  191. self.assertEqual(key.export_key(format='raw'), privkey)
  192. key = EDDSA448(pub=b'1' * DECAF_EDDSA_448_PUBLIC_BYTES)
  193. self.assertRaises(ValueError, EDDSA448, priv=u'1' * DECAF_EDDSA_448_PRIVATE_BYTES)
  194. def test_sig(self):
  195. key = generate()
  196. message = b'this is a test message for signing'
  197. sig = key.sign(message)
  198. # Make sure sig is a string of bytes
  199. self.assertIsInstance(sig, bytes)
  200. self.assertEqual(len(sig), EDDSA448._SIG_SIZE)
  201. # Make sure sig is valid
  202. key.verify(sig, message)
  203. # Make sure sig is valid for public only version
  204. pubkey = key.public_key()
  205. pubkey.verify(sig, message)
  206. # Ensure that the wrong message fails
  207. message = b'this is the wrong message'
  208. self.assertRaises(ValueError, pubkey.verify, sig, message)
  209. def test_ctx(self):
  210. key = generate()
  211. message = b'foobar'
  212. ctx = b'contexta'
  213. sig = key.sign(message, ctx)
  214. # Make sure it verifies correctly
  215. key.verify(sig, message, ctx)
  216. # Make sure it fails w/o context
  217. self.assertRaises(ValueError, key.verify, sig, message)
  218. # Make sure it fails w/ invalid/different context
  219. self.assertRaises(ValueError, key.verify, sig, message, ctx + b'a')
  220. class TestBasicLib(unittest.TestCase):
  221. def test_basic(self):
  222. priv = _ed448_privkey()
  223. pub = ed448_pubkey_t()
  224. decaf.decaf_ed448_derive_public_key(pub, priv)
  225. message = b'this is a test message'
  226. sig = ed448_sig_t()
  227. decaf.decaf_ed448_sign(sig, priv, pub, _makeba(message), len(message), 0, None, 0)
  228. r = decaf.decaf_ed448_verify(sig, pub, _makeba(message), len(message), 0, None, 0)
  229. self.assertTrue(r)
  230. message = b'aofeijseflj'
  231. r = decaf.decaf_ed448_verify(sig, pub, _makeba(message), len(message), 0, None, 0)
  232. self.assertFalse(r)