DSA.py 22 KB

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