algos.py 33 KB

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