test_import_ECC.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 binascii import unhexlify
  32. from Cryptodome.SelfTest.st_common import list_test_cases
  33. from Cryptodome.Util._file_system import pycryptodome_filename
  34. from Cryptodome.Util.py3compat import bord, tostr
  35. from Cryptodome.Util.number import bytes_to_long
  36. from Cryptodome.Hash import SHAKE128
  37. from Cryptodome.PublicKey import ECC
  38. def load_file(filename, mode="rb"):
  39. comps = [ "Cryptodome", "SelfTest", "PublicKey", "test_vectors", "ECC" ]
  40. with open(pycryptodome_filename(comps, filename), mode) as fd:
  41. return fd.read()
  42. def compact(lines):
  43. ext = b"".join(lines)
  44. return unhexlify(tostr(ext).replace(" ", "").replace(":", ""))
  45. def create_ref_keys():
  46. key_lines = load_file("ecc_p256.txt").splitlines()
  47. private_key_d = bytes_to_long(compact(key_lines[2:5]))
  48. public_key_xy = compact(key_lines[6:11])
  49. assert bord(public_key_xy[0]) == 4 # Uncompressed
  50. public_key_x = bytes_to_long(public_key_xy[1:33])
  51. public_key_y = bytes_to_long(public_key_xy[33:])
  52. return (ECC.construct(curve="P-256", d=private_key_d),
  53. ECC.construct(curve="P-256", point_x=public_key_x, point_y=public_key_y))
  54. # Create reference key pair
  55. ref_private, ref_public = create_ref_keys()
  56. def get_fixed_prng():
  57. return SHAKE128.new().update(b"SEED").read
  58. class TestImport(unittest.TestCase):
  59. def test_import_public_der(self):
  60. key_file = load_file("ecc_p256_public.der")
  61. key = ECC._import_subjectPublicKeyInfo(key_file)
  62. self.assertEqual(ref_public, key)
  63. key = ECC._import_der(key_file, None)
  64. self.assertEqual(ref_public, key)
  65. key = ECC.import_key(key_file)
  66. self.assertEqual(ref_public, key)
  67. def test_import_private_der(self):
  68. key_file = load_file("ecc_p256_private.der")
  69. key = ECC._import_private_der(key_file, None)
  70. self.assertEqual(ref_private, key)
  71. key = ECC._import_der(key_file, None)
  72. self.assertEqual(ref_private, key)
  73. key = ECC.import_key(key_file)
  74. self.assertEqual(ref_private, key)
  75. def test_import_private_pkcs8_clear(self):
  76. key_file = load_file("ecc_p256_private_p8_clear.der")
  77. key = ECC._import_der(key_file, None)
  78. self.assertEqual(ref_private, key)
  79. key = ECC.import_key(key_file)
  80. self.assertEqual(ref_private, key)
  81. def test_import_private_pkcs8_in_pem_clear(self):
  82. key_file = load_file("ecc_p256_private_p8_clear.pem")
  83. key = ECC.import_key(key_file)
  84. self.assertEqual(ref_private, key)
  85. def test_import_private_pkcs8_encrypted_1(self):
  86. key_file = load_file("ecc_p256_private_p8.der")
  87. key = ECC._import_der(key_file, "secret")
  88. self.assertEqual(ref_private, key)
  89. key = ECC.import_key(key_file, "secret")
  90. self.assertEqual(ref_private, key)
  91. def test_import_private_pkcs8_encrypted_2(self):
  92. key_file = load_file("ecc_p256_private_p8.pem")
  93. key = ECC.import_key(key_file, "secret")
  94. self.assertEqual(ref_private, key)
  95. def test_import_x509_der(self):
  96. key_file = load_file("ecc_p256_x509.der")
  97. key = ECC._import_der(key_file, None)
  98. self.assertEqual(ref_public, key)
  99. key = ECC.import_key(key_file)
  100. self.assertEqual(ref_public, key)
  101. def test_import_public_pem(self):
  102. key_file = load_file("ecc_p256_public.pem")
  103. key = ECC.import_key(key_file)
  104. self.assertEqual(ref_public, key)
  105. def test_import_private_pem(self):
  106. key_file = load_file("ecc_p256_private.pem")
  107. key = ECC.import_key(key_file)
  108. self.assertEqual(ref_private, key)
  109. def test_import_private_pem_encrypted(self):
  110. for algo in "des3", : # TODO: , "aes128", "aes192", "aes256_gcm":
  111. key_file = load_file("ecc_p256_private_enc_%s.pem" % algo)
  112. key = ECC.import_key(key_file, "secret")
  113. self.assertEqual(ref_private, key)
  114. key = ECC.import_key(tostr(key_file), b"secret")
  115. self.assertEqual(ref_private, key)
  116. def test_import_x509_pem(self):
  117. key_file = load_file("ecc_p256_x509.pem")
  118. key = ECC.import_key(key_file)
  119. self.assertEqual(ref_public, key)
  120. def test_import_openssh(self):
  121. key_file = load_file("ecc_p256_public_openssh.txt")
  122. key = ECC._import_openssh(key_file)
  123. self.assertEqual(ref_public, key)
  124. key = ECC.import_key(key_file)
  125. self.assertEqual(ref_public, key)
  126. class TestExport(unittest.TestCase):
  127. def test_export_public_der_uncompressed(self):
  128. key_file = load_file("ecc_p256_public.der")
  129. encoded = ref_public._export_subjectPublicKeyInfo(False)
  130. self.assertEqual(key_file, encoded)
  131. encoded = ref_public.export_key(format="DER")
  132. self.assertEqual(key_file, encoded)
  133. encoded = ref_public.export_key(format="DER", compress=False)
  134. self.assertEqual(key_file, encoded)
  135. def test_export_public_der_compressed(self):
  136. key_file = load_file("ecc_p256_public.der")
  137. pub_key = ECC.import_key(key_file)
  138. key_file_compressed = pub_key.export_key(format="DER", compress=True)
  139. key_file_compressed_ref = load_file("ecc_p256_public_compressed.der")
  140. self.assertEqual(key_file_compressed, key_file_compressed_ref)
  141. def test_export_private_der(self):
  142. key_file = load_file("ecc_p256_private.der")
  143. encoded = ref_private._export_private_der()
  144. self.assertEqual(key_file, encoded)
  145. # ---
  146. encoded = ref_private.export_key(format="DER", use_pkcs8=False)
  147. self.assertEqual(key_file, encoded)
  148. def test_export_private_pkcs8_clear(self):
  149. key_file = load_file("ecc_p256_private_p8_clear.der")
  150. encoded = ref_private._export_pkcs8()
  151. self.assertEqual(key_file, encoded)
  152. # ---
  153. encoded = ref_private.export_key(format="DER")
  154. self.assertEqual(key_file, encoded)
  155. def test_export_private_pkcs8_encrypted(self):
  156. encoded = ref_private._export_pkcs8(passphrase="secret",
  157. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
  158. # This should prove that the output is password-protected
  159. self.assertRaises(ValueError, ECC._import_pkcs8, encoded, None)
  160. decoded = ECC._import_pkcs8(encoded, "secret")
  161. self.assertEqual(ref_private, decoded)
  162. # ---
  163. encoded = ref_private.export_key(format="DER",
  164. passphrase="secret",
  165. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
  166. decoded = ECC.import_key(encoded, "secret")
  167. self.assertEqual(ref_private, decoded)
  168. def test_export_public_pem_uncompressed(self):
  169. key_file = load_file("ecc_p256_public.pem", "rt").strip()
  170. encoded = ref_private._export_public_pem(False)
  171. self.assertEqual(key_file, encoded)
  172. # ---
  173. encoded = ref_public.export_key(format="PEM")
  174. self.assertEqual(key_file, encoded)
  175. encoded = ref_public.export_key(format="PEM", compress=False)
  176. self.assertEqual(key_file, encoded)
  177. def test_export_public_pem_compressed(self):
  178. key_file = load_file("ecc_p256_public.pem", "rt").strip()
  179. pub_key = ECC.import_key(key_file)
  180. key_file_compressed = pub_key.export_key(format="PEM", compress=True)
  181. key_file_compressed_ref = load_file("ecc_p256_public_compressed.pem", "rt").strip()
  182. self.assertEqual(key_file_compressed, key_file_compressed_ref)
  183. def test_export_private_pem_clear(self):
  184. key_file = load_file("ecc_p256_private.pem", "rt").strip()
  185. encoded = ref_private._export_private_pem(None)
  186. self.assertEqual(key_file, encoded)
  187. # ---
  188. encoded = ref_private.export_key(format="PEM", use_pkcs8=False)
  189. self.assertEqual(key_file, encoded)
  190. def test_export_private_pem_encrypted(self):
  191. encoded = ref_private._export_private_pem(passphrase=b"secret")
  192. # This should prove that the output is password-protected
  193. self.assertRaises(ValueError, ECC.import_key, encoded)
  194. assert "EC PRIVATE KEY" in encoded
  195. decoded = ECC.import_key(encoded, "secret")
  196. self.assertEqual(ref_private, decoded)
  197. # ---
  198. encoded = ref_private.export_key(format="PEM",
  199. passphrase="secret",
  200. use_pkcs8=False)
  201. decoded = ECC.import_key(encoded, "secret")
  202. self.assertEqual(ref_private, decoded)
  203. def test_export_private_pkcs8_and_pem_1(self):
  204. # PKCS8 inside PEM with both unencrypted
  205. key_file = load_file("ecc_p256_private_p8_clear.pem", "rt").strip()
  206. encoded = ref_private._export_private_clear_pkcs8_in_clear_pem()
  207. self.assertEqual(key_file, encoded)
  208. # ---
  209. encoded = ref_private.export_key(format="PEM")
  210. self.assertEqual(key_file, encoded)
  211. def test_export_private_pkcs8_and_pem_2(self):
  212. # PKCS8 inside PEM with PKCS8 encryption
  213. encoded = ref_private._export_private_encrypted_pkcs8_in_clear_pem("secret",
  214. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
  215. # This should prove that the output is password-protected
  216. self.assertRaises(ValueError, ECC.import_key, encoded)
  217. assert "ENCRYPTED PRIVATE KEY" in encoded
  218. decoded = ECC.import_key(encoded, "secret")
  219. self.assertEqual(ref_private, decoded)
  220. # ---
  221. encoded = ref_private.export_key(format="PEM",
  222. passphrase="secret",
  223. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
  224. decoded = ECC.import_key(encoded, "secret")
  225. self.assertEqual(ref_private, decoded)
  226. def test_export_openssh_uncompressed(self):
  227. key_file = load_file("ecc_p256_public_openssh.txt", "rt")
  228. encoded = ref_public._export_openssh(False)
  229. self.assertEquals(key_file, encoded)
  230. # ---
  231. encoded = ref_public.export_key(format="OpenSSH")
  232. self.assertEquals(key_file, encoded)
  233. encoded = ref_public.export_key(format="OpenSSH", compress=False)
  234. self.assertEquals(key_file, encoded)
  235. def test_export_openssh_compressed(self):
  236. key_file = load_file("ecc_p256_public_openssh.txt", "rt")
  237. pub_key = ECC.import_key(key_file)
  238. key_file_compressed = pub_key.export_key(format="OpenSSH", compress=True)
  239. assert len(key_file) > len(key_file_compressed)
  240. self.assertEquals(pub_key, ECC.import_key(key_file_compressed))
  241. def test_prng(self):
  242. # Test that password-protected containers use the provided PRNG
  243. encoded1 = ref_private.export_key(format="PEM",
  244. passphrase="secret",
  245. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC",
  246. randfunc=get_fixed_prng())
  247. encoded2 = ref_private.export_key(format="PEM",
  248. passphrase="secret",
  249. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC",
  250. randfunc=get_fixed_prng())
  251. self.assertEquals(encoded1, encoded2)
  252. # ---
  253. encoded1 = ref_private.export_key(format="PEM",
  254. use_pkcs8=False,
  255. passphrase="secret",
  256. randfunc=get_fixed_prng())
  257. encoded2 = ref_private.export_key(format="PEM",
  258. use_pkcs8=False,
  259. passphrase="secret",
  260. randfunc=get_fixed_prng())
  261. self.assertEquals(encoded1, encoded2)
  262. def test_byte_or_string_passphrase(self):
  263. encoded1 = ref_private.export_key(format="PEM",
  264. use_pkcs8=False,
  265. passphrase="secret",
  266. randfunc=get_fixed_prng())
  267. encoded2 = ref_private.export_key(format="PEM",
  268. use_pkcs8=False,
  269. passphrase=b"secret",
  270. randfunc=get_fixed_prng())
  271. self.assertEquals(encoded1, encoded2)
  272. def test_error_params1(self):
  273. # Unknown format
  274. self.assertRaises(ValueError, ref_private.export_key, format="XXX")
  275. # Missing 'protection' parameter when PKCS#8 is used
  276. ref_private.export_key(format="PEM", passphrase="secret",
  277. use_pkcs8=False)
  278. self.assertRaises(ValueError, ref_private.export_key, format="PEM",
  279. passphrase="secret")
  280. # DER format but no PKCS#8
  281. self.assertRaises(ValueError, ref_private.export_key, format="DER",
  282. passphrase="secret",
  283. use_pkcs8=False,
  284. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
  285. # Incorrect parameters for public keys
  286. self.assertRaises(ValueError, ref_public.export_key, format="DER",
  287. use_pkcs8=False)
  288. # Empty password
  289. self.assertRaises(ValueError, ref_private.export_key, format="PEM",
  290. passphrase="", use_pkcs8=False)
  291. self.assertRaises(ValueError, ref_private.export_key, format="PEM",
  292. passphrase="",
  293. protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
  294. # No private keys with OpenSSH
  295. self.assertRaises(ValueError, ref_private.export_key, format="OpenSSH",
  296. passphrase="secret")
  297. def test_unsupported_curve(self):
  298. # openssl ecparam -name secp224r1 -genkey -noout -out strange-curve.pem -conv_form uncompressed
  299. curve = """-----BEGIN EC PRIVATE KEY-----
  300. MGgCAQEEHEi7xTHW+5oT8wgpjoEKV7uwMuY8rt2YUZe4j1SgBwYFK4EEACGhPAM6
  301. AATJgfOG+Bnki8robpNM8MtArji43GU9up4B0x9sVhqB+fZP+hXgV9ITN7YX4E/k
  302. gVnJp9EBND/tHQ==
  303. -----END EC PRIVATE KEY-----"""
  304. from Cryptodome.PublicKey.ECC import UnsupportedEccFeature
  305. try:
  306. ECC.import_key(curve)
  307. except UnsupportedEccFeature as uef:
  308. assert("1.3.132.0.33" in str(uef))
  309. else:
  310. assert(False)
  311. def test_compressed_curve(self):
  312. # Compressed P-256 curve (Y-point is even)
  313. pem1 = """-----BEGIN EC PRIVATE KEY-----
  314. MFcCAQEEIHTuc09jC51xXomV6MVCDN+DpAAvSmaJWZPTEHM6D5H1oAoGCCqGSM49
  315. AwEHoSQDIgACWFuGbHe8yJ43rir7PMTE9w8vHz0BSpXHq90Xi7/s+a0=
  316. -----END EC PRIVATE KEY-----"""
  317. # Compressed P-256 curve (Y-point is odd)
  318. pem2 = """-----BEGIN EC PRIVATE KEY-----
  319. MFcCAQEEIFggiPN9SQP+FAPTCPp08fRUz7rHp2qNBRcBJ1DXhb3ZoAoGCCqGSM49
  320. AwEHoSQDIgADLpph1trTIlVfa8NJvlMUPyWvL+wP+pW3BJITUL/wj9A=
  321. -----END EC PRIVATE KEY-----"""
  322. key1 = ECC.import_key(pem1)
  323. low16 = int(key1.pointQ.y % 65536)
  324. self.assertEqual(low16, 0xA6FC)
  325. key2 = ECC.import_key(pem2)
  326. low16 = int(key2.pointQ.y % 65536)
  327. self.assertEqual(low16, 0x6E57)
  328. def get_tests(config={}):
  329. tests = []
  330. tests += list_test_cases(TestImport)
  331. tests += list_test_cases(TestExport)
  332. return tests
  333. if __name__ == '__main__':
  334. suite = lambda: unittest.TestSuite(get_tests())
  335. unittest.main(defaultTest='suite')