You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1143 lines
33 KiB

4 years ago
  1. # coding: utf-8
  2. """
  3. ASN.1 type classes for various algorithms using in various aspects of public
  4. key cryptography. Exports the following items:
  5. - AlgorithmIdentifier()
  6. - AnyAlgorithmIdentifier()
  7. - DigestAlgorithm()
  8. - DigestInfo()
  9. - DSASignature()
  10. - EncryptionAlgorithm()
  11. - HmacAlgorithm()
  12. - KdfAlgorithm()
  13. - Pkcs5MacAlgorithm()
  14. - SignedDigestAlgorithm()
  15. Other type classes are defined that help compose the types listed above.
  16. """
  17. from __future__ import unicode_literals, division, absolute_import, print_function
  18. from ._errors import unwrap
  19. from ._int import fill_width
  20. from .util import int_from_bytes, int_to_bytes
  21. from .core import (
  22. Any,
  23. Choice,
  24. Integer,
  25. Null,
  26. ObjectIdentifier,
  27. OctetString,
  28. Sequence,
  29. Void,
  30. )
  31. # Structures and OIDs in this file are pulled from
  32. # https://tools.ietf.org/html/rfc3279, https://tools.ietf.org/html/rfc4055,
  33. # https://tools.ietf.org/html/rfc5758, https://tools.ietf.org/html/rfc7292,
  34. # http://www.emc.com/collateral/white-papers/h11302-pkcs5v2-1-password-based-cryptography-standard-wp.pdf
  35. class AlgorithmIdentifier(Sequence):
  36. _fields = [
  37. ('algorithm', ObjectIdentifier),
  38. ('parameters', Any, {'optional': True}),
  39. ]
  40. class _ForceNullParameters(object):
  41. """
  42. Various structures based on AlgorithmIdentifier require that the parameters
  43. field be core.Null() for certain OIDs. This mixin ensures that happens.
  44. """
  45. # The following attribute, plus the parameters spec callback and custom
  46. # __setitem__ are all to handle a situation where parameters should not be
  47. # optional and must be Null for certain OIDs. More info at
  48. # https://tools.ietf.org/html/rfc4055#page-15 and
  49. # https://tools.ietf.org/html/rfc4055#section-2.1
  50. _null_algos = set([
  51. '1.2.840.113549.1.1.1', # rsassa_pkcs1v15 / rsaes_pkcs1v15 / rsa
  52. '1.2.840.113549.1.1.11', # sha256_rsa
  53. '1.2.840.113549.1.1.12', # sha384_rsa
  54. '1.2.840.113549.1.1.13', # sha512_rsa
  55. '1.2.840.113549.1.1.14', # sha224_rsa
  56. '1.3.14.3.2.26', # sha1
  57. '2.16.840.1.101.3.4.2.4', # sha224
  58. '2.16.840.1.101.3.4.2.1', # sha256
  59. '2.16.840.1.101.3.4.2.2', # sha384
  60. '2.16.840.1.101.3.4.2.3', # sha512
  61. ])
  62. def _parameters_spec(self):
  63. if self._oid_pair == ('algorithm', 'parameters'):
  64. algo = self['algorithm'].native
  65. if algo in self._oid_specs:
  66. return self._oid_specs[algo]
  67. if self['algorithm'].dotted in self._null_algos:
  68. return Null
  69. return None
  70. _spec_callbacks = {
  71. 'parameters': _parameters_spec
  72. }
  73. # We have to override this since the spec callback uses the value of
  74. # algorithm to determine the parameter spec, however default values are
  75. # assigned before setting a field, so a default value can't be based on
  76. # another field value (unless it is a default also). Thus we have to
  77. # manually check to see if the algorithm was set and parameters is unset,
  78. # and then fix the value as appropriate.
  79. def __setitem__(self, key, value):
  80. res = super(_ForceNullParameters, self).__setitem__(key, value)
  81. if key != 'algorithm':
  82. return res
  83. if self['algorithm'].dotted not in self._null_algos:
  84. return res
  85. if self['parameters'].__class__ != Void:
  86. return res
  87. self['parameters'] = Null()
  88. return res
  89. class HmacAlgorithmId(ObjectIdentifier):
  90. _map = {
  91. '1.3.14.3.2.10': 'des_mac',
  92. '1.2.840.113549.2.7': 'sha1',
  93. '1.2.840.113549.2.8': 'sha224',
  94. '1.2.840.113549.2.9': 'sha256',
  95. '1.2.840.113549.2.10': 'sha384',
  96. '1.2.840.113549.2.11': 'sha512',
  97. '1.2.840.113549.2.12': 'sha512_224',
  98. '1.2.840.113549.2.13': 'sha512_256',
  99. }
  100. class HmacAlgorithm(Sequence):
  101. _fields = [
  102. ('algorithm', HmacAlgorithmId),
  103. ('parameters', Any, {'optional': True}),
  104. ]
  105. class DigestAlgorithmId(ObjectIdentifier):
  106. _map = {
  107. '1.2.840.113549.2.2': 'md2',
  108. '1.2.840.113549.2.5': 'md5',
  109. '1.3.14.3.2.26': 'sha1',
  110. '2.16.840.1.101.3.4.2.4': 'sha224',
  111. '2.16.840.1.101.3.4.2.1': 'sha256',
  112. '2.16.840.1.101.3.4.2.2': 'sha384',
  113. '2.16.840.1.101.3.4.2.3': 'sha512',
  114. '2.16.840.1.101.3.4.2.5': 'sha512_224',
  115. '2.16.840.1.101.3.4.2.6': 'sha512_256',
  116. }
  117. class DigestAlgorithm(_ForceNullParameters, Sequence):
  118. _fields = [
  119. ('algorithm', DigestAlgorithmId),
  120. ('parameters', Any, {'optional': True}),
  121. ]
  122. # This structure is what is signed with a SignedDigestAlgorithm
  123. class DigestInfo(Sequence):
  124. _fields = [
  125. ('digest_algorithm', DigestAlgorithm),
  126. ('digest', OctetString),
  127. ]
  128. class MaskGenAlgorithmId(ObjectIdentifier):
  129. _map = {
  130. '1.2.840.113549.1.1.8': 'mgf1',
  131. }
  132. class MaskGenAlgorithm(Sequence):
  133. _fields = [
  134. ('algorithm', MaskGenAlgorithmId),
  135. ('parameters', Any, {'optional': True}),
  136. ]
  137. _oid_pair = ('algorithm', 'parameters')
  138. _oid_specs = {
  139. 'mgf1': DigestAlgorithm
  140. }
  141. class TrailerField(Integer):
  142. _map = {
  143. 1: 'trailer_field_bc',
  144. }
  145. class RSASSAPSSParams(Sequence):
  146. _fields = [
  147. (
  148. 'hash_algorithm',
  149. DigestAlgorithm,
  150. {
  151. 'explicit': 0,
  152. 'default': {'algorithm': 'sha1'},
  153. }
  154. ),
  155. (
  156. 'mask_gen_algorithm',
  157. MaskGenAlgorithm,
  158. {
  159. 'explicit': 1,
  160. 'default': {
  161. 'algorithm': 'mgf1',
  162. 'parameters': {'algorithm': 'sha1'},
  163. },
  164. }
  165. ),
  166. (
  167. 'salt_length',
  168. Integer,
  169. {
  170. 'explicit': 2,
  171. 'default': 20,
  172. }
  173. ),
  174. (
  175. 'trailer_field',
  176. TrailerField,
  177. {
  178. 'explicit': 3,
  179. 'default': 'trailer_field_bc',
  180. }
  181. ),
  182. ]
  183. class SignedDigestAlgorithmId(ObjectIdentifier):
  184. _map = {
  185. '1.3.14.3.2.3': 'md5_rsa',
  186. '1.3.14.3.2.29': 'sha1_rsa',
  187. '1.3.14.7.2.3.1': 'md2_rsa',
  188. '1.2.840.113549.1.1.2': 'md2_rsa',
  189. '1.2.840.113549.1.1.4': 'md5_rsa',
  190. '1.2.840.113549.1.1.5': 'sha1_rsa',
  191. '1.2.840.113549.1.1.14': 'sha224_rsa',
  192. '1.2.840.113549.1.1.11': 'sha256_rsa',
  193. '1.2.840.113549.1.1.12': 'sha384_rsa',
  194. '1.2.840.113549.1.1.13': 'sha512_rsa',
  195. '1.2.840.113549.1.1.10': 'rsassa_pss',
  196. '1.2.840.10040.4.3': 'sha1_dsa',
  197. '1.3.14.3.2.13': 'sha1_dsa',
  198. '1.3.14.3.2.27': 'sha1_dsa',
  199. '2.16.840.1.101.3.4.3.1': 'sha224_dsa',
  200. '2.16.840.1.101.3.4.3.2': 'sha256_dsa',
  201. '1.2.840.10045.4.1': 'sha1_ecdsa',
  202. '1.2.840.10045.4.3.1': 'sha224_ecdsa',
  203. '1.2.840.10045.4.3.2': 'sha256_ecdsa',
  204. '1.2.840.10045.4.3.3': 'sha384_ecdsa',
  205. '1.2.840.10045.4.3.4': 'sha512_ecdsa',
  206. # For when the digest is specified elsewhere in a Sequence
  207. '1.2.840.113549.1.1.1': 'rsassa_pkcs1v15',
  208. '1.2.840.10040.4.1': 'dsa',
  209. '1.2.840.10045.4': 'ecdsa',
  210. }
  211. _reverse_map = {
  212. 'dsa': '1.2.840.10040.4.1',
  213. 'ecdsa': '1.2.840.10045.4',
  214. 'md2_rsa': '1.2.840.113549.1.1.2',
  215. 'md5_rsa': '1.2.840.113549.1.1.4',
  216. 'rsassa_pkcs1v15': '1.2.840.113549.1.1.1',
  217. 'rsassa_pss': '1.2.840.113549.1.1.10',
  218. 'sha1_dsa': '1.2.840.10040.4.3',
  219. 'sha1_ecdsa': '1.2.840.10045.4.1',
  220. 'sha1_rsa': '1.2.840.113549.1.1.5',
  221. 'sha224_dsa': '2.16.840.1.101.3.4.3.1',
  222. 'sha224_ecdsa': '1.2.840.10045.4.3.1',
  223. 'sha224_rsa': '1.2.840.113549.1.1.14',
  224. 'sha256_dsa': '2.16.840.1.101.3.4.3.2',
  225. 'sha256_ecdsa': '1.2.840.10045.4.3.2',
  226. 'sha256_rsa': '1.2.840.113549.1.1.11',
  227. 'sha384_ecdsa': '1.2.840.10045.4.3.3',
  228. 'sha384_rsa': '1.2.840.113549.1.1.12',
  229. 'sha512_ecdsa': '1.2.840.10045.4.3.4',
  230. 'sha512_rsa': '1.2.840.113549.1.1.13',
  231. }
  232. class SignedDigestAlgorithm(_ForceNullParameters, Sequence):
  233. _fields = [
  234. ('algorithm', SignedDigestAlgorithmId),
  235. ('parameters', Any, {'optional': True}),
  236. ]
  237. _oid_pair = ('algorithm', 'parameters')
  238. _oid_specs = {
  239. 'rsassa_pss': RSASSAPSSParams,
  240. }
  241. @property
  242. def signature_algo(self):
  243. """
  244. :return:
  245. A unicode string of "rsassa_pkcs1v15", "rsassa_pss", "dsa" or
  246. "ecdsa"
  247. """
  248. algorithm = self['algorithm'].native
  249. algo_map = {
  250. 'md2_rsa': 'rsassa_pkcs1v15',
  251. 'md5_rsa': 'rsassa_pkcs1v15',
  252. 'sha1_rsa': 'rsassa_pkcs1v15',
  253. 'sha224_rsa': 'rsassa_pkcs1v15',
  254. 'sha256_rsa': 'rsassa_pkcs1v15',
  255. 'sha384_rsa': 'rsassa_pkcs1v15',
  256. 'sha512_rsa': 'rsassa_pkcs1v15',
  257. 'rsassa_pkcs1v15': 'rsassa_pkcs1v15',
  258. 'rsassa_pss': 'rsassa_pss',
  259. 'sha1_dsa': 'dsa',
  260. 'sha224_dsa': 'dsa',
  261. 'sha256_dsa': 'dsa',
  262. 'dsa': 'dsa',
  263. 'sha1_ecdsa': 'ecdsa',
  264. 'sha224_ecdsa': 'ecdsa',
  265. 'sha256_ecdsa': 'ecdsa',
  266. 'sha384_ecdsa': 'ecdsa',
  267. 'sha512_ecdsa': 'ecdsa',
  268. 'ecdsa': 'ecdsa',
  269. }
  270. if algorithm in algo_map:
  271. return algo_map[algorithm]
  272. raise ValueError(unwrap(
  273. '''
  274. Signature algorithm not known for %s
  275. ''',
  276. algorithm
  277. ))
  278. @property
  279. def hash_algo(self):
  280. """
  281. :return:
  282. A unicode string of "md2", "md5", "sha1", "sha224", "sha256",
  283. "sha384", "sha512", "sha512_224", "sha512_256"
  284. """
  285. algorithm = self['algorithm'].native
  286. algo_map = {
  287. 'md2_rsa': 'md2',
  288. 'md5_rsa': 'md5',
  289. 'sha1_rsa': 'sha1',
  290. 'sha224_rsa': 'sha224',
  291. 'sha256_rsa': 'sha256',
  292. 'sha384_rsa': 'sha384',
  293. 'sha512_rsa': 'sha512',
  294. 'sha1_dsa': 'sha1',
  295. 'sha224_dsa': 'sha224',
  296. 'sha256_dsa': 'sha256',
  297. 'sha1_ecdsa': 'sha1',
  298. 'sha224_ecdsa': 'sha224',
  299. 'sha256_ecdsa': 'sha256',
  300. 'sha384_ecdsa': 'sha384',
  301. 'sha512_ecdsa': 'sha512',
  302. }
  303. if algorithm in algo_map:
  304. return algo_map[algorithm]
  305. if algorithm == 'rsassa_pss':
  306. return self['parameters']['hash_algorithm']['algorithm'].native
  307. raise ValueError(unwrap(
  308. '''
  309. Hash algorithm not known for %s
  310. ''',
  311. algorithm
  312. ))
  313. class Pbkdf2Salt(Choice):
  314. _alternatives = [
  315. ('specified', OctetString),
  316. ('other_source', AlgorithmIdentifier),
  317. ]
  318. class Pbkdf2Params(Sequence):
  319. _fields = [
  320. ('salt', Pbkdf2Salt),
  321. ('iteration_count', Integer),
  322. ('key_length', Integer, {'optional': True}),
  323. ('prf', HmacAlgorithm, {'default': {'algorithm': 'sha1'}}),
  324. ]
  325. class KdfAlgorithmId(ObjectIdentifier):
  326. _map = {
  327. '1.2.840.113549.1.5.12': 'pbkdf2'
  328. }
  329. class KdfAlgorithm(Sequence):
  330. _fields = [
  331. ('algorithm', KdfAlgorithmId),
  332. ('parameters', Any, {'optional': True}),
  333. ]
  334. _oid_pair = ('algorithm', 'parameters')
  335. _oid_specs = {
  336. 'pbkdf2': Pbkdf2Params
  337. }
  338. class DHParameters(Sequence):
  339. """
  340. Original Name: DHParameter
  341. Source: ftp://ftp.rsasecurity.com/pub/pkcs/ascii/pkcs-3.asc section 9
  342. """
  343. _fields = [
  344. ('p', Integer),
  345. ('g', Integer),
  346. ('private_value_length', Integer, {'optional': True}),
  347. ]
  348. class KeyExchangeAlgorithmId(ObjectIdentifier):
  349. _map = {
  350. '1.2.840.113549.1.3.1': 'dh',
  351. }
  352. class KeyExchangeAlgorithm(Sequence):
  353. _fields = [
  354. ('algorithm', KeyExchangeAlgorithmId),
  355. ('parameters', Any, {'optional': True}),
  356. ]
  357. _oid_pair = ('algorithm', 'parameters')
  358. _oid_specs = {
  359. 'dh': DHParameters,
  360. }
  361. class Rc2Params(Sequence):
  362. _fields = [
  363. ('rc2_parameter_version', Integer, {'optional': True}),
  364. ('iv', OctetString),
  365. ]
  366. class Rc5ParamVersion(Integer):
  367. _map = {
  368. 16: 'v1-0'
  369. }
  370. class Rc5Params(Sequence):
  371. _fields = [
  372. ('version', Rc5ParamVersion),
  373. ('rounds', Integer),
  374. ('block_size_in_bits', Integer),
  375. ('iv', OctetString, {'optional': True}),
  376. ]
  377. class Pbes1Params(Sequence):
  378. _fields = [
  379. ('salt', OctetString),
  380. ('iterations', Integer),
  381. ]
  382. class PSourceAlgorithmId(ObjectIdentifier):
  383. _map = {
  384. '1.2.840.113549.1.1.9': 'p_specified',
  385. }
  386. class PSourceAlgorithm(Sequence):
  387. _fields = [
  388. ('algorithm', PSourceAlgorithmId),
  389. ('parameters', Any, {'optional': True}),
  390. ]
  391. _oid_pair = ('algorithm', 'parameters')
  392. _oid_specs = {
  393. 'p_specified': OctetString
  394. }
  395. class RSAESOAEPParams(Sequence):
  396. _fields = [
  397. (
  398. 'hash_algorithm',
  399. DigestAlgorithm,
  400. {
  401. 'explicit': 0,
  402. 'default': {'algorithm': 'sha1'}
  403. }
  404. ),
  405. (
  406. 'mask_gen_algorithm',
  407. MaskGenAlgorithm,
  408. {
  409. 'explicit': 1,
  410. 'default': {
  411. 'algorithm': 'mgf1',
  412. 'parameters': {'algorithm': 'sha1'}
  413. }
  414. }
  415. ),
  416. (
  417. 'p_source_algorithm',
  418. PSourceAlgorithm,
  419. {
  420. 'explicit': 2,
  421. 'default': {
  422. 'algorithm': 'p_specified',
  423. 'parameters': b''
  424. }
  425. }
  426. ),
  427. ]
  428. class DSASignature(Sequence):
  429. """
  430. An ASN.1 class for translating between the OS crypto library's
  431. representation of an (EC)DSA signature and the ASN.1 structure that is part
  432. of various RFCs.
  433. Original Name: DSS-Sig-Value
  434. Source: https://tools.ietf.org/html/rfc3279#section-2.2.2
  435. """
  436. _fields = [
  437. ('r', Integer),
  438. ('s', Integer),
  439. ]
  440. @classmethod
  441. def from_p1363(cls, data):
  442. """
  443. Reads a signature from a byte string encoding accordint to IEEE P1363,
  444. which is used by Microsoft's BCryptSignHash() function.
  445. :param data:
  446. A byte string from BCryptSignHash()
  447. :return:
  448. A DSASignature object
  449. """
  450. r = int_from_bytes(data[0:len(data) // 2])
  451. s = int_from_bytes(data[len(data) // 2:])
  452. return cls({'r': r, 's': s})
  453. def to_p1363(self):
  454. """
  455. Dumps a signature to a byte string compatible with Microsoft's
  456. BCryptVerifySignature() function.
  457. :return:
  458. A byte string compatible with BCryptVerifySignature()
  459. """
  460. r_bytes = int_to_bytes(self['r'].native)
  461. s_bytes = int_to_bytes(self['s'].native)
  462. int_byte_length = max(len(r_bytes), len(s_bytes))
  463. r_bytes = fill_width(r_bytes, int_byte_length)
  464. s_bytes = fill_width(s_bytes, int_byte_length)
  465. return r_bytes + s_bytes
  466. class EncryptionAlgorithmId(ObjectIdentifier):
  467. _map = {
  468. '1.3.14.3.2.7': 'des',
  469. '1.2.840.113549.3.7': 'tripledes_3key',
  470. '1.2.840.113549.3.2': 'rc2',
  471. '1.2.840.113549.3.9': 'rc5',
  472. # From http://csrc.nist.gov/groups/ST/crypto_apps_infra/csor/algorithms.html#AES
  473. '2.16.840.1.101.3.4.1.1': 'aes128_ecb',
  474. '2.16.840.1.101.3.4.1.2': 'aes128_cbc',
  475. '2.16.840.1.101.3.4.1.3': 'aes128_ofb',
  476. '2.16.840.1.101.3.4.1.4': 'aes128_cfb',
  477. '2.16.840.1.101.3.4.1.5': 'aes128_wrap',
  478. '2.16.840.1.101.3.4.1.6': 'aes128_gcm',
  479. '2.16.840.1.101.3.4.1.7': 'aes128_ccm',
  480. '2.16.840.1.101.3.4.1.8': 'aes128_wrap_pad',
  481. '2.16.840.1.101.3.4.1.21': 'aes192_ecb',
  482. '2.16.840.1.101.3.4.1.22': 'aes192_cbc',
  483. '2.16.840.1.101.3.4.1.23': 'aes192_ofb',
  484. '2.16.840.1.101.3.4.1.24': 'aes192_cfb',
  485. '2.16.840.1.101.3.4.1.25': 'aes192_wrap',
  486. '2.16.840.1.101.3.4.1.26': 'aes192_gcm',
  487. '2.16.840.1.101.3.4.1.27': 'aes192_ccm',
  488. '2.16.840.1.101.3.4.1.28': 'aes192_wrap_pad',
  489. '2.16.840.1.101.3.4.1.41': 'aes256_ecb',
  490. '2.16.840.1.101.3.4.1.42': 'aes256_cbc',
  491. '2.16.840.1.101.3.4.1.43': 'aes256_ofb',
  492. '2.16.840.1.101.3.4.1.44': 'aes256_cfb',
  493. '2.16.840.1.101.3.4.1.45': 'aes256_wrap',
  494. '2.16.840.1.101.3.4.1.46': 'aes256_gcm',
  495. '2.16.840.1.101.3.4.1.47': 'aes256_ccm',
  496. '2.16.840.1.101.3.4.1.48': 'aes256_wrap_pad',
  497. # From PKCS#5
  498. '1.2.840.113549.1.5.13': 'pbes2',
  499. '1.2.840.113549.1.5.1': 'pbes1_md2_des',
  500. '1.2.840.113549.1.5.3': 'pbes1_md5_des',
  501. '1.2.840.113549.1.5.4': 'pbes1_md2_rc2',
  502. '1.2.840.113549.1.5.6': 'pbes1_md5_rc2',
  503. '1.2.840.113549.1.5.10': 'pbes1_sha1_des',
  504. '1.2.840.113549.1.5.11': 'pbes1_sha1_rc2',
  505. # From PKCS#12
  506. '1.2.840.113549.1.12.1.1': 'pkcs12_sha1_rc4_128',
  507. '1.2.840.113549.1.12.1.2': 'pkcs12_sha1_rc4_40',
  508. '1.2.840.113549.1.12.1.3': 'pkcs12_sha1_tripledes_3key',
  509. '1.2.840.113549.1.12.1.4': 'pkcs12_sha1_tripledes_2key',
  510. '1.2.840.113549.1.12.1.5': 'pkcs12_sha1_rc2_128',
  511. '1.2.840.113549.1.12.1.6': 'pkcs12_sha1_rc2_40',
  512. # PKCS#1 v2.2
  513. '1.2.840.113549.1.1.1': 'rsaes_pkcs1v15',
  514. '1.2.840.113549.1.1.7': 'rsaes_oaep',
  515. }
  516. class EncryptionAlgorithm(_ForceNullParameters, Sequence):
  517. _fields = [
  518. ('algorithm', EncryptionAlgorithmId),
  519. ('parameters', Any, {'optional': True}),
  520. ]
  521. _oid_pair = ('algorithm', 'parameters')
  522. _oid_specs = {
  523. 'des': OctetString,
  524. 'tripledes_3key': OctetString,
  525. 'rc2': Rc2Params,
  526. 'rc5': Rc5Params,
  527. 'aes128_cbc': OctetString,
  528. 'aes192_cbc': OctetString,
  529. 'aes256_cbc': OctetString,
  530. 'aes128_ofb': OctetString,
  531. 'aes192_ofb': OctetString,
  532. 'aes256_ofb': OctetString,
  533. # From PKCS#5
  534. 'pbes1_md2_des': Pbes1Params,
  535. 'pbes1_md5_des': Pbes1Params,
  536. 'pbes1_md2_rc2': Pbes1Params,
  537. 'pbes1_md5_rc2': Pbes1Params,
  538. 'pbes1_sha1_des': Pbes1Params,
  539. 'pbes1_sha1_rc2': Pbes1Params,
  540. # From PKCS#12
  541. 'pkcs12_sha1_rc4_128': Pbes1Params,
  542. 'pkcs12_sha1_rc4_40': Pbes1Params,
  543. 'pkcs12_sha1_tripledes_3key': Pbes1Params,
  544. 'pkcs12_sha1_tripledes_2key': Pbes1Params,
  545. 'pkcs12_sha1_rc2_128': Pbes1Params,
  546. 'pkcs12_sha1_rc2_40': Pbes1Params,
  547. # PKCS#1 v2.2
  548. 'rsaes_oaep': RSAESOAEPParams,
  549. }
  550. @property
  551. def kdf(self):
  552. """
  553. Returns the name of the key derivation function to use.
  554. :return:
  555. A unicode from of one of the following: "pbkdf1", "pbkdf2",
  556. "pkcs12_kdf"
  557. """
  558. encryption_algo = self['algorithm'].native
  559. if encryption_algo == 'pbes2':
  560. return self['parameters']['key_derivation_func']['algorithm'].native
  561. if encryption_algo.find('.') == -1:
  562. if encryption_algo.find('_') != -1:
  563. encryption_algo, _ = encryption_algo.split('_', 1)
  564. if encryption_algo == 'pbes1':
  565. return 'pbkdf1'
  566. if encryption_algo == 'pkcs12':
  567. return 'pkcs12_kdf'
  568. raise ValueError(unwrap(
  569. '''
  570. Encryption algorithm "%s" does not have a registered key
  571. derivation function
  572. ''',
  573. encryption_algo
  574. ))
  575. raise ValueError(unwrap(
  576. '''
  577. Unrecognized encryption algorithm "%s", can not determine key
  578. derivation function
  579. ''',
  580. encryption_algo
  581. ))
  582. @property
  583. def kdf_hmac(self):
  584. """
  585. Returns the HMAC algorithm to use with the KDF.
  586. :return:
  587. A unicode string of one of the following: "md2", "md5", "sha1",
  588. "sha224", "sha256", "sha384", "sha512"
  589. """
  590. encryption_algo = self['algorithm'].native
  591. if encryption_algo == 'pbes2':
  592. return self['parameters']['key_derivation_func']['parameters']['prf']['algorithm'].native
  593. if encryption_algo.find('.') == -1:
  594. if encryption_algo.find('_') != -1:
  595. _, hmac_algo, _ = encryption_algo.split('_', 2)
  596. return hmac_algo
  597. raise ValueError(unwrap(
  598. '''
  599. Encryption algorithm "%s" does not have a registered key
  600. derivation function
  601. ''',
  602. encryption_algo
  603. ))
  604. raise ValueError(unwrap(
  605. '''
  606. Unrecognized encryption algorithm "%s", can not determine key
  607. derivation hmac algorithm
  608. ''',
  609. encryption_algo
  610. ))
  611. @property
  612. def kdf_salt(self):
  613. """
  614. Returns the byte string to use as the salt for the KDF.
  615. :return:
  616. A byte string
  617. """
  618. encryption_algo = self['algorithm'].native
  619. if encryption_algo == 'pbes2':
  620. salt = self['parameters']['key_derivation_func']['parameters']['salt']
  621. if salt.name == 'other_source':
  622. raise ValueError(unwrap(
  623. '''
  624. Can not determine key derivation salt - the
  625. reserved-for-future-use other source salt choice was
  626. specified in the PBKDF2 params structure
  627. '''
  628. ))
  629. return salt.native
  630. if encryption_algo.find('.') == -1:
  631. if encryption_algo.find('_') != -1:
  632. return self['parameters']['salt'].native
  633. raise ValueError(unwrap(
  634. '''
  635. Encryption algorithm "%s" does not have a registered key
  636. derivation function
  637. ''',
  638. encryption_algo
  639. ))
  640. raise ValueError(unwrap(
  641. '''
  642. Unrecognized encryption algorithm "%s", can not determine key
  643. derivation salt
  644. ''',
  645. encryption_algo
  646. ))
  647. @property
  648. def kdf_iterations(self):
  649. """
  650. Returns the number of iterations that should be run via the KDF.
  651. :return:
  652. An integer
  653. """
  654. encryption_algo = self['algorithm'].native
  655. if encryption_algo == 'pbes2':
  656. return self['parameters']['key_derivation_func']['parameters']['iteration_count'].native
  657. if encryption_algo.find('.') == -1:
  658. if encryption_algo.find('_') != -1:
  659. return self['parameters']['iterations'].native
  660. raise ValueError(unwrap(
  661. '''
  662. Encryption algorithm "%s" does not have a registered key
  663. derivation function
  664. ''',
  665. encryption_algo
  666. ))
  667. raise ValueError(unwrap(
  668. '''
  669. Unrecognized encryption algorithm "%s", can not determine key
  670. derivation iterations
  671. ''',
  672. encryption_algo
  673. ))
  674. @property
  675. def key_length(self):
  676. """
  677. Returns the key length to pass to the cipher/kdf. The PKCS#5 spec does
  678. not specify a way to store the RC5 key length, however this tends not
  679. to be a problem since OpenSSL does not support RC5 in PKCS#8 and OS X
  680. does not provide an RC5 cipher for use in the Security Transforms
  681. library.
  682. :raises:
  683. ValueError - when the key length can not be determined
  684. :return:
  685. An integer representing the length in bytes
  686. """
  687. encryption_algo = self['algorithm'].native
  688. if encryption_algo[0:3] == 'aes':
  689. return {
  690. 'aes128_': 16,
  691. 'aes192_': 24,
  692. 'aes256_': 32,
  693. }[encryption_algo[0:7]]
  694. cipher_lengths = {
  695. 'des': 8,
  696. 'tripledes_3key': 24,
  697. }
  698. if encryption_algo in cipher_lengths:
  699. return cipher_lengths[encryption_algo]
  700. if encryption_algo == 'rc2':
  701. rc2_params = self['parameters'].parsed['encryption_scheme']['parameters'].parsed
  702. rc2_parameter_version = rc2_params['rc2_parameter_version'].native
  703. # See page 24 of
  704. # http://www.emc.com/collateral/white-papers/h11302-pkcs5v2-1-password-based-cryptography-standard-wp.pdf
  705. encoded_key_bits_map = {
  706. 160: 5, # 40-bit
  707. 120: 8, # 64-bit
  708. 58: 16, # 128-bit
  709. }
  710. if rc2_parameter_version in encoded_key_bits_map:
  711. return encoded_key_bits_map[rc2_parameter_version]
  712. if rc2_parameter_version >= 256:
  713. return rc2_parameter_version
  714. if rc2_parameter_version is None:
  715. return 4 # 32-bit default
  716. raise ValueError(unwrap(
  717. '''
  718. Invalid RC2 parameter version found in EncryptionAlgorithm
  719. parameters
  720. '''
  721. ))
  722. if encryption_algo == 'pbes2':
  723. key_length = self['parameters']['key_derivation_func']['parameters']['key_length'].native
  724. if key_length is not None:
  725. return key_length
  726. # If the KDF params don't specify the key size, we can infer it from
  727. # the encryption scheme for all schemes except for RC5. However, in
  728. # practical terms, neither OpenSSL or OS X support RC5 for PKCS#8
  729. # so it is unlikely to be an issue that is run into.
  730. return self['parameters']['encryption_scheme'].key_length
  731. if encryption_algo.find('.') == -1:
  732. return {
  733. 'pbes1_md2_des': 8,
  734. 'pbes1_md5_des': 8,
  735. 'pbes1_md2_rc2': 8,
  736. 'pbes1_md5_rc2': 8,
  737. 'pbes1_sha1_des': 8,
  738. 'pbes1_sha1_rc2': 8,
  739. 'pkcs12_sha1_rc4_128': 16,
  740. 'pkcs12_sha1_rc4_40': 5,
  741. 'pkcs12_sha1_tripledes_3key': 24,
  742. 'pkcs12_sha1_tripledes_2key': 16,
  743. 'pkcs12_sha1_rc2_128': 16,
  744. 'pkcs12_sha1_rc2_40': 5,
  745. }[encryption_algo]
  746. raise ValueError(unwrap(
  747. '''
  748. Unrecognized encryption algorithm "%s"
  749. ''',
  750. encryption_algo
  751. ))
  752. @property
  753. def encryption_mode(self):
  754. """
  755. Returns the name of the encryption mode to use.
  756. :return:
  757. A unicode string from one of the following: "cbc", "ecb", "ofb",
  758. "cfb", "wrap", "gcm", "ccm", "wrap_pad"
  759. """
  760. encryption_algo = self['algorithm'].native
  761. if encryption_algo[0:7] in set(['aes128_', 'aes192_', 'aes256_']):
  762. return encryption_algo[7:]
  763. if encryption_algo[0:6] == 'pbes1_':
  764. return 'cbc'
  765. if encryption_algo[0:7] == 'pkcs12_':
  766. return 'cbc'
  767. if encryption_algo in set(['des', 'tripledes_3key', 'rc2', 'rc5']):
  768. return 'cbc'
  769. if encryption_algo == 'pbes2':
  770. return self['parameters']['encryption_scheme'].encryption_mode
  771. raise ValueError(unwrap(
  772. '''
  773. Unrecognized encryption algorithm "%s"
  774. ''',
  775. encryption_algo
  776. ))
  777. @property
  778. def encryption_cipher(self):
  779. """
  780. Returns the name of the symmetric encryption cipher to use. The key
  781. length can be retrieved via the .key_length property to disabiguate
  782. between different variations of TripleDES, AES, and the RC* ciphers.
  783. :return:
  784. A unicode string from one of the following: "rc2", "rc5", "des",
  785. "tripledes", "aes"
  786. """
  787. encryption_algo = self['algorithm'].native
  788. if encryption_algo[0:7] in set(['aes128_', 'aes192_', 'aes256_']):
  789. return 'aes'
  790. if encryption_algo in set(['des', 'rc2', 'rc5']):
  791. return encryption_algo
  792. if encryption_algo == 'tripledes_3key':
  793. return 'tripledes'
  794. if encryption_algo == 'pbes2':
  795. return self['parameters']['encryption_scheme'].encryption_cipher
  796. if encryption_algo.find('.') == -1:
  797. return {
  798. 'pbes1_md2_des': 'des',
  799. 'pbes1_md5_des': 'des',
  800. 'pbes1_md2_rc2': 'rc2',
  801. 'pbes1_md5_rc2': 'rc2',
  802. 'pbes1_sha1_des': 'des',
  803. 'pbes1_sha1_rc2': 'rc2',
  804. 'pkcs12_sha1_rc4_128': 'rc4',
  805. 'pkcs12_sha1_rc4_40': 'rc4',
  806. 'pkcs12_sha1_tripledes_3key': 'tripledes',
  807. 'pkcs12_sha1_tripledes_2key': 'tripledes',
  808. 'pkcs12_sha1_rc2_128': 'rc2',
  809. 'pkcs12_sha1_rc2_40': 'rc2',
  810. }[encryption_algo]
  811. raise ValueError(unwrap(
  812. '''
  813. Unrecognized encryption algorithm "%s"
  814. ''',
  815. encryption_algo
  816. ))
  817. @property
  818. def encryption_block_size(self):
  819. """
  820. Returns the block size of the encryption cipher, in bytes.
  821. :return:
  822. An integer that is the block size in bytes
  823. """
  824. encryption_algo = self['algorithm'].native
  825. if encryption_algo[0:7] in set(['aes128_', 'aes192_', 'aes256_']):
  826. return 16
  827. cipher_map = {
  828. 'des': 8,
  829. 'tripledes_3key': 8,
  830. 'rc2': 8,
  831. }
  832. if encryption_algo in cipher_map:
  833. return cipher_map[encryption_algo]
  834. if encryption_algo == 'rc5':
  835. return self['parameters'].parsed['block_size_in_bits'].native / 8
  836. if encryption_algo == 'pbes2':
  837. return self['parameters']['encryption_scheme'].encryption_block_size
  838. if encryption_algo.find('.') == -1:
  839. return {
  840. 'pbes1_md2_des': 8,
  841. 'pbes1_md5_des': 8,
  842. 'pbes1_md2_rc2': 8,
  843. 'pbes1_md5_rc2': 8,
  844. 'pbes1_sha1_des': 8,
  845. 'pbes1_sha1_rc2': 8,
  846. 'pkcs12_sha1_rc4_128': 0,
  847. 'pkcs12_sha1_rc4_40': 0,
  848. 'pkcs12_sha1_tripledes_3key': 8,
  849. 'pkcs12_sha1_tripledes_2key': 8,
  850. 'pkcs12_sha1_rc2_128': 8,
  851. 'pkcs12_sha1_rc2_40': 8,
  852. }[encryption_algo]
  853. raise ValueError(unwrap(
  854. '''
  855. Unrecognized encryption algorithm "%s"
  856. ''',
  857. encryption_algo
  858. ))
  859. @property
  860. def encryption_iv(self):
  861. """
  862. Returns the byte string of the initialization vector for the encryption
  863. scheme. Only the PBES2 stores the IV in the params. For PBES1, the IV
  864. is derived from the KDF and this property will return None.
  865. :return:
  866. A byte string or None
  867. """
  868. encryption_algo = self['algorithm'].native
  869. if encryption_algo in set(['rc2', 'rc5']):
  870. return self['parameters'].parsed['iv'].native
  871. # For DES/Triple DES and AES the IV is the entirety of the parameters
  872. octet_string_iv_oids = set([
  873. 'des',
  874. 'tripledes_3key',
  875. 'aes128_cbc',
  876. 'aes192_cbc',
  877. 'aes256_cbc',
  878. 'aes128_ofb',
  879. 'aes192_ofb',
  880. 'aes256_ofb',
  881. ])
  882. if encryption_algo in octet_string_iv_oids:
  883. return self['parameters'].native
  884. if encryption_algo == 'pbes2':
  885. return self['parameters']['encryption_scheme'].encryption_iv
  886. # All of the PBES1 algos use their KDF to create the IV. For the pbkdf1,
  887. # the KDF is told to generate a key that is an extra 8 bytes long, and
  888. # that is used for the IV. For the PKCS#12 KDF, it is called with an id
  889. # of 2 to generate the IV. In either case, we can't return the IV
  890. # without knowing the user's password.
  891. if encryption_algo.find('.') == -1:
  892. return None
  893. raise ValueError(unwrap(
  894. '''
  895. Unrecognized encryption algorithm "%s"
  896. ''',
  897. encryption_algo
  898. ))
  899. class Pbes2Params(Sequence):
  900. _fields = [
  901. ('key_derivation_func', KdfAlgorithm),
  902. ('encryption_scheme', EncryptionAlgorithm),
  903. ]
  904. class Pbmac1Params(Sequence):
  905. _fields = [
  906. ('key_derivation_func', KdfAlgorithm),
  907. ('message_auth_scheme', HmacAlgorithm),
  908. ]
  909. class Pkcs5MacId(ObjectIdentifier):
  910. _map = {
  911. '1.2.840.113549.1.5.14': 'pbmac1',
  912. }
  913. class Pkcs5MacAlgorithm(Sequence):
  914. _fields = [
  915. ('algorithm', Pkcs5MacId),
  916. ('parameters', Any),
  917. ]
  918. _oid_pair = ('algorithm', 'parameters')
  919. _oid_specs = {
  920. 'pbmac1': Pbmac1Params,
  921. }
  922. EncryptionAlgorithm._oid_specs['pbes2'] = Pbes2Params
  923. class AnyAlgorithmId(ObjectIdentifier):
  924. _map = {}
  925. def _setup(self):
  926. _map = self.__class__._map
  927. for other_cls in (EncryptionAlgorithmId, SignedDigestAlgorithmId, DigestAlgorithmId):
  928. for oid, name in other_cls._map.items():
  929. _map[oid] = name
  930. class AnyAlgorithmIdentifier(_ForceNullParameters, Sequence):
  931. _fields = [
  932. ('algorithm', AnyAlgorithmId),
  933. ('parameters', Any, {'optional': True}),
  934. ]
  935. _oid_pair = ('algorithm', 'parameters')
  936. _oid_specs = {}
  937. def _setup(self):
  938. Sequence._setup(self)
  939. specs = self.__class__._oid_specs
  940. for other_cls in (EncryptionAlgorithm, SignedDigestAlgorithm):
  941. for oid, spec in other_cls._oid_specs.items():
  942. specs[oid] = spec