選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

1182 行
35 KiB

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