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.

1115 lines
32 KiB

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

Powered by TurnKey Linux.