DSA.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. # -*- coding: utf-8 -*-
  2. #
  3. # PublicKey/DSA.py : DSA signature primitive
  4. #
  5. # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
  6. #
  7. # ===================================================================
  8. # The contents of this file are dedicated to the public domain. To
  9. # the extent that dedication to the public domain is not available,
  10. # everyone is granted a worldwide, perpetual, royalty-free,
  11. # non-exclusive license to exercise all rights associated with the
  12. # contents of this file for any purpose whatsoever.
  13. # No rights are reserved.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  19. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  20. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  21. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. # SOFTWARE.
  23. # ===================================================================
  24. __all__ = ['generate', 'construct', 'DsaKey', 'import_key' ]
  25. import binascii
  26. import struct
  27. import itertools
  28. from Cryptodome.Util.py3compat import bchr, bord, tobytes, tostr, iter_range
  29. from Cryptodome import Random
  30. from Cryptodome.IO import PKCS8, PEM
  31. from Cryptodome.Hash import SHA256
  32. from Cryptodome.Util.asn1 import (
  33. DerObject, DerSequence,
  34. DerInteger, DerObjectId,
  35. DerBitString,
  36. )
  37. from Cryptodome.Math.Numbers import Integer
  38. from Cryptodome.Math.Primality import (test_probable_prime, COMPOSITE,
  39. PROBABLY_PRIME)
  40. from Cryptodome.PublicKey import (_expand_subject_public_key_info,
  41. _create_subject_public_key_info,
  42. _extract_subject_public_key_info)
  43. # ; The following ASN.1 types are relevant for DSA
  44. #
  45. # SubjectPublicKeyInfo ::= SEQUENCE {
  46. # algorithm AlgorithmIdentifier,
  47. # subjectPublicKey BIT STRING
  48. # }
  49. #
  50. # id-dsa ID ::= { iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 1 }
  51. #
  52. # ; See RFC3279
  53. # Dss-Parms ::= SEQUENCE {
  54. # p INTEGER,
  55. # q INTEGER,
  56. # g INTEGER
  57. # }
  58. #
  59. # DSAPublicKey ::= INTEGER
  60. #
  61. # DSSPrivatKey_OpenSSL ::= SEQUENCE
  62. # version INTEGER,
  63. # p INTEGER,
  64. # q INTEGER,
  65. # g INTEGER,
  66. # y INTEGER,
  67. # x INTEGER
  68. # }
  69. #
  70. class DsaKey(object):
  71. r"""Class defining an actual DSA key.
  72. Do not instantiate directly.
  73. Use :func:`generate`, :func:`construct` or :func:`import_key` instead.
  74. :ivar p: DSA modulus
  75. :vartype p: integer
  76. :ivar q: Order of the subgroup
  77. :vartype q: integer
  78. :ivar g: Generator
  79. :vartype g: integer
  80. :ivar y: Public key
  81. :vartype y: integer
  82. :ivar x: Private key
  83. :vartype x: integer
  84. :undocumented: exportKey, publickey
  85. """
  86. _keydata = ['y', 'g', 'p', 'q', 'x']
  87. def __init__(self, key_dict):
  88. input_set = set(key_dict.keys())
  89. public_set = set(('y' , 'g', 'p', 'q'))
  90. if not public_set.issubset(input_set):
  91. raise ValueError("Some DSA components are missing = %s" %
  92. str(public_set - input_set))
  93. extra_set = input_set - public_set
  94. if extra_set and extra_set != set(('x',)):
  95. raise ValueError("Unknown DSA components = %s" %
  96. str(extra_set - set(('x',))))
  97. self._key = dict(key_dict)
  98. def _sign(self, m, k):
  99. if not self.has_private():
  100. raise TypeError("DSA public key cannot be used for signing")
  101. if not (1 < k < self.q):
  102. raise ValueError("k is not between 2 and q-1")
  103. x, q, p, g = [self._key[comp] for comp in ['x', 'q', 'p', 'g']]
  104. blind_factor = Integer.random_range(min_inclusive=1,
  105. max_exclusive=q)
  106. inv_blind_k = (blind_factor * k).inverse(q)
  107. blind_x = x * blind_factor
  108. r = pow(g, k, p) % q # r = (g**k mod p) mod q
  109. s = (inv_blind_k * (blind_factor * m + blind_x * r)) % q
  110. return map(int, (r, s))
  111. def _verify(self, m, sig):
  112. r, s = sig
  113. y, q, p, g = [self._key[comp] for comp in ['y', 'q', 'p', 'g']]
  114. if not (0 < r < q) or not (0 < s < q):
  115. return False
  116. w = Integer(s).inverse(q)
  117. u1 = (w * m) % q
  118. u2 = (w * r) % q
  119. v = (pow(g, u1, p) * pow(y, u2, p) % p) % q
  120. return v == r
  121. def has_private(self):
  122. """Whether this is a DSA private key"""
  123. return 'x' in self._key
  124. def can_encrypt(self): # legacy
  125. return False
  126. def can_sign(self): # legacy
  127. return True
  128. def public_key(self):
  129. """A matching DSA public key.
  130. Returns:
  131. a new :class:`DsaKey` object
  132. """
  133. public_components = dict((k, self._key[k]) for k in ('y', 'g', 'p', 'q'))
  134. return DsaKey(public_components)
  135. def __eq__(self, other):
  136. if bool(self.has_private()) != bool(other.has_private()):
  137. return False
  138. result = True
  139. for comp in self._keydata:
  140. result = result and (getattr(self._key, comp, None) ==
  141. getattr(other._key, comp, None))
  142. return result
  143. def __ne__(self, other):
  144. return not self.__eq__(other)
  145. def __getstate__(self):
  146. # DSA key is not pickable
  147. from pickle import PicklingError
  148. raise PicklingError
  149. def domain(self):
  150. """The DSA domain parameters.
  151. Returns
  152. tuple : (p,q,g)
  153. """
  154. return [int(self._key[comp]) for comp in ('p', 'q', 'g')]
  155. def __repr__(self):
  156. attrs = []
  157. for k in self._keydata:
  158. if k == 'p':
  159. bits = Integer(self.p).size_in_bits()
  160. attrs.append("p(%d)" % (bits,))
  161. elif hasattr(self, k):
  162. attrs.append(k)
  163. if self.has_private():
  164. attrs.append("private")
  165. # PY3K: This is meant to be text, do not change to bytes (data)
  166. return "<%s @0x%x %s>" % (self.__class__.__name__, id(self), ",".join(attrs))
  167. def __getattr__(self, item):
  168. try:
  169. return int(self._key[item])
  170. except KeyError:
  171. raise AttributeError(item)
  172. def export_key(self, format='PEM', pkcs8=None, passphrase=None,
  173. protection=None, randfunc=None):
  174. """Export this DSA key.
  175. Args:
  176. format (string):
  177. The encoding for the output:
  178. - *'PEM'* (default). ASCII as per `RFC1421`_/ `RFC1423`_.
  179. - *'DER'*. Binary ASN.1 encoding.
  180. - *'OpenSSH'*. ASCII one-liner as per `RFC4253`_.
  181. Only suitable for public keys, not for private keys.
  182. passphrase (string):
  183. *Private keys only*. The pass phrase to protect the output.
  184. pkcs8 (boolean):
  185. *Private keys only*. If ``True`` (default), the key is encoded
  186. with `PKCS#8`_. If ``False``, it is encoded in the custom
  187. OpenSSL/OpenSSH container.
  188. protection (string):
  189. *Only in combination with a pass phrase*.
  190. The encryption scheme to use to protect the output.
  191. If :data:`pkcs8` takes value ``True``, this is the PKCS#8
  192. algorithm to use for deriving the secret and encrypting
  193. the private DSA key.
  194. For a complete list of algorithms, see :mod:`Cryptodome.IO.PKCS8`.
  195. The default is *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*.
  196. If :data:`pkcs8` is ``False``, the obsolete PEM encryption scheme is
  197. used. It is based on MD5 for key derivation, and Triple DES for
  198. encryption. Parameter :data:`protection` is then ignored.
  199. The combination ``format='DER'`` and ``pkcs8=False`` is not allowed
  200. if a passphrase is present.
  201. randfunc (callable):
  202. A function that returns random bytes.
  203. By default it is :func:`Cryptodome.Random.get_random_bytes`.
  204. Returns:
  205. byte string : the encoded key
  206. Raises:
  207. ValueError : when the format is unknown or when you try to encrypt a private
  208. key with *DER* format and OpenSSL/OpenSSH.
  209. .. warning::
  210. If you don't provide a pass phrase, the private key will be
  211. exported in the clear!
  212. .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
  213. .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
  214. .. _RFC4253: http://www.ietf.org/rfc/rfc4253.txt
  215. .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
  216. """
  217. if passphrase is not None:
  218. passphrase = tobytes(passphrase)
  219. if randfunc is None:
  220. randfunc = Random.get_random_bytes
  221. if format == 'OpenSSH':
  222. tup1 = [self._key[x].to_bytes() for x in ('p', 'q', 'g', 'y')]
  223. def func(x):
  224. if (bord(x[0]) & 0x80):
  225. return bchr(0) + x
  226. else:
  227. return x
  228. tup2 = [func(x) for x in tup1]
  229. keyparts = [b'ssh-dss'] + tup2
  230. keystring = b''.join(
  231. [struct.pack(">I", len(kp)) + kp for kp in keyparts]
  232. )
  233. return b'ssh-dss ' + binascii.b2a_base64(keystring)[:-1]
  234. # DER format is always used, even in case of PEM, which simply
  235. # encodes it into BASE64.
  236. params = DerSequence([self.p, self.q, self.g])
  237. if self.has_private():
  238. if pkcs8 is None:
  239. pkcs8 = True
  240. if pkcs8:
  241. if not protection:
  242. protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'
  243. private_key = DerInteger(self.x).encode()
  244. binary_key = PKCS8.wrap(
  245. private_key, oid, passphrase,
  246. protection, key_params=params,
  247. randfunc=randfunc
  248. )
  249. if passphrase:
  250. key_type = 'ENCRYPTED PRIVATE'
  251. else:
  252. key_type = 'PRIVATE'
  253. passphrase = None
  254. else:
  255. if format != 'PEM' and passphrase:
  256. raise ValueError("DSA private key cannot be encrypted")
  257. ints = [0, self.p, self.q, self.g, self.y, self.x]
  258. binary_key = DerSequence(ints).encode()
  259. key_type = "DSA PRIVATE"
  260. else:
  261. if pkcs8:
  262. raise ValueError("PKCS#8 is only meaningful for private keys")
  263. binary_key = _create_subject_public_key_info(oid,
  264. DerInteger(self.y), params)
  265. key_type = "PUBLIC"
  266. if format == 'DER':
  267. return binary_key
  268. if format == 'PEM':
  269. pem_str = PEM.encode(
  270. binary_key, key_type + " KEY",
  271. passphrase, randfunc
  272. )
  273. return tobytes(pem_str)
  274. raise ValueError("Unknown key format '%s'. Cannot export the DSA key." % format)
  275. # Backward-compatibility
  276. exportKey = export_key
  277. publickey = public_key
  278. # Methods defined in PyCryptodome that we don't support anymore
  279. def sign(self, M, K):
  280. raise NotImplementedError("Use module Cryptodome.Signature.DSS instead")
  281. def verify(self, M, signature):
  282. raise NotImplementedError("Use module Cryptodome.Signature.DSS instead")
  283. def encrypt(self, plaintext, K):
  284. raise NotImplementedError
  285. def decrypt(self, ciphertext):
  286. raise NotImplementedError
  287. def blind(self, M, B):
  288. raise NotImplementedError
  289. def unblind(self, M, B):
  290. raise NotImplementedError
  291. def size(self):
  292. raise NotImplementedError
  293. def _generate_domain(L, randfunc):
  294. """Generate a new set of DSA domain parameters"""
  295. N = { 1024:160, 2048:224, 3072:256 }.get(L)
  296. if N is None:
  297. raise ValueError("Invalid modulus length (%d)" % L)
  298. outlen = SHA256.digest_size * 8
  299. n = (L + outlen - 1) // outlen - 1 # ceil(L/outlen) -1
  300. b_ = L - 1 - (n * outlen)
  301. # Generate q (A.1.1.2)
  302. q = Integer(4)
  303. upper_bit = 1 << (N - 1)
  304. while test_probable_prime(q, randfunc) != PROBABLY_PRIME:
  305. seed = randfunc(64)
  306. U = Integer.from_bytes(SHA256.new(seed).digest()) & (upper_bit - 1)
  307. q = U | upper_bit | 1
  308. assert(q.size_in_bits() == N)
  309. # Generate p (A.1.1.2)
  310. offset = 1
  311. upper_bit = 1 << (L - 1)
  312. while True:
  313. V = [ SHA256.new(seed + Integer(offset + j).to_bytes()).digest()
  314. for j in iter_range(n + 1) ]
  315. V = [ Integer.from_bytes(v) for v in V ]
  316. W = sum([V[i] * (1 << (i * outlen)) for i in iter_range(n)],
  317. (V[n] & ((1 << b_) - 1)) * (1 << (n * outlen)))
  318. X = Integer(W + upper_bit) # 2^{L-1} < X < 2^{L}
  319. assert(X.size_in_bits() == L)
  320. c = X % (q * 2)
  321. p = X - (c - 1) # 2q divides (p-1)
  322. if p.size_in_bits() == L and \
  323. test_probable_prime(p, randfunc) == PROBABLY_PRIME:
  324. break
  325. offset += n + 1
  326. # Generate g (A.2.3, index=1)
  327. e = (p - 1) // q
  328. for count in itertools.count(1):
  329. U = seed + b"ggen" + bchr(1) + Integer(count).to_bytes()
  330. W = Integer.from_bytes(SHA256.new(U).digest())
  331. g = pow(W, e, p)
  332. if g != 1:
  333. break
  334. return (p, q, g, seed)
  335. def generate(bits, randfunc=None, domain=None):
  336. """Generate a new DSA key pair.
  337. The algorithm follows Appendix A.1/A.2 and B.1 of `FIPS 186-4`_,
  338. respectively for domain generation and key pair generation.
  339. Args:
  340. bits (integer):
  341. Key length, or size (in bits) of the DSA modulus *p*.
  342. It must be 1024, 2048 or 3072.
  343. randfunc (callable):
  344. Random number generation function; it accepts a single integer N
  345. and return a string of random data N bytes long.
  346. If not specified, :func:`Cryptodome.Random.get_random_bytes` is used.
  347. domain (tuple):
  348. The DSA domain parameters *p*, *q* and *g* as a list of 3
  349. integers. Size of *p* and *q* must comply to `FIPS 186-4`_.
  350. If not specified, the parameters are created anew.
  351. Returns:
  352. :class:`DsaKey` : a new DSA key object
  353. Raises:
  354. ValueError : when **bits** is too little, too big, or not a multiple of 64.
  355. .. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
  356. """
  357. if randfunc is None:
  358. randfunc = Random.get_random_bytes
  359. if domain:
  360. p, q, g = map(Integer, domain)
  361. ## Perform consistency check on domain parameters
  362. # P and Q must be prime
  363. fmt_error = test_probable_prime(p) == COMPOSITE
  364. fmt_error |= test_probable_prime(q) == COMPOSITE
  365. # Verify Lagrange's theorem for sub-group
  366. fmt_error |= ((p - 1) % q) != 0
  367. fmt_error |= g <= 1 or g >= p
  368. fmt_error |= pow(g, q, p) != 1
  369. if fmt_error:
  370. raise ValueError("Invalid DSA domain parameters")
  371. else:
  372. p, q, g, _ = _generate_domain(bits, randfunc)
  373. L = p.size_in_bits()
  374. N = q.size_in_bits()
  375. if L != bits:
  376. raise ValueError("Mismatch between size of modulus (%d)"
  377. " and 'bits' parameter (%d)" % (L, bits))
  378. if (L, N) not in [(1024, 160), (2048, 224),
  379. (2048, 256), (3072, 256)]:
  380. raise ValueError("Lengths of p and q (%d, %d) are not compatible"
  381. "to FIPS 186-3" % (L, N))
  382. if not 1 < g < p:
  383. raise ValueError("Incorrent DSA generator")
  384. # B.1.1
  385. c = Integer.random(exact_bits=N + 64, randfunc=randfunc)
  386. x = c % (q - 1) + 1 # 1 <= x <= q-1
  387. y = pow(g, x, p)
  388. key_dict = { 'y':y, 'g':g, 'p':p, 'q':q, 'x':x }
  389. return DsaKey(key_dict)
  390. def construct(tup, consistency_check=True):
  391. """Construct a DSA key from a tuple of valid DSA components.
  392. Args:
  393. tup (tuple):
  394. A tuple of long integers, with 4 or 5 items
  395. in the following order:
  396. 1. Public key (*y*).
  397. 2. Sub-group generator (*g*).
  398. 3. Modulus, finite field order (*p*).
  399. 4. Sub-group order (*q*).
  400. 5. Private key (*x*). Optional.
  401. consistency_check (boolean):
  402. If ``True``, the library will verify that the provided components
  403. fulfil the main DSA properties.
  404. Raises:
  405. ValueError: when the key being imported fails the most basic DSA validity checks.
  406. Returns:
  407. :class:`DsaKey` : a DSA key object
  408. """
  409. key_dict = dict(zip(('y', 'g', 'p', 'q', 'x'), map(Integer, tup)))
  410. key = DsaKey(key_dict)
  411. fmt_error = False
  412. if consistency_check:
  413. # P and Q must be prime
  414. fmt_error = test_probable_prime(key.p) == COMPOSITE
  415. fmt_error |= test_probable_prime(key.q) == COMPOSITE
  416. # Verify Lagrange's theorem for sub-group
  417. fmt_error |= ((key.p - 1) % key.q) != 0
  418. fmt_error |= key.g <= 1 or key.g >= key.p
  419. fmt_error |= pow(key.g, key.q, key.p) != 1
  420. # Public key
  421. fmt_error |= key.y <= 0 or key.y >= key.p
  422. if hasattr(key, 'x'):
  423. fmt_error |= key.x <= 0 or key.x >= key.q
  424. fmt_error |= pow(key.g, key.x, key.p) != key.y
  425. if fmt_error:
  426. raise ValueError("Invalid DSA key components")
  427. return key
  428. # Dss-Parms ::= SEQUENCE {
  429. # p OCTET STRING,
  430. # q OCTET STRING,
  431. # g OCTET STRING
  432. # }
  433. # DSAPublicKey ::= INTEGER -- public key, y
  434. def _import_openssl_private(encoded, passphrase, params):
  435. if params:
  436. raise ValueError("DSA private key already comes with parameters")
  437. der = DerSequence().decode(encoded, nr_elements=6, only_ints_expected=True)
  438. if der[0] != 0:
  439. raise ValueError("No version found")
  440. tup = [der[comp] for comp in (4, 3, 1, 2, 5)]
  441. return construct(tup)
  442. def _import_subjectPublicKeyInfo(encoded, passphrase, params):
  443. algoid, encoded_key, emb_params = _expand_subject_public_key_info(encoded)
  444. if algoid != oid:
  445. raise ValueError("No DSA subjectPublicKeyInfo")
  446. if params and emb_params:
  447. raise ValueError("Too many DSA parameters")
  448. y = DerInteger().decode(encoded_key).value
  449. p, q, g = list(DerSequence().decode(params or emb_params))
  450. tup = (y, g, p, q)
  451. return construct(tup)
  452. def _import_x509_cert(encoded, passphrase, params):
  453. sp_info = _extract_subject_public_key_info(encoded)
  454. return _import_subjectPublicKeyInfo(sp_info, None, params)
  455. def _import_pkcs8(encoded, passphrase, params):
  456. if params:
  457. raise ValueError("PKCS#8 already includes parameters")
  458. k = PKCS8.unwrap(encoded, passphrase)
  459. if k[0] != oid:
  460. raise ValueError("No PKCS#8 encoded DSA key")
  461. x = DerInteger().decode(k[1]).value
  462. p, q, g = list(DerSequence().decode(k[2]))
  463. tup = (pow(g, x, p), g, p, q, x)
  464. return construct(tup)
  465. def _import_key_der(key_data, passphrase, params):
  466. """Import a DSA key (public or private half), encoded in DER form."""
  467. decodings = (_import_openssl_private,
  468. _import_subjectPublicKeyInfo,
  469. _import_x509_cert,
  470. _import_pkcs8)
  471. for decoding in decodings:
  472. try:
  473. return decoding(key_data, passphrase, params)
  474. except ValueError:
  475. pass
  476. raise ValueError("DSA key format is not supported")
  477. def import_key(extern_key, passphrase=None):
  478. """Import a DSA key.
  479. Args:
  480. extern_key (string or byte string):
  481. The DSA key to import.
  482. The following formats are supported for a DSA **public** key:
  483. - X.509 certificate (binary DER or PEM)
  484. - X.509 ``subjectPublicKeyInfo`` (binary DER or PEM)
  485. - OpenSSH (ASCII one-liner, see `RFC4253`_)
  486. The following formats are supported for a DSA **private** key:
  487. - `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo``
  488. DER SEQUENCE (binary or PEM)
  489. - OpenSSL/OpenSSH custom format (binary or PEM)
  490. For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
  491. passphrase (string):
  492. In case of an encrypted private key, this is the pass phrase
  493. from which the decryption key is derived.
  494. Encryption may be applied either at the `PKCS#8`_ or at the PEM level.
  495. Returns:
  496. :class:`DsaKey` : a DSA key object
  497. Raises:
  498. ValueError : when the given key cannot be parsed (possibly because
  499. the pass phrase is wrong).
  500. .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
  501. .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
  502. .. _RFC4253: http://www.ietf.org/rfc/rfc4253.txt
  503. .. _PKCS#8: http://www.ietf.org/rfc/rfc5208.txt
  504. """
  505. extern_key = tobytes(extern_key)
  506. if passphrase is not None:
  507. passphrase = tobytes(passphrase)
  508. if extern_key.startswith(b'-----'):
  509. # This is probably a PEM encoded key
  510. (der, marker, enc_flag) = PEM.decode(tostr(extern_key), passphrase)
  511. if enc_flag:
  512. passphrase = None
  513. return _import_key_der(der, passphrase, None)
  514. if extern_key.startswith(b'ssh-dss '):
  515. # This is probably a public OpenSSH key
  516. keystring = binascii.a2b_base64(extern_key.split(b' ')[1])
  517. keyparts = []
  518. while len(keystring) > 4:
  519. length = struct.unpack(">I", keystring[:4])[0]
  520. keyparts.append(keystring[4:4 + length])
  521. keystring = keystring[4 + length:]
  522. if keyparts[0] == b"ssh-dss":
  523. tup = [Integer.from_bytes(keyparts[x]) for x in (4, 3, 1, 2)]
  524. return construct(tup)
  525. if len(extern_key) > 0 and bord(extern_key[0]) == 0x30:
  526. # This is probably a DER encoded key
  527. return _import_key_der(extern_key, passphrase, None)
  528. raise ValueError("DSA key format is not supported")
  529. # Backward compatibility
  530. importKey = import_key
  531. #: `Object ID`_ for a DSA key.
  532. #:
  533. #: id-dsa ID ::= { iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 1 }
  534. #:
  535. #: .. _`Object ID`: http://www.alvestrand.no/objectid/1.2.840.10040.4.1.html
  536. oid = "1.2.840.10040.4.1"