DSA.py 22 KB

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