test_import_RSA.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. # -*- coding: utf-8 -*-
  2. #
  3. # SelfTest/PublicKey/test_importKey.py: Self-test for importing RSA keys
  4. #
  5. # ===================================================================
  6. # The contents of this file are dedicated to the public domain. To
  7. # the extent that dedication to the public domain is not available,
  8. # everyone is granted a worldwide, perpetual, royalty-free,
  9. # non-exclusive license to exercise all rights associated with the
  10. # contents of this file for any purpose whatsoever.
  11. # No rights are reserved.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  17. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  18. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  19. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. # ===================================================================
  22. import unittest
  23. import re
  24. from tls.Crypto.PublicKey import RSA
  25. from tls.Crypto.SelfTest.st_common import *
  26. from tls.Crypto.Util.py3compat import *
  27. from tls.Crypto.Util.number import inverse
  28. from tls.Crypto.Util import asn1
  29. from tls.Crypto.Util._file_system import pycryptodome_filename
  30. def load_file(filename, mode="rb"):
  31. comps = [ "Crypto", "SelfTest", "PublicKey", "test_vectors", "RSA" ]
  32. with open(pycryptodome_filename(comps, filename), mode) as fd:
  33. return fd.read()
  34. def der2pem(der, text='PUBLIC'):
  35. import binascii
  36. chunks = [ binascii.b2a_base64(der[i:i+48]) for i in range(0, len(der), 48) ]
  37. pem = b('-----BEGIN %s KEY-----\n' % text)
  38. pem += b('').join(chunks)
  39. pem += b('-----END %s KEY-----' % text)
  40. return pem
  41. class ImportKeyTests(unittest.TestCase):
  42. # 512-bit RSA key generated with openssl
  43. rsaKeyPEM = u'''-----BEGIN RSA PRIVATE KEY-----
  44. MIIBOwIBAAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+TLr7UkvEtFrRhDDKMtuII
  45. q19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQJACUSDEp8RTe32ftq8IwG8
  46. Wojl5mAd1wFiIOrZ/Uv8b963WJOJiuQcVN29vxU5+My9GPZ7RA3hrDBEAoHUDPrI
  47. OQIhAPIPLz4dphiD9imAkivY31Rc5AfHJiQRA7XixTcjEkojAiEAyh/pJHks/Mlr
  48. +rdPNEpotBjfV4M4BkgGAA/ipcmaAjcCIQCHvhwwKVBLzzTscT2HeUdEeBMoiXXK
  49. JACAr3sJQJGxIQIgarRp+m1WSKV1MciwMaTOnbU7wxFs9DP1pva76lYBzgUCIQC9
  50. n0CnZCJ6IZYqSt0H5N7+Q+2Ro64nuwV/OSQfM6sBwQ==
  51. -----END RSA PRIVATE KEY-----'''
  52. # As above, but this is actually an unencrypted PKCS#8 key
  53. rsaKeyPEM8 = u'''-----BEGIN PRIVATE KEY-----
  54. MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAvx4nkAqgiyNRGlwS
  55. ga5tkzEsPv6RP5MuvtSS8S0WtGEMMoy24girX0WsvilQgzKY8xIsGfeEkt7fQPDj
  56. wZAzhQIDAQABAkAJRIMSnxFN7fZ+2rwjAbxaiOXmYB3XAWIg6tn9S/xv3rdYk4mK
  57. 5BxU3b2/FTn4zL0Y9ntEDeGsMEQCgdQM+sg5AiEA8g8vPh2mGIP2KYCSK9jfVFzk
  58. B8cmJBEDteLFNyMSSiMCIQDKH+kkeSz8yWv6t080Smi0GN9XgzgGSAYAD+KlyZoC
  59. NwIhAIe+HDApUEvPNOxxPYd5R0R4EyiJdcokAICvewlAkbEhAiBqtGn6bVZIpXUx
  60. yLAxpM6dtTvDEWz0M/Wm9rvqVgHOBQIhAL2fQKdkInohlipK3Qfk3v5D7ZGjrie7
  61. BX85JB8zqwHB
  62. -----END PRIVATE KEY-----'''
  63. # The same RSA private key as in rsaKeyPEM, but now encrypted
  64. rsaKeyEncryptedPEM=(
  65. # PEM encryption
  66. # With DES and passphrase 'test'
  67. ('test', u'''-----BEGIN RSA PRIVATE KEY-----
  68. Proc-Type: 4,ENCRYPTED
  69. DEK-Info: DES-CBC,AF8F9A40BD2FA2FC
  70. Ckl9ex1kaVEWhYC2QBmfaF+YPiR4NFkRXA7nj3dcnuFEzBnY5XULupqQpQI3qbfA
  71. u8GYS7+b3toWWiHZivHbAAUBPDIZG9hKDyB9Sq2VMARGsX1yW1zhNvZLIiVJzUHs
  72. C6NxQ1IJWOXzTew/xM2I26kPwHIvadq+/VaT8gLQdjdH0jOiVNaevjWnLgrn1mLP
  73. BCNRMdcexozWtAFNNqSzfW58MJL2OdMi21ED184EFytIc1BlB+FZiGZduwKGuaKy
  74. 9bMbdb/1PSvsSzPsqW7KSSrTw6MgJAFJg6lzIYvR5F4poTVBxwBX3+EyEmShiaNY
  75. IRX3TgQI0IjrVuLmvlZKbGWP18FXj7I7k9tSsNOOzllTTdq3ny5vgM3A+ynfAaxp
  76. dysKznQ6P+IoqML1WxAID4aGRMWka+uArOJ148Rbj9s=
  77. -----END RSA PRIVATE KEY-----'''),
  78. # PKCS8 encryption
  79. ('winter', u'''-----BEGIN ENCRYPTED PRIVATE KEY-----
  80. MIIBpjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIeZIsbW3O+JcCAggA
  81. MBQGCCqGSIb3DQMHBAgSM2p0D8FilgSCAWBhFyP2tiGKVpGj3mO8qIBzinU60ApR
  82. 3unvP+N6j7LVgnV2lFGaXbJ6a1PbQXe+2D6DUyBLo8EMXrKKVLqOMGkFMHc0UaV6
  83. R6MmrsRDrbOqdpTuVRW+NVd5J9kQQh4xnfU/QrcPPt7vpJvSf4GzG0n666Ki50OV
  84. M/feuVlIiyGXY6UWdVDpcOV72cq02eNUs/1JWdh2uEBvA9fCL0c07RnMrdT+CbJQ
  85. NjJ7f8ULtp7xvR9O3Al/yJ4Wv3i4VxF1f3MCXzhlUD4I0ONlr0kJWgeQ80q/cWhw
  86. ntvgJwnCn2XR1h6LA8Wp+0ghDTsL2NhJpWd78zClGhyU4r3hqu1XDjoXa7YCXCix
  87. jCV15+ViDJzlNCwg+W6lRg18sSLkCT7alviIE0U5tHc6UPbbHwT5QqAxAABaP+nZ
  88. CGqJGyiwBzrKebjgSm/KRd4C91XqcsysyH2kKPfT51MLAoD4xelOURBP
  89. -----END ENCRYPTED PRIVATE KEY-----'''
  90. ),
  91. )
  92. rsaPublicKeyPEM = u'''-----BEGIN PUBLIC KEY-----
  93. MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+T
  94. Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQ==
  95. -----END PUBLIC KEY-----'''
  96. # Obtained using 'ssh-keygen -i -m PKCS8 -f rsaPublicKeyPEM'
  97. rsaPublicKeyOpenSSH = b('''ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQC/HieQCqCLI1EaXBKBrm2TMSw+/pE/ky6+1JLxLRa0YQwyjLbiCKtfRay+KVCDMpjzEiwZ94SS3t9A8OPBkDOF comment\n''')
  98. # The private key, in PKCS#1 format encoded with DER
  99. rsaKeyDER = a2b_hex(
  100. '''3082013b020100024100bf1e27900aa08b23511a5c1281ae6d93312c3efe
  101. 913f932ebed492f12d16b4610c328cb6e208ab5f45acbe2950833298f312
  102. 2c19f78492dedf40f0e3c190338502030100010240094483129f114dedf6
  103. 7edabc2301bc5a88e5e6601dd7016220ead9fd4bfc6fdeb75893898ae41c
  104. 54ddbdbf1539f8ccbd18f67b440de1ac30440281d40cfac839022100f20f
  105. 2f3e1da61883f62980922bd8df545ce407c726241103b5e2c53723124a23
  106. 022100ca1fe924792cfcc96bfab74f344a68b418df578338064806000fe2
  107. a5c99a023702210087be1c3029504bcf34ec713d877947447813288975ca
  108. 240080af7b094091b12102206ab469fa6d5648a57531c8b031a4ce9db53b
  109. c3116cf433f5a6f6bbea5601ce05022100bd9f40a764227a21962a4add07
  110. e4defe43ed91a3ae27bb057f39241f33ab01c1
  111. '''.replace(" ",""))
  112. # The private key, in unencrypted PKCS#8 format encoded with DER
  113. rsaKeyDER8 = a2b_hex(
  114. '''30820155020100300d06092a864886f70d01010105000482013f3082013
  115. b020100024100bf1e27900aa08b23511a5c1281ae6d93312c3efe913f932
  116. ebed492f12d16b4610c328cb6e208ab5f45acbe2950833298f3122c19f78
  117. 492dedf40f0e3c190338502030100010240094483129f114dedf67edabc2
  118. 301bc5a88e5e6601dd7016220ead9fd4bfc6fdeb75893898ae41c54ddbdb
  119. f1539f8ccbd18f67b440de1ac30440281d40cfac839022100f20f2f3e1da
  120. 61883f62980922bd8df545ce407c726241103b5e2c53723124a23022100c
  121. a1fe924792cfcc96bfab74f344a68b418df578338064806000fe2a5c99a0
  122. 23702210087be1c3029504bcf34ec713d877947447813288975ca240080a
  123. f7b094091b12102206ab469fa6d5648a57531c8b031a4ce9db53bc3116cf
  124. 433f5a6f6bbea5601ce05022100bd9f40a764227a21962a4add07e4defe4
  125. 3ed91a3ae27bb057f39241f33ab01c1
  126. '''.replace(" ",""))
  127. rsaPublicKeyDER = a2b_hex(
  128. '''305c300d06092a864886f70d0101010500034b003048024100bf1e27900a
  129. a08b23511a5c1281ae6d93312c3efe913f932ebed492f12d16b4610c328c
  130. b6e208ab5f45acbe2950833298f3122c19f78492dedf40f0e3c190338502
  131. 03010001
  132. '''.replace(" ",""))
  133. n = int('BF 1E 27 90 0A A0 8B 23 51 1A 5C 12 81 AE 6D 93 31 2C 3E FE 91 3F 93 2E BE D4 92 F1 2D 16 B4 61 0C 32 8C B6 E2 08 AB 5F 45 AC BE 29 50 83 32 98 F3 12 2C 19 F7 84 92 DE DF 40 F0 E3 C1 90 33 85'.replace(" ",""),16)
  134. e = 65537
  135. d = int('09 44 83 12 9F 11 4D ED F6 7E DA BC 23 01 BC 5A 88 E5 E6 60 1D D7 01 62 20 EA D9 FD 4B FC 6F DE B7 58 93 89 8A E4 1C 54 DD BD BF 15 39 F8 CC BD 18 F6 7B 44 0D E1 AC 30 44 02 81 D4 0C FA C8 39'.replace(" ",""),16)
  136. p = int('00 F2 0F 2F 3E 1D A6 18 83 F6 29 80 92 2B D8 DF 54 5C E4 07 C7 26 24 11 03 B5 E2 C5 37 23 12 4A 23'.replace(" ",""),16)
  137. q = int('00 CA 1F E9 24 79 2C FC C9 6B FA B7 4F 34 4A 68 B4 18 DF 57 83 38 06 48 06 00 0F E2 A5 C9 9A 02 37'.replace(" ",""),16)
  138. # This is q^{-1} mod p). fastmath and slowmath use pInv (p^{-1}
  139. # mod q) instead!
  140. qInv = int('00 BD 9F 40 A7 64 22 7A 21 96 2A 4A DD 07 E4 DE FE 43 ED 91 A3 AE 27 BB 05 7F 39 24 1F 33 AB 01 C1'.replace(" ",""),16)
  141. pInv = inverse(p,q)
  142. def testImportKey1(self):
  143. """Verify import of RSAPrivateKey DER SEQUENCE"""
  144. key = RSA.importKey(self.rsaKeyDER)
  145. self.failUnless(key.has_private())
  146. self.assertEqual(key.n, self.n)
  147. self.assertEqual(key.e, self.e)
  148. self.assertEqual(key.d, self.d)
  149. self.assertEqual(key.p, self.p)
  150. self.assertEqual(key.q, self.q)
  151. def testImportKey2(self):
  152. """Verify import of SubjectPublicKeyInfo DER SEQUENCE"""
  153. key = RSA.importKey(self.rsaPublicKeyDER)
  154. self.failIf(key.has_private())
  155. self.assertEqual(key.n, self.n)
  156. self.assertEqual(key.e, self.e)
  157. def testImportKey3unicode(self):
  158. """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as unicode"""
  159. key = RSA.importKey(self.rsaKeyPEM)
  160. self.assertEqual(key.has_private(),True) # assert_
  161. self.assertEqual(key.n, self.n)
  162. self.assertEqual(key.e, self.e)
  163. self.assertEqual(key.d, self.d)
  164. self.assertEqual(key.p, self.p)
  165. self.assertEqual(key.q, self.q)
  166. def testImportKey3bytes(self):
  167. """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as byte string"""
  168. key = RSA.importKey(b(self.rsaKeyPEM))
  169. self.assertEqual(key.has_private(),True) # assert_
  170. self.assertEqual(key.n, self.n)
  171. self.assertEqual(key.e, self.e)
  172. self.assertEqual(key.d, self.d)
  173. self.assertEqual(key.p, self.p)
  174. self.assertEqual(key.q, self.q)
  175. def testImportKey4unicode(self):
  176. """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as unicode"""
  177. key = RSA.importKey(self.rsaPublicKeyPEM)
  178. self.assertEqual(key.has_private(),False) # failIf
  179. self.assertEqual(key.n, self.n)
  180. self.assertEqual(key.e, self.e)
  181. def testImportKey4bytes(self):
  182. """Verify import of SubjectPublicKeyInfo DER SEQUENCE, encoded with PEM as byte string"""
  183. key = RSA.importKey(b(self.rsaPublicKeyPEM))
  184. self.assertEqual(key.has_private(),False) # failIf
  185. self.assertEqual(key.n, self.n)
  186. self.assertEqual(key.e, self.e)
  187. def testImportKey5(self):
  188. """Verifies that the imported key is still a valid RSA pair"""
  189. key = RSA.importKey(self.rsaKeyPEM)
  190. idem = key._encrypt(key._decrypt(89))
  191. self.assertEqual(idem, 89)
  192. def testImportKey6(self):
  193. """Verifies that the imported key is still a valid RSA pair"""
  194. key = RSA.importKey(self.rsaKeyDER)
  195. idem = key._encrypt(key._decrypt(65))
  196. self.assertEqual(idem, 65)
  197. def testImportKey7(self):
  198. """Verify import of OpenSSH public key"""
  199. key = RSA.importKey(self.rsaPublicKeyOpenSSH)
  200. self.assertEqual(key.n, self.n)
  201. self.assertEqual(key.e, self.e)
  202. def testImportKey8(self):
  203. """Verify import of encrypted PrivateKeyInfo DER SEQUENCE"""
  204. for t in self.rsaKeyEncryptedPEM:
  205. key = RSA.importKey(t[1], t[0])
  206. self.failUnless(key.has_private())
  207. self.assertEqual(key.n, self.n)
  208. self.assertEqual(key.e, self.e)
  209. self.assertEqual(key.d, self.d)
  210. self.assertEqual(key.p, self.p)
  211. self.assertEqual(key.q, self.q)
  212. def testImportKey9(self):
  213. """Verify import of unencrypted PrivateKeyInfo DER SEQUENCE"""
  214. key = RSA.importKey(self.rsaKeyDER8)
  215. self.failUnless(key.has_private())
  216. self.assertEqual(key.n, self.n)
  217. self.assertEqual(key.e, self.e)
  218. self.assertEqual(key.d, self.d)
  219. self.assertEqual(key.p, self.p)
  220. self.assertEqual(key.q, self.q)
  221. def testImportKey10(self):
  222. """Verify import of unencrypted PrivateKeyInfo DER SEQUENCE, encoded with PEM"""
  223. key = RSA.importKey(self.rsaKeyPEM8)
  224. self.failUnless(key.has_private())
  225. self.assertEqual(key.n, self.n)
  226. self.assertEqual(key.e, self.e)
  227. self.assertEqual(key.d, self.d)
  228. self.assertEqual(key.p, self.p)
  229. self.assertEqual(key.q, self.q)
  230. def testImportKey11(self):
  231. """Verify import of RSAPublicKey DER SEQUENCE"""
  232. der = asn1.DerSequence([17, 3]).encode()
  233. key = RSA.importKey(der)
  234. self.assertEqual(key.n, 17)
  235. self.assertEqual(key.e, 3)
  236. def testImportKey12(self):
  237. """Verify import of RSAPublicKey DER SEQUENCE, encoded with PEM"""
  238. der = asn1.DerSequence([17, 3]).encode()
  239. pem = der2pem(der)
  240. key = RSA.importKey(pem)
  241. self.assertEqual(key.n, 17)
  242. self.assertEqual(key.e, 3)
  243. def test_import_key_windows_cr_lf(self):
  244. pem_cr_lf = "\r\n".join(self.rsaKeyPEM.splitlines())
  245. key = RSA.importKey(pem_cr_lf)
  246. self.assertEqual(key.n, self.n)
  247. self.assertEqual(key.e, self.e)
  248. self.assertEqual(key.d, self.d)
  249. self.assertEqual(key.p, self.p)
  250. self.assertEqual(key.q, self.q)
  251. def test_import_empty(self):
  252. self.assertRaises(ValueError, RSA.import_key, b"")
  253. ###
  254. def testExportKey1(self):
  255. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
  256. derKey = key.export_key("DER")
  257. self.assertEqual(derKey, self.rsaKeyDER)
  258. def testExportKey2(self):
  259. key = RSA.construct([self.n, self.e])
  260. derKey = key.export_key("DER")
  261. self.assertEqual(derKey, self.rsaPublicKeyDER)
  262. def testExportKey3(self):
  263. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
  264. pemKey = key.export_key("PEM")
  265. self.assertEqual(pemKey, b(self.rsaKeyPEM))
  266. def testExportKey4(self):
  267. key = RSA.construct([self.n, self.e])
  268. pemKey = key.export_key("PEM")
  269. self.assertEqual(pemKey, b(self.rsaPublicKeyPEM))
  270. def testExportKey5(self):
  271. key = RSA.construct([self.n, self.e])
  272. openssh_1 = key.export_key("OpenSSH").split()
  273. openssh_2 = self.rsaPublicKeyOpenSSH.split()
  274. self.assertEqual(openssh_1[0], openssh_2[0])
  275. self.assertEqual(openssh_1[1], openssh_2[1])
  276. def testExportKey7(self):
  277. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
  278. derKey = key.export_key("DER", pkcs=8)
  279. self.assertEqual(derKey, self.rsaKeyDER8)
  280. def testExportKey8(self):
  281. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
  282. pemKey = key.export_key("PEM", pkcs=8)
  283. self.assertEqual(pemKey, b(self.rsaKeyPEM8))
  284. def testExportKey9(self):
  285. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
  286. self.assertRaises(ValueError, key.export_key, "invalid-format")
  287. def testExportKey10(self):
  288. # Export and re-import the encrypted key. It must match.
  289. # PEM envelope, PKCS#1, old PEM encryption
  290. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
  291. outkey = key.export_key('PEM', 'test')
  292. self.failUnless(tostr(outkey).find('4,ENCRYPTED')!=-1)
  293. self.failUnless(tostr(outkey).find('BEGIN RSA PRIVATE KEY')!=-1)
  294. inkey = RSA.importKey(outkey, 'test')
  295. self.assertEqual(key.n, inkey.n)
  296. self.assertEqual(key.e, inkey.e)
  297. self.assertEqual(key.d, inkey.d)
  298. def testExportKey11(self):
  299. # Export and re-import the encrypted key. It must match.
  300. # PEM envelope, PKCS#1, old PEM encryption
  301. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
  302. outkey = key.export_key('PEM', 'test', pkcs=1)
  303. self.failUnless(tostr(outkey).find('4,ENCRYPTED')!=-1)
  304. self.failUnless(tostr(outkey).find('BEGIN RSA PRIVATE KEY')!=-1)
  305. inkey = RSA.importKey(outkey, 'test')
  306. self.assertEqual(key.n, inkey.n)
  307. self.assertEqual(key.e, inkey.e)
  308. self.assertEqual(key.d, inkey.d)
  309. def testExportKey12(self):
  310. # Export and re-import the encrypted key. It must match.
  311. # PEM envelope, PKCS#8, old PEM encryption
  312. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
  313. outkey = key.export_key('PEM', 'test', pkcs=8)
  314. self.failUnless(tostr(outkey).find('4,ENCRYPTED')!=-1)
  315. self.failUnless(tostr(outkey).find('BEGIN PRIVATE KEY')!=-1)
  316. inkey = RSA.importKey(outkey, 'test')
  317. self.assertEqual(key.n, inkey.n)
  318. self.assertEqual(key.e, inkey.e)
  319. self.assertEqual(key.d, inkey.d)
  320. def testExportKey13(self):
  321. # Export and re-import the encrypted key. It must match.
  322. # PEM envelope, PKCS#8, PKCS#8 encryption
  323. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
  324. outkey = key.export_key('PEM', 'test', pkcs=8,
  325. protection='PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC')
  326. self.failUnless(tostr(outkey).find('4,ENCRYPTED')==-1)
  327. self.failUnless(tostr(outkey).find('BEGIN ENCRYPTED PRIVATE KEY')!=-1)
  328. inkey = RSA.importKey(outkey, 'test')
  329. self.assertEqual(key.n, inkey.n)
  330. self.assertEqual(key.e, inkey.e)
  331. self.assertEqual(key.d, inkey.d)
  332. def testExportKey14(self):
  333. # Export and re-import the encrypted key. It must match.
  334. # DER envelope, PKCS#8, PKCS#8 encryption
  335. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
  336. outkey = key.export_key('DER', 'test', pkcs=8)
  337. inkey = RSA.importKey(outkey, 'test')
  338. self.assertEqual(key.n, inkey.n)
  339. self.assertEqual(key.e, inkey.e)
  340. self.assertEqual(key.d, inkey.d)
  341. def testExportKey15(self):
  342. # Verify that that error an condition is detected when trying to
  343. # use a password with DER encoding and PKCS#1.
  344. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
  345. self.assertRaises(ValueError, key.export_key, 'DER', 'test', 1)
  346. def test_import_key(self):
  347. """Verify that import_key is an alias to importKey"""
  348. key = RSA.import_key(self.rsaPublicKeyDER)
  349. self.failIf(key.has_private())
  350. self.assertEqual(key.n, self.n)
  351. self.assertEqual(key.e, self.e)
  352. def test_exportKey(self):
  353. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
  354. self.assertEqual(key.export_key(), key.exportKey())
  355. class ImportKeyFromX509Cert(unittest.TestCase):
  356. def test_x509v1(self):
  357. # Sample V1 certificate with a 1024 bit RSA key
  358. x509_v1_cert = """
  359. -----BEGIN CERTIFICATE-----
  360. MIICOjCCAaMCAQEwDQYJKoZIhvcNAQEEBQAwfjENMAsGA1UEChMEQWNtZTELMAkG
  361. A1UECxMCUkQxHDAaBgkqhkiG9w0BCQEWDXNwYW1AYWNtZS5vcmcxEzARBgNVBAcT
  362. Ck1ldHJvcG9saXMxETAPBgNVBAgTCE5ldyBZb3JrMQswCQYDVQQGEwJVUzENMAsG
  363. A1UEAxMEdGVzdDAeFw0xNDA3MTExOTU3MjRaFw0xNzA0MDYxOTU3MjRaME0xCzAJ
  364. BgNVBAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazENMAsGA1UEChMEQWNtZTELMAkG
  365. A1UECxMCUkQxDzANBgNVBAMTBmxhdHZpYTCBnzANBgkqhkiG9w0BAQEFAAOBjQAw
  366. gYkCgYEAyG+kytdRj3TFbRmHDYp3TXugVQ81chew0qeOxZWOz80IjtWpgdOaCvKW
  367. NCuc8wUR9BWrEQW+39SaRMLiQfQtyFSQZijc3nsEBu/Lo4uWZ0W/FHDRVSvkJA/V
  368. Ex5NL5ikI+wbUeCV5KajGNDalZ8F1pk32+CBs8h1xNx5DyxuEHUCAwEAATANBgkq
  369. hkiG9w0BAQQFAAOBgQCVQF9Y//Q4Psy+umEM38pIlbZ2hxC5xNz/MbVPwuCkNcGn
  370. KYNpQJP+JyVTsPpO8RLZsAQDzRueMI3S7fbbwTzAflN0z19wvblvu93xkaBytVok
  371. 9VBAH28olVhy9b1MMeg2WOt5sUEQaFNPnwwsyiY9+HsRpvpRnPSQF+kyYVsshQ==
  372. -----END CERTIFICATE-----
  373. """.strip()
  374. # RSA public key as dumped by openssl
  375. exponent = 65537
  376. modulus_str = """
  377. 00:c8:6f:a4:ca:d7:51:8f:74:c5:6d:19:87:0d:8a:
  378. 77:4d:7b:a0:55:0f:35:72:17:b0:d2:a7:8e:c5:95:
  379. 8e:cf:cd:08:8e:d5:a9:81:d3:9a:0a:f2:96:34:2b:
  380. 9c:f3:05:11:f4:15:ab:11:05:be:df:d4:9a:44:c2:
  381. e2:41:f4:2d:c8:54:90:66:28:dc:de:7b:04:06:ef:
  382. cb:a3:8b:96:67:45:bf:14:70:d1:55:2b:e4:24:0f:
  383. d5:13:1e:4d:2f:98:a4:23:ec:1b:51:e0:95:e4:a6:
  384. a3:18:d0:da:95:9f:05:d6:99:37:db:e0:81:b3:c8:
  385. 75:c4:dc:79:0f:2c:6e:10:75
  386. """
  387. modulus = int(re.sub("[^0-9a-f]","", modulus_str), 16)
  388. key = RSA.importKey(x509_v1_cert)
  389. self.assertEqual(key.e, exponent)
  390. self.assertEqual(key.n, modulus)
  391. self.failIf(key.has_private())
  392. def test_x509v3(self):
  393. # Sample V3 certificate with a 1024 bit RSA key
  394. x509_v3_cert = """
  395. -----BEGIN CERTIFICATE-----
  396. MIIEcjCCAlqgAwIBAgIBATANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQGEwJVUzEL
  397. MAkGA1UECAwCTUQxEjAQBgNVBAcMCUJhbHRpbW9yZTEQMA4GA1UEAwwHVGVzdCBD
  398. QTEfMB0GCSqGSIb3DQEJARYQdGVzdEBleGFtcGxlLmNvbTAeFw0xNDA3MTIwOTM1
  399. MTJaFw0xNzA0MDcwOTM1MTJaMEQxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJNRDES
  400. MBAGA1UEBwwJQmFsdGltb3JlMRQwEgYDVQQDDAtUZXN0IFNlcnZlcjCBnzANBgkq
  401. hkiG9w0BAQEFAAOBjQAwgYkCgYEA/S7GJV2OcFdyNMQ4K75KrYFtMEn3VnEFdPHa
  402. jyS37XlMxSh0oS4GeTGVUCJInl5Cpsv8WQdh03FfeOdvzp5IZ46OcjeOPiWnmjgl
  403. 2G5j7e2bDH7RSchGV+OD6Fb1Agvuu2/9iy8fdf3rPQ/7eAddzKUrzwacVbnW+tg2
  404. QtSXKRcCAwEAAaOB1TCB0jAdBgNVHQ4EFgQU/WwCX7FfWMIPDFfJ+I8a2COG+l8w
  405. HwYDVR0jBBgwFoAUa0hkif3RMaraiWtsOOZZlLu9wJwwCQYDVR0TBAIwADALBgNV
  406. HQ8EBAMCBeAwSgYDVR0RBEMwQYILZXhhbXBsZS5jb22CD3d3dy5leGFtcGxlLmNv
  407. bYIQbWFpbC5leGFtcGxlLmNvbYIPZnRwLmV4YW1wbGUuY29tMCwGCWCGSAGG+EIB
  408. DQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTANBgkqhkiG9w0BAQsF
  409. AAOCAgEAvO6xfdsGbnoK4My3eJthodTAjMjPwFVY133LH04QLcCv54TxKhtUg1fi
  410. PgdjVe1HpTytPBfXy2bSZbXAN0abZCtw1rYrnn7o1g2pN8iypVq3zVn0iMTzQzxs
  411. zEPO3bpR/UhNSf90PmCsS5rqZpAAnXSaAy1ClwHWk/0eG2pYkhE1m1ABVMN2lsAW
  412. e9WxGk6IFqaI9O37NYQwmEypMs4DC+ECJEvbPFiqi3n0gbXCZJJ6omDA5xJldaYK
  413. Oa7KR3s/qjBsu9UAiWpLBuFoSTHIF2aeRKRFmUdmzwo43eVPep65pY6eQ4AdL2RF
  414. rqEuINbGlzI5oQyYhu71IwB+iPZXaZZPlwjLgOsuad/p2hOgDb5WxUi8FnDPursQ
  415. ujfpIpmrOP/zpvvQWnwePI3lI+5n41kTBSbefXEdv6rXpHk3QRzB90uPxnXPdxSC
  416. 16ASA8bQT5an/1AgoE3k9CrcD2K0EmgaX0YI0HUhkyzbkg34EhpWJ6vvRUbRiNRo
  417. 9cIbt/ya9Y9u0Ja8GLXv6dwX0l0IdJMkL8KifXUFAVCujp1FBrr/gdmwQn8itANy
  418. +qbnWSxmOvtaY0zcaFAcONuHva0h51/WqXOMO1eb8PhR4HIIYU8p1oBwQp7dSni8
  419. THDi1F+GG5PsymMDj5cWK42f+QzjVw5PrVmFqqrrEoMlx8DWh5Y=
  420. -----END CERTIFICATE-----
  421. """.strip()
  422. # RSA public key as dumped by openssl
  423. exponent = 65537
  424. modulus_str = """
  425. 00:fd:2e:c6:25:5d:8e:70:57:72:34:c4:38:2b:be:
  426. 4a:ad:81:6d:30:49:f7:56:71:05:74:f1:da:8f:24:
  427. b7:ed:79:4c:c5:28:74:a1:2e:06:79:31:95:50:22:
  428. 48:9e:5e:42:a6:cb:fc:59:07:61:d3:71:5f:78:e7:
  429. 6f:ce:9e:48:67:8e:8e:72:37:8e:3e:25:a7:9a:38:
  430. 25:d8:6e:63:ed:ed:9b:0c:7e:d1:49:c8:46:57:e3:
  431. 83:e8:56:f5:02:0b:ee:bb:6f:fd:8b:2f:1f:75:fd:
  432. eb:3d:0f:fb:78:07:5d:cc:a5:2b:cf:06:9c:55:b9:
  433. d6:fa:d8:36:42:d4:97:29:17
  434. """
  435. modulus = int(re.sub("[^0-9a-f]","", modulus_str), 16)
  436. key = RSA.importKey(x509_v3_cert)
  437. self.assertEqual(key.e, exponent)
  438. self.assertEqual(key.n, modulus)
  439. self.failIf(key.has_private())
  440. class TestImport_2048(unittest.TestCase):
  441. def test_import_openssh_public(self):
  442. key_file_ref = load_file("rsa2048_private.pem")
  443. key_file = load_file("rsa2048_public_openssh.txt")
  444. key_ref = RSA.import_key(key_file_ref).publickey()
  445. key = RSA.import_key(key_file)
  446. self.assertEqual(key_ref, key)
  447. def test_import_openssh_private_clear(self):
  448. key_file = load_file("rsa2048_private_openssh.pem")
  449. key_file_old = load_file("rsa2048_private_openssh_old.pem")
  450. key = RSA.import_key(key_file)
  451. key_old = RSA.import_key(key_file_old)
  452. self.assertEqual(key, key_old)
  453. def test_import_openssh_private_password(self):
  454. key_file = load_file("rsa2048_private_openssh_pwd.pem")
  455. key_file_old = load_file("rsa2048_private_openssh_pwd_old.pem")
  456. key = RSA.import_key(key_file, b"password")
  457. key_old = RSA.import_key(key_file_old)
  458. self.assertEqual(key, key_old)
  459. if __name__ == '__main__':
  460. unittest.main()
  461. def get_tests(config={}):
  462. tests = []
  463. tests += list_test_cases(ImportKeyTests)
  464. tests += list_test_cases(ImportKeyFromX509Cert)
  465. tests += list_test_cases(TestImport_2048)
  466. return tests
  467. if __name__ == '__main__':
  468. suite = lambda: unittest.TestSuite(get_tests())
  469. unittest.main(defaultTest='suite')
  470. # vim:set ts=4 sw=4 sts=4 expandtab: