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.
 
 
 
 
 

300 lines
8.6 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 unittest
  40. import warnings
  41. import sys
  42. from ctypes import *
  43. try:
  44. decaf = CDLL('../build/lib/libdecaf.so')
  45. except OSError as e: # pragma: no cover
  46. import warnings
  47. warnings.warn('goldilocks.so not installed.')
  48. raise ImportError(str(e))
  49. DECAF_EDDSA_448_PUBLIC_BYTES = 57
  50. DECAF_EDDSA_448_PRIVATE_BYTES = DECAF_EDDSA_448_PUBLIC_BYTES
  51. DECAF_EDDSA_448_SIGNATURE_BYTES = DECAF_EDDSA_448_PUBLIC_BYTES + DECAF_EDDSA_448_PRIVATE_BYTES
  52. # Types
  53. ed448_pubkey_t = c_uint8 * DECAF_EDDSA_448_PUBLIC_BYTES
  54. ed448_privkey_t = c_uint8 * DECAF_EDDSA_448_PRIVATE_BYTES
  55. ed448_sig_t = c_uint8 * DECAF_EDDSA_448_SIGNATURE_BYTES
  56. c_uint8_p = POINTER(c_uint8)
  57. decaf_error_t = c_int
  58. # Data
  59. try:
  60. DECAF_ED448_NO_CONTEXT = POINTER(c_uint8).in_dll(decaf, 'DECAF_ED448_NO_CONTEXT')
  61. except ValueError:
  62. DECAF_ED448_NO_CONTEXT = None
  63. funs = {
  64. 'decaf_ed448_derive_public_key': (None, [ ed448_pubkey_t, ed448_privkey_t]),
  65. '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 ]),
  66. '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 ]),
  67. }
  68. for i in funs:
  69. f = getattr(decaf, i)
  70. f.restype, f.argtypes = funs[i]
  71. def _makeba(s):
  72. r = (c_ubyte * len(s))()
  73. r[:] = array.array('B', s)
  74. return r
  75. def _makestr(a):
  76. # XXX - because python3 sucks, and unittest doesn't offer
  77. # ability to silence stupid warnings, hide the tostring
  78. # DeprecationWarning.
  79. with warnings.catch_warnings():
  80. warnings.simplefilter('ignore')
  81. return array.array('B', a).tostring()
  82. def _ed448_privkey():
  83. return _makeba(os.urandom(DECAF_EDDSA_448_PRIVATE_BYTES))
  84. class EDDSA448(object):
  85. _PUBLIC_SIZE = DECAF_EDDSA_448_PUBLIC_BYTES
  86. _PRIVATE_SIZE = DECAF_EDDSA_448_PRIVATE_BYTES
  87. _SIG_SIZE = DECAF_EDDSA_448_SIGNATURE_BYTES
  88. def __init__(self, priv=None, pub=None):
  89. '''Generate a new sign or verify object. At least one
  90. of priv or pub MUST be specified.
  91. If pub is not specified, it will be generated from priv.
  92. If both are specified, there is no verification that pub
  93. is the public key for priv.
  94. It is recommended that you use the generate method to
  95. generate a new key.'''
  96. if priv is None and pub is None:
  97. raise ValueError('at least one of priv or pub must be specified.')
  98. if priv is not None:
  99. try:
  100. priv = _makeba(priv)
  101. except Exception as e:
  102. raise ValueError('priv must be a byte string', e)
  103. self._priv = priv
  104. if self._priv is not None and pub is None:
  105. self._pub = ed448_pubkey_t()
  106. decaf.decaf_ed448_derive_public_key(self._pub, self._priv)
  107. else:
  108. self._pub = _makeba(pub)
  109. @classmethod
  110. def generate(cls):
  111. '''Generate a signing object w/ a newly generated key.'''
  112. return cls(priv=_ed448_privkey())
  113. def has_private(self):
  114. '''Returns True if object has private key.'''
  115. return self._priv is not None
  116. def public_key(self):
  117. '''Returns a new object w/o the private key. This new
  118. object will have the public part and can be used for
  119. verifying messages'''
  120. return self.__class__(pub=self._pub)
  121. def export_key(self, format):
  122. '''Export the key. The only format supported is 'raw'.
  123. If has_private is True, then the private part will be
  124. exported. If it is False, then the public part will be.
  125. There is no indication on the output if the key is
  126. public or private. It must be tracked independantly
  127. of the data.'''
  128. if format == 'raw':
  129. if self._priv is None:
  130. return _makestr(self._pub)
  131. else:
  132. return _makestr(self._priv)
  133. else:
  134. raise ValueError('unsupported format: %s' % repr(format))
  135. @staticmethod
  136. def _makectxargs(ctx):
  137. if ctx is None:
  138. ctxargs = (DECAF_ED448_NO_CONTEXT, 0)
  139. else:
  140. ctxargs = (_makeba(ctx), len(ctx))
  141. return ctxargs
  142. def sign(self, msg, ctx=None):
  143. '''Returns a signature over the message. Requires that has_private returns True.'''
  144. sig = ed448_sig_t()
  145. ctxargs = self._makectxargs(ctx)
  146. decaf.decaf_ed448_sign(sig, self._priv, self._pub, _makeba(msg), len(msg), 0, *ctxargs)
  147. return _makestr(sig)
  148. def verify(self, sig, msg, ctx=None):
  149. '''Raises an error if sig is not valid for msg.'''
  150. _sig = ed448_sig_t()
  151. _sig[:] = array.array('B', sig)
  152. ctxargs = self._makectxargs(ctx)
  153. if not decaf.decaf_ed448_verify(_sig, self._pub, _makeba(msg), len(msg), 0, *ctxargs):
  154. raise ValueError('signature is not valid')
  155. def generate(curve='ed448'):
  156. return EDDSA448.generate()
  157. class TestEd448(unittest.TestCase):
  158. def test_init(self):
  159. self.assertRaises(ValueError, EDDSA448)
  160. def test_gen(self):
  161. key = generate(curve='ed448')
  162. self.assertIsInstance(key, EDDSA448)
  163. self.assertTrue(key.has_private())
  164. pubkey = key.public_key()
  165. self.assertFalse(pubkey.has_private())
  166. def test_keyexport(self):
  167. # Generate key and export
  168. key = generate(curve='ed448')
  169. privkey = key.export_key('raw')
  170. # Generate signature
  171. message = b'sdlkfjsdf'
  172. sig = key.sign(message)
  173. # Verify that the key can be imported and verifies
  174. key2 = EDDSA448(privkey)
  175. key2.verify(sig, message)
  176. # Export the public key
  177. keypub = key.public_key()
  178. pubkey = keypub.export_key('raw')
  179. # Verify that the public key can be imported and verifies
  180. key3 = EDDSA448(pub=pubkey)
  181. key3.verify(sig, message)
  182. def test_keyimportexport(self):
  183. privkey = b'1' * DECAF_EDDSA_448_PRIVATE_BYTES
  184. key = EDDSA448(privkey)
  185. self.assertEqual(key.export_key(format='raw'), privkey)
  186. key = EDDSA448(pub=b'1' * DECAF_EDDSA_448_PUBLIC_BYTES)
  187. self.assertRaises(ValueError, EDDSA448, priv=u'1' * DECAF_EDDSA_448_PRIVATE_BYTES)
  188. def test_sig(self):
  189. key = generate()
  190. message = b'this is a test message for signing'
  191. sig = key.sign(message)
  192. # Make sure sig is a string of bytes
  193. self.assertIsInstance(sig, bytes)
  194. self.assertEqual(len(sig), EDDSA448._SIG_SIZE)
  195. # Make sure sig is valid
  196. key.verify(sig, message)
  197. # Make sure sig is valid for public only version
  198. pubkey = key.public_key()
  199. pubkey.verify(sig, message)
  200. # Ensure that the wrong message fails
  201. message = b'this is the wrong message'
  202. self.assertRaises(ValueError, pubkey.verify, sig, message)
  203. def test_ctx(self):
  204. key = generate()
  205. message = b'foobar'
  206. ctx = b'contexta'
  207. sig = key.sign(message, ctx)
  208. # Make sure it verifies correctly
  209. key.verify(sig, message, ctx)
  210. # Make sure it fails w/o context
  211. self.assertRaises(ValueError, key.verify, sig, message)
  212. # Make sure it fails w/ invalid/different context
  213. self.assertRaises(ValueError, key.verify, sig, message, ctx + b'a')
  214. class TestBasicLib(unittest.TestCase):
  215. def test_basic(self):
  216. priv = _ed448_privkey()
  217. pub = ed448_pubkey_t()
  218. decaf.decaf_ed448_derive_public_key(pub, priv)
  219. message = b'this is a test message'
  220. sig = ed448_sig_t()
  221. decaf.decaf_ed448_sign(sig, priv, pub, _makeba(message), len(message), 0, None, 0)
  222. r = decaf.decaf_ed448_verify(sig, pub, _makeba(message), len(message), 0, None, 0)
  223. self.assertTrue(r)
  224. message = b'aofeijseflj'
  225. r = decaf.decaf_ed448_verify(sig, pub, _makeba(message), len(message), 0, None, 0)
  226. self.assertFalse(r)