test_import_ECC.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2015, Legrandin <helderijs@gmail.com>
  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. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in
  14. # the documentation and/or other materials provided with the
  15. # distribution.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  27. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. # POSSIBILITY OF SUCH DAMAGE.
  29. # ===================================================================
  30. import unittest
  31. from Crypto.SelfTest.st_common import list_test_cases
  32. from Crypto.Util._file_system import pycryptodome_filename
  33. from Crypto.Util.py3compat import b, unhexlify, bord, tostr
  34. from Crypto.Util.number import bytes_to_long
  35. from Crypto.Hash import SHAKE128
  36. from Crypto.PublicKey import ECC
  37. def load_file(filename, mode="rb"):
  38. fd = open(pycryptodome_filename([
  39. "Crypto",
  40. "SelfTest",
  41. "PublicKey",
  42. "test_vectors",
  43. "ECC",
  44. ], filename), mode)
  45. return fd.read()
  46. def compact(lines):
  47. ext = b("").join(lines)
  48. return unhexlify(tostr(ext).replace(" ", "").replace(":", ""))
  49. def create_ref_keys():
  50. key_lines = load_file("ecc_p256.txt").splitlines()
  51. private_key_d = bytes_to_long(compact(key_lines[2:5]))
  52. public_key_xy = compact(key_lines[6:11])
  53. assert bord(public_key_xy[0]) == 4 # Uncompressed
  54. public_key_x = bytes_to_long(public_key_xy[1:33])
  55. public_key_y = bytes_to_long(public_key_xy[33:])
  56. return (ECC.construct(curve="P-256", d=private_key_d),
  57. ECC.construct(curve="P-256", point_x=public_key_x, point_y=public_key_y))
  58. # Create reference key pair
  59. ref_private, ref_public = create_ref_keys()
  60. def get_fixed_prng():
  61. return SHAKE128.new().update(b("SEED")).read
  62. class TestImport(unittest.TestCase):
  63. def test_import_public_der(self):
  64. key_file = load_file("ecc_p256_public.der")
  65. key = ECC._import_subjectPublicKeyInfo(key_file)
  66. self.assertEqual(ref_public, key)
  67. key = ECC._import_der(key_file, None)
  68. self.assertEqual(ref_public, key)
  69. key = ECC.import_key(key_file)
  70. self.assertEqual(ref_public, key)
  71. def test_import_private_der(self):
  72. key_file = load_file("ecc_p256_private.der")
  73. key = ECC._import_private_der(key_file, None)
  74. self.assertEqual(ref_private, key)
  75. key = ECC._import_der(key_file, None)
  76. self.assertEqual(ref_private, key)
  77. key = ECC.import_key(key_file)
  78. self.assertEqual(ref_private, key)
  79. def test_import_private_pkcs8_clear(self):
  80. key_file = load_file("ecc_p256_private_p8_clear.der")
  81. key = ECC._import_der(key_file, None)
  82. self.assertEqual(ref_private, key)
  83. key = ECC.import_key(key_file)
  84. self.assertEqual(ref_private, key)
  85. def test_import_private_pkcs8_in_pem_clear(self):
  86. key_file = load_file("ecc_p256_private_p8_clear.pem")
  87. key = ECC.import_key(key_file)
  88. self.assertEqual(ref_private, key)
  89. def test_import_private_pkcs8_encrypted_1(self):
  90. key_file = load_file("ecc_p256_private_p8.der")
  91. key = ECC._import_der(key_file, "secret")
  92. self.assertEqual(ref_private, key)
  93. key = ECC.import_key(key_file, "secret")
  94. self.assertEqual(ref_private, key)
  95. def test_import_private_pkcs8_encrypted_2(self):
  96. key_file = load_file("ecc_p256_private_p8.pem")
  97. key = ECC.import_key(key_file, "secret")
  98. self.assertEqual(ref_private, key)
  99. def test_import_x509_der(self):
  100. key_file = load_file("ecc_p256_x509.der")
  101. key = ECC._import_der(key_file, None)
  102. self.assertEqual(ref_public, key)
  103. key = ECC.import_key(key_file)
  104. self.assertEqual(ref_public, key)
  105. def test_import_public_pem(self):
  106. key_file = load_file("ecc_p256_public.pem")
  107. key = ECC.import_key(key_file)
  108. self.assertEqual(ref_public, key)
  109. def test_import_private_pem(self):
  110. key_file = load_file("ecc_p256_private.pem")
  111. key = ECC.import_key(key_file)
  112. self.assertEqual(ref_private, key)
  113. def test_import_private_pem_encrypted(self):
  114. for algo in "des3", : # TODO: , "aes128", "aes192", "aes256_gcm":
  115. key_file = load_file("ecc_p256_private_enc_%s.pem" % algo)
  116. key = ECC.import_key(key_file, "secret")
  117. self.assertEqual(ref_private, key)
  118. key = ECC.import_key(tostr(key_file), b("secret"))
  119. self.assertEqual(ref_private, key)
  120. def test_import_x509_pem(self):
  121. key_file = load_file("ecc_p256_x509.pem")
  122. key = ECC.import_key(key_file)
  123. self.assertEqual(ref_public, key)
  124. def test_import_openssh(self):
  125. key_file = load_file("ecc_p256_public_openssh.txt")
  126. key = ECC._import_openssh(key_file)
  127. self.assertEqual(ref_public, key)
  128. key = ECC.import_key(key_file)
  129. self.assertEqual(ref_public, key)
  130. class TestExport(unittest.TestCase):
  131. def test_export_public_der(self):
  132. key_file = load_file("ecc_p256_public.der")
  133. encoded = ref_public._export_subjectPublicKeyInfo()
  134. self.assertEqual(key_file, encoded)
  135. # ---
  136. encoded = ref_public.export_key(format="DER")
  137. self.assertEqual(key_file, encoded)
  138. def test_export_private_der(self):
  139. key_file = load_file("ecc_p256_private.der")
  140. encoded = ref_private._export_private_der()
  141. self.assertEqual(key_file, encoded)
  142. # ---
  143. encoded = ref_private.export_key(format="DER", use_pkcs8=False)
  144. self.assertEqual(key_file, encoded)
  145. def test_export_private_pkcs8_clear(self):
  146. key_file = load_file("ecc_p256_private_p8_clear.der")
  147. encoded = ref_private._export_pkcs8()
  148. self.assertEqual(key_file, encoded)
  149. # ---
  150. encoded = ref_private.export_key(format="DER")
  151. self.assertEqual(key_file, encoded)
  152. def test_export_private_pkcs8_encrypted(self):
  153. encoded = ref_private._export_pkcs8(passphrase="secret",
  154. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
  155. # This should prove that the output is password-protected
  156. self.assertRaises(ValueError, ECC._import_pkcs8, encoded, None)
  157. decoded = ECC._import_pkcs8(encoded, "secret")
  158. self.assertEqual(ref_private, decoded)
  159. # ---
  160. encoded = ref_private.export_key(format="DER",
  161. passphrase="secret",
  162. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
  163. decoded = ECC.import_key(encoded, "secret")
  164. self.assertEqual(ref_private, decoded)
  165. def test_export_public_pem(self):
  166. key_file = load_file("ecc_p256_public.pem", "rt").strip()
  167. encoded = ref_private._export_public_pem()
  168. self.assertEqual(key_file, encoded)
  169. # ---
  170. encoded = ref_public.export_key(format="PEM")
  171. self.assertEqual(key_file, encoded)
  172. def test_export_private_pem_clear(self):
  173. key_file = load_file("ecc_p256_private.pem", "rt").strip()
  174. encoded = ref_private._export_private_pem(None)
  175. self.assertEqual(key_file, encoded)
  176. # ---
  177. encoded = ref_private.export_key(format="PEM", use_pkcs8=False)
  178. self.assertEqual(key_file, encoded)
  179. def test_export_private_pem_encrypted(self):
  180. encoded = ref_private._export_private_pem(passphrase=b("secret"))
  181. # This should prove that the output is password-protected
  182. self.assertRaises(ValueError, ECC.import_key, encoded)
  183. assert "EC PRIVATE KEY" in encoded
  184. decoded = ECC.import_key(encoded, "secret")
  185. self.assertEqual(ref_private, decoded)
  186. # ---
  187. encoded = ref_private.export_key(format="PEM",
  188. passphrase="secret",
  189. use_pkcs8=False)
  190. decoded = ECC.import_key(encoded, "secret")
  191. self.assertEqual(ref_private, decoded)
  192. def test_export_private_pkcs8_and_pem_1(self):
  193. # PKCS8 inside PEM with both unencrypted
  194. key_file = load_file("ecc_p256_private_p8_clear.pem", "rt").strip()
  195. encoded = ref_private._export_private_clear_pkcs8_in_clear_pem()
  196. self.assertEqual(key_file, encoded)
  197. # ---
  198. encoded = ref_private.export_key(format="PEM")
  199. self.assertEqual(key_file, encoded)
  200. def test_export_private_pkcs8_and_pem_2(self):
  201. # PKCS8 inside PEM with PKCS8 encryption
  202. encoded = ref_private._export_private_encrypted_pkcs8_in_clear_pem("secret",
  203. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
  204. # This should prove that the output is password-protected
  205. self.assertRaises(ValueError, ECC.import_key, encoded)
  206. assert "ENCRYPTED PRIVATE KEY" in encoded
  207. decoded = ECC.import_key(encoded, "secret")
  208. self.assertEqual(ref_private, decoded)
  209. # ---
  210. encoded = ref_private.export_key(format="PEM",
  211. passphrase="secret",
  212. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
  213. decoded = ECC.import_key(encoded, "secret")
  214. self.assertEqual(ref_private, decoded)
  215. def test_export_openssh(self):
  216. key_file = load_file("ecc_p256_public_openssh.txt", "rt")
  217. encoded = ref_public._export_openssh()
  218. self.assertEquals(key_file, encoded)
  219. # ---
  220. encoded = ref_public.export_key(format="OpenSSH")
  221. self.assertEquals(key_file, encoded)
  222. def test_prng(self):
  223. # Test that password-protected containers use the provided PRNG
  224. encoded1 = ref_private.export_key(format="PEM",
  225. passphrase="secret",
  226. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC",
  227. randfunc=get_fixed_prng())
  228. encoded2 = ref_private.export_key(format="PEM",
  229. passphrase="secret",
  230. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC",
  231. randfunc=get_fixed_prng())
  232. self.assertEquals(encoded1, encoded2)
  233. # ---
  234. encoded1 = ref_private.export_key(format="PEM",
  235. use_pkcs8=False,
  236. passphrase="secret",
  237. randfunc=get_fixed_prng())
  238. encoded2 = ref_private.export_key(format="PEM",
  239. use_pkcs8=False,
  240. passphrase="secret",
  241. randfunc=get_fixed_prng())
  242. self.assertEquals(encoded1, encoded2)
  243. def test_byte_or_string_passphrase(self):
  244. encoded1 = ref_private.export_key(format="PEM",
  245. use_pkcs8=False,
  246. passphrase="secret",
  247. randfunc=get_fixed_prng())
  248. encoded2 = ref_private.export_key(format="PEM",
  249. use_pkcs8=False,
  250. passphrase=b("secret"),
  251. randfunc=get_fixed_prng())
  252. self.assertEquals(encoded1, encoded2)
  253. def test_error_params1(self):
  254. # Unknown format
  255. self.assertRaises(ValueError, ref_private.export_key, format="XXX")
  256. # Missing 'protection' parameter when PKCS#8 is used
  257. ref_private.export_key(format="PEM", passphrase="secret",
  258. use_pkcs8=False)
  259. self.assertRaises(ValueError, ref_private.export_key, format="PEM",
  260. passphrase="secret")
  261. # DER format but no PKCS#8
  262. self.assertRaises(ValueError, ref_private.export_key, format="DER",
  263. passphrase="secret",
  264. use_pkcs8=False,
  265. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
  266. # Incorrect parameters for public keys
  267. self.assertRaises(ValueError, ref_public.export_key, format="DER",
  268. use_pkcs8=False)
  269. # Empty password
  270. self.assertRaises(ValueError, ref_private.export_key, format="PEM",
  271. passphrase="", use_pkcs8=False)
  272. self.assertRaises(ValueError, ref_private.export_key, format="PEM",
  273. passphrase="",
  274. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
  275. # No private keys with OpenSSH
  276. self.assertRaises(ValueError, ref_private.export_key, format="OpenSSH",
  277. passphrase="secret")
  278. def get_tests(config={}):
  279. tests = []
  280. tests += list_test_cases(TestImport)
  281. tests += list_test_cases(TestExport)
  282. return tests
  283. if __name__ == '__main__':
  284. suite = lambda: unittest.TestSuite(get_tests())
  285. unittest.main(defaultTest='suite')