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.
 
 
 
 
 

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