algos.py 35 KB

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