crypto.py 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368
  1. """
  2. This file contains some classical ciphers and routines
  3. implementing a linear-feedback shift register (LFSR)
  4. and the Diffie-Hellman key exchange.
  5. .. warning::
  6. This module is intended for educational purposes only. Do not use the
  7. functions in this module for real cryptographic applications. If you wish
  8. to encrypt real data, we recommend using something like the `cryptography
  9. <https://cryptography.io/en/latest/>`_ module.
  10. """
  11. from string import whitespace, ascii_uppercase as uppercase, printable
  12. from functools import reduce
  13. import string
  14. import warnings
  15. from itertools import cycle
  16. from sympy.external.gmpy import GROUND_TYPES
  17. from sympy.core import Symbol
  18. from sympy.core.numbers import Rational
  19. from sympy.core.random import _randrange, _randint
  20. from sympy.external.gmpy import gcd, invert
  21. from sympy.functions.combinatorial.numbers import (totient as _euler,
  22. reduced_totient as _carmichael)
  23. from sympy.matrices import Matrix
  24. from sympy.ntheory import isprime, primitive_root, factorint
  25. from sympy.ntheory.generate import nextprime
  26. from sympy.ntheory.modular import crt
  27. from sympy.polys.domains import FF
  28. from sympy.polys.polytools import Poly
  29. from sympy.utilities.misc import as_int, filldedent, translate
  30. from sympy.utilities.iterables import uniq, multiset
  31. from sympy.utilities.decorator import doctest_depends_on
  32. if GROUND_TYPES == 'flint':
  33. __doctest_skip__ = ['lfsr_sequence']
  34. class NonInvertibleCipherWarning(RuntimeWarning):
  35. """A warning raised if the cipher is not invertible."""
  36. def __init__(self, msg):
  37. self.fullMessage = msg
  38. def __str__(self):
  39. return '\n\t' + self.fullMessage
  40. def warn(self, stacklevel=3):
  41. warnings.warn(self, stacklevel=stacklevel)
  42. def AZ(s=None):
  43. """Return the letters of ``s`` in uppercase. In case more than
  44. one string is passed, each of them will be processed and a list
  45. of upper case strings will be returned.
  46. Examples
  47. ========
  48. >>> from sympy.crypto.crypto import AZ
  49. >>> AZ('Hello, world!')
  50. 'HELLOWORLD'
  51. >>> AZ('Hello, world!'.split())
  52. ['HELLO', 'WORLD']
  53. See Also
  54. ========
  55. check_and_join
  56. """
  57. if not s:
  58. return uppercase
  59. t = isinstance(s, str)
  60. if t:
  61. s = [s]
  62. rv = [check_and_join(i.upper().split(), uppercase, filter=True)
  63. for i in s]
  64. if t:
  65. return rv[0]
  66. return rv
  67. bifid5 = AZ().replace('J', '')
  68. bifid6 = AZ() + string.digits
  69. bifid10 = printable
  70. def padded_key(key, symbols):
  71. """Return a string of the distinct characters of ``symbols`` with
  72. those of ``key`` appearing first. A ValueError is raised if
  73. a) there are duplicate characters in ``symbols`` or
  74. b) there are characters in ``key`` that are not in ``symbols``.
  75. Examples
  76. ========
  77. >>> from sympy.crypto.crypto import padded_key
  78. >>> padded_key('PUPPY', 'OPQRSTUVWXY')
  79. 'PUYOQRSTVWX'
  80. >>> padded_key('RSA', 'ARTIST')
  81. Traceback (most recent call last):
  82. ...
  83. ValueError: duplicate characters in symbols: T
  84. """
  85. syms = list(uniq(symbols))
  86. if len(syms) != len(symbols):
  87. extra = ''.join(sorted({
  88. i for i in symbols if symbols.count(i) > 1}))
  89. raise ValueError('duplicate characters in symbols: %s' % extra)
  90. extra = set(key) - set(syms)
  91. if extra:
  92. raise ValueError(
  93. 'characters in key but not symbols: %s' % ''.join(
  94. sorted(extra)))
  95. key0 = ''.join(list(uniq(key)))
  96. # remove from syms characters in key0
  97. return key0 + translate(''.join(syms), None, key0)
  98. def check_and_join(phrase, symbols=None, filter=None):
  99. """
  100. Joins characters of ``phrase`` and if ``symbols`` is given, raises
  101. an error if any character in ``phrase`` is not in ``symbols``.
  102. Parameters
  103. ==========
  104. phrase
  105. String or list of strings to be returned as a string.
  106. symbols
  107. Iterable of characters allowed in ``phrase``.
  108. If ``symbols`` is ``None``, no checking is performed.
  109. Examples
  110. ========
  111. >>> from sympy.crypto.crypto import check_and_join
  112. >>> check_and_join('a phrase')
  113. 'a phrase'
  114. >>> check_and_join('a phrase'.upper().split())
  115. 'APHRASE'
  116. >>> check_and_join('a phrase!'.upper().split(), 'ARE', filter=True)
  117. 'ARAE'
  118. >>> check_and_join('a phrase!'.upper().split(), 'ARE')
  119. Traceback (most recent call last):
  120. ...
  121. ValueError: characters in phrase but not symbols: "!HPS"
  122. """
  123. rv = ''.join(''.join(phrase))
  124. if symbols is not None:
  125. symbols = check_and_join(symbols)
  126. missing = ''.join(sorted(set(rv) - set(symbols)))
  127. if missing:
  128. if not filter:
  129. raise ValueError(
  130. 'characters in phrase but not symbols: "%s"' % missing)
  131. rv = translate(rv, None, missing)
  132. return rv
  133. def _prep(msg, key, alp, default=None):
  134. if not alp:
  135. if not default:
  136. alp = AZ()
  137. msg = AZ(msg)
  138. key = AZ(key)
  139. else:
  140. alp = default
  141. else:
  142. alp = ''.join(alp)
  143. key = check_and_join(key, alp, filter=True)
  144. msg = check_and_join(msg, alp, filter=True)
  145. return msg, key, alp
  146. def cycle_list(k, n):
  147. """
  148. Returns the elements of the list ``range(n)`` shifted to the
  149. left by ``k`` (so the list starts with ``k`` (mod ``n``)).
  150. Examples
  151. ========
  152. >>> from sympy.crypto.crypto import cycle_list
  153. >>> cycle_list(3, 10)
  154. [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
  155. """
  156. k = k % n
  157. return list(range(k, n)) + list(range(k))
  158. ######## shift cipher examples ############
  159. def encipher_shift(msg, key, symbols=None):
  160. """
  161. Performs shift cipher encryption on plaintext msg, and returns the
  162. ciphertext.
  163. Parameters
  164. ==========
  165. key : int
  166. The secret key.
  167. msg : str
  168. Plaintext of upper-case letters.
  169. Returns
  170. =======
  171. str
  172. Ciphertext of upper-case letters.
  173. Examples
  174. ========
  175. >>> from sympy.crypto.crypto import encipher_shift, decipher_shift
  176. >>> msg = "GONAVYBEATARMY"
  177. >>> ct = encipher_shift(msg, 1); ct
  178. 'HPOBWZCFBUBSNZ'
  179. To decipher the shifted text, change the sign of the key:
  180. >>> encipher_shift(ct, -1)
  181. 'GONAVYBEATARMY'
  182. There is also a convenience function that does this with the
  183. original key:
  184. >>> decipher_shift(ct, 1)
  185. 'GONAVYBEATARMY'
  186. Notes
  187. =====
  188. ALGORITHM:
  189. STEPS:
  190. 0. Number the letters of the alphabet from 0, ..., N
  191. 1. Compute from the string ``msg`` a list ``L1`` of
  192. corresponding integers.
  193. 2. Compute from the list ``L1`` a new list ``L2``, given by
  194. adding ``(k mod 26)`` to each element in ``L1``.
  195. 3. Compute from the list ``L2`` a string ``ct`` of
  196. corresponding letters.
  197. The shift cipher is also called the Caesar cipher, after
  198. Julius Caesar, who, according to Suetonius, used it with a
  199. shift of three to protect messages of military significance.
  200. Caesar's nephew Augustus reportedly used a similar cipher, but
  201. with a right shift of 1.
  202. References
  203. ==========
  204. .. [1] https://en.wikipedia.org/wiki/Caesar_cipher
  205. .. [2] https://mathworld.wolfram.com/CaesarsMethod.html
  206. See Also
  207. ========
  208. decipher_shift
  209. """
  210. msg, _, A = _prep(msg, '', symbols)
  211. shift = len(A) - key % len(A)
  212. key = A[shift:] + A[:shift]
  213. return translate(msg, key, A)
  214. def decipher_shift(msg, key, symbols=None):
  215. """
  216. Return the text by shifting the characters of ``msg`` to the
  217. left by the amount given by ``key``.
  218. Examples
  219. ========
  220. >>> from sympy.crypto.crypto import encipher_shift, decipher_shift
  221. >>> msg = "GONAVYBEATARMY"
  222. >>> ct = encipher_shift(msg, 1); ct
  223. 'HPOBWZCFBUBSNZ'
  224. To decipher the shifted text, change the sign of the key:
  225. >>> encipher_shift(ct, -1)
  226. 'GONAVYBEATARMY'
  227. Or use this function with the original key:
  228. >>> decipher_shift(ct, 1)
  229. 'GONAVYBEATARMY'
  230. """
  231. return encipher_shift(msg, -key, symbols)
  232. def encipher_rot13(msg, symbols=None):
  233. """
  234. Performs the ROT13 encryption on a given plaintext ``msg``.
  235. Explanation
  236. ===========
  237. ROT13 is a substitution cipher which substitutes each letter
  238. in the plaintext message for the letter furthest away from it
  239. in the English alphabet.
  240. Equivalently, it is just a Caeser (shift) cipher with a shift
  241. key of 13 (midway point of the alphabet).
  242. References
  243. ==========
  244. .. [1] https://en.wikipedia.org/wiki/ROT13
  245. See Also
  246. ========
  247. decipher_rot13
  248. encipher_shift
  249. """
  250. return encipher_shift(msg, 13, symbols)
  251. def decipher_rot13(msg, symbols=None):
  252. """
  253. Performs the ROT13 decryption on a given plaintext ``msg``.
  254. Explanation
  255. ============
  256. ``decipher_rot13`` is equivalent to ``encipher_rot13`` as both
  257. ``decipher_shift`` with a key of 13 and ``encipher_shift`` key with a
  258. key of 13 will return the same results. Nonetheless,
  259. ``decipher_rot13`` has nonetheless been explicitly defined here for
  260. consistency.
  261. Examples
  262. ========
  263. >>> from sympy.crypto.crypto import encipher_rot13, decipher_rot13
  264. >>> msg = 'GONAVYBEATARMY'
  265. >>> ciphertext = encipher_rot13(msg);ciphertext
  266. 'TBANILORNGNEZL'
  267. >>> decipher_rot13(ciphertext)
  268. 'GONAVYBEATARMY'
  269. >>> encipher_rot13(msg) == decipher_rot13(msg)
  270. True
  271. >>> msg == decipher_rot13(ciphertext)
  272. True
  273. """
  274. return decipher_shift(msg, 13, symbols)
  275. ######## affine cipher examples ############
  276. def encipher_affine(msg, key, symbols=None, _inverse=False):
  277. r"""
  278. Performs the affine cipher encryption on plaintext ``msg``, and
  279. returns the ciphertext.
  280. Explanation
  281. ===========
  282. Encryption is based on the map `x \rightarrow ax+b` (mod `N`)
  283. where ``N`` is the number of characters in the alphabet.
  284. Decryption is based on the map `x \rightarrow cx+d` (mod `N`),
  285. where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
  286. In particular, for the map to be invertible, we need
  287. `\mathrm{gcd}(a, N) = 1` and an error will be raised if this is
  288. not true.
  289. Parameters
  290. ==========
  291. msg : str
  292. Characters that appear in ``symbols``.
  293. a, b : int, int
  294. A pair integers, with ``gcd(a, N) = 1`` (the secret key).
  295. symbols
  296. String of characters (default = uppercase letters).
  297. When no symbols are given, ``msg`` is converted to upper case
  298. letters and all other characters are ignored.
  299. Returns
  300. =======
  301. ct
  302. String of characters (the ciphertext message)
  303. Notes
  304. =====
  305. ALGORITHM:
  306. STEPS:
  307. 0. Number the letters of the alphabet from 0, ..., N
  308. 1. Compute from the string ``msg`` a list ``L1`` of
  309. corresponding integers.
  310. 2. Compute from the list ``L1`` a new list ``L2``, given by
  311. replacing ``x`` by ``a*x + b (mod N)``, for each element
  312. ``x`` in ``L1``.
  313. 3. Compute from the list ``L2`` a string ``ct`` of
  314. corresponding letters.
  315. This is a straightforward generalization of the shift cipher with
  316. the added complexity of requiring 2 characters to be deciphered in
  317. order to recover the key.
  318. References
  319. ==========
  320. .. [1] https://en.wikipedia.org/wiki/Affine_cipher
  321. See Also
  322. ========
  323. decipher_affine
  324. """
  325. msg, _, A = _prep(msg, '', symbols)
  326. N = len(A)
  327. a, b = key
  328. assert gcd(a, N) == 1
  329. if _inverse:
  330. c = invert(a, N)
  331. d = -b*c
  332. a, b = c, d
  333. B = ''.join([A[(a*i + b) % N] for i in range(N)])
  334. return translate(msg, A, B)
  335. def decipher_affine(msg, key, symbols=None):
  336. r"""
  337. Return the deciphered text that was made from the mapping,
  338. `x \rightarrow ax+b` (mod `N`), where ``N`` is the
  339. number of characters in the alphabet. Deciphering is done by
  340. reciphering with a new key: `x \rightarrow cx+d` (mod `N`),
  341. where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
  342. Examples
  343. ========
  344. >>> from sympy.crypto.crypto import encipher_affine, decipher_affine
  345. >>> msg = "GO NAVY BEAT ARMY"
  346. >>> key = (3, 1)
  347. >>> encipher_affine(msg, key)
  348. 'TROBMVENBGBALV'
  349. >>> decipher_affine(_, key)
  350. 'GONAVYBEATARMY'
  351. See Also
  352. ========
  353. encipher_affine
  354. """
  355. return encipher_affine(msg, key, symbols, _inverse=True)
  356. def encipher_atbash(msg, symbols=None):
  357. r"""
  358. Enciphers a given ``msg`` into its Atbash ciphertext and returns it.
  359. Explanation
  360. ===========
  361. Atbash is a substitution cipher originally used to encrypt the Hebrew
  362. alphabet. Atbash works on the principle of mapping each alphabet to its
  363. reverse / counterpart (i.e. a would map to z, b to y etc.)
  364. Atbash is functionally equivalent to the affine cipher with ``a = 25``
  365. and ``b = 25``
  366. See Also
  367. ========
  368. decipher_atbash
  369. """
  370. return encipher_affine(msg, (25, 25), symbols)
  371. def decipher_atbash(msg, symbols=None):
  372. r"""
  373. Deciphers a given ``msg`` using Atbash cipher and returns it.
  374. Explanation
  375. ===========
  376. ``decipher_atbash`` is functionally equivalent to ``encipher_atbash``.
  377. However, it has still been added as a separate function to maintain
  378. consistency.
  379. Examples
  380. ========
  381. >>> from sympy.crypto.crypto import encipher_atbash, decipher_atbash
  382. >>> msg = 'GONAVYBEATARMY'
  383. >>> encipher_atbash(msg)
  384. 'TLMZEBYVZGZINB'
  385. >>> decipher_atbash(msg)
  386. 'TLMZEBYVZGZINB'
  387. >>> encipher_atbash(msg) == decipher_atbash(msg)
  388. True
  389. >>> msg == encipher_atbash(encipher_atbash(msg))
  390. True
  391. References
  392. ==========
  393. .. [1] https://en.wikipedia.org/wiki/Atbash
  394. See Also
  395. ========
  396. encipher_atbash
  397. """
  398. return decipher_affine(msg, (25, 25), symbols)
  399. #################### substitution cipher ###########################
  400. def encipher_substitution(msg, old, new=None):
  401. r"""
  402. Returns the ciphertext obtained by replacing each character that
  403. appears in ``old`` with the corresponding character in ``new``.
  404. If ``old`` is a mapping, then new is ignored and the replacements
  405. defined by ``old`` are used.
  406. Explanation
  407. ===========
  408. This is a more general than the affine cipher in that the key can
  409. only be recovered by determining the mapping for each symbol.
  410. Though in practice, once a few symbols are recognized the mappings
  411. for other characters can be quickly guessed.
  412. Examples
  413. ========
  414. >>> from sympy.crypto.crypto import encipher_substitution, AZ
  415. >>> old = 'OEYAG'
  416. >>> new = '034^6'
  417. >>> msg = AZ("go navy! beat army!")
  418. >>> ct = encipher_substitution(msg, old, new); ct
  419. '60N^V4B3^T^RM4'
  420. To decrypt a substitution, reverse the last two arguments:
  421. >>> encipher_substitution(ct, new, old)
  422. 'GONAVYBEATARMY'
  423. In the special case where ``old`` and ``new`` are a permutation of
  424. order 2 (representing a transposition of characters) their order
  425. is immaterial:
  426. >>> old = 'NAVY'
  427. >>> new = 'ANYV'
  428. >>> encipher = lambda x: encipher_substitution(x, old, new)
  429. >>> encipher('NAVY')
  430. 'ANYV'
  431. >>> encipher(_)
  432. 'NAVY'
  433. The substitution cipher, in general, is a method
  434. whereby "units" (not necessarily single characters) of plaintext
  435. are replaced with ciphertext according to a regular system.
  436. >>> ords = dict(zip('abc', ['\\%i' % ord(i) for i in 'abc']))
  437. >>> print(encipher_substitution('abc', ords))
  438. \97\98\99
  439. References
  440. ==========
  441. .. [1] https://en.wikipedia.org/wiki/Substitution_cipher
  442. """
  443. return translate(msg, old, new)
  444. ######################################################################
  445. #################### Vigenere cipher examples ########################
  446. ######################################################################
  447. def encipher_vigenere(msg, key, symbols=None):
  448. """
  449. Performs the Vigenere cipher encryption on plaintext ``msg``, and
  450. returns the ciphertext.
  451. Examples
  452. ========
  453. >>> from sympy.crypto.crypto import encipher_vigenere, AZ
  454. >>> key = "encrypt"
  455. >>> msg = "meet me on monday"
  456. >>> encipher_vigenere(msg, key)
  457. 'QRGKKTHRZQEBPR'
  458. Section 1 of the Kryptos sculpture at the CIA headquarters
  459. uses this cipher and also changes the order of the
  460. alphabet [2]_. Here is the first line of that section of
  461. the sculpture:
  462. >>> from sympy.crypto.crypto import decipher_vigenere, padded_key
  463. >>> alp = padded_key('KRYPTOS', AZ())
  464. >>> key = 'PALIMPSEST'
  465. >>> msg = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJ'
  466. >>> decipher_vigenere(msg, key, alp)
  467. 'BETWEENSUBTLESHADINGANDTHEABSENC'
  468. Explanation
  469. ===========
  470. The Vigenere cipher is named after Blaise de Vigenere, a sixteenth
  471. century diplomat and cryptographer, by a historical accident.
  472. Vigenere actually invented a different and more complicated cipher.
  473. The so-called *Vigenere cipher* was actually invented
  474. by Giovan Batista Belaso in 1553.
  475. This cipher was used in the 1800's, for example, during the American
  476. Civil War. The Confederacy used a brass cipher disk to implement the
  477. Vigenere cipher (now on display in the NSA Museum in Fort
  478. Meade) [1]_.
  479. The Vigenere cipher is a generalization of the shift cipher.
  480. Whereas the shift cipher shifts each letter by the same amount
  481. (that amount being the key of the shift cipher) the Vigenere
  482. cipher shifts a letter by an amount determined by the key (which is
  483. a word or phrase known only to the sender and receiver).
  484. For example, if the key was a single letter, such as "C", then the
  485. so-called Vigenere cipher is actually a shift cipher with a
  486. shift of `2` (since "C" is the 2nd letter of the alphabet, if
  487. you start counting at `0`). If the key was a word with two
  488. letters, such as "CA", then the so-called Vigenere cipher will
  489. shift letters in even positions by `2` and letters in odd positions
  490. are left alone (shifted by `0`, since "A" is the 0th letter, if
  491. you start counting at `0`).
  492. ALGORITHM:
  493. INPUT:
  494. ``msg``: string of characters that appear in ``symbols``
  495. (the plaintext)
  496. ``key``: a string of characters that appear in ``symbols``
  497. (the secret key)
  498. ``symbols``: a string of letters defining the alphabet
  499. OUTPUT:
  500. ``ct``: string of characters (the ciphertext message)
  501. STEPS:
  502. 0. Number the letters of the alphabet from 0, ..., N
  503. 1. Compute from the string ``key`` a list ``L1`` of
  504. corresponding integers. Let ``n1 = len(L1)``.
  505. 2. Compute from the string ``msg`` a list ``L2`` of
  506. corresponding integers. Let ``n2 = len(L2)``.
  507. 3. Break ``L2`` up sequentially into sublists of size
  508. ``n1``; the last sublist may be smaller than ``n1``
  509. 4. For each of these sublists ``L`` of ``L2``, compute a
  510. new list ``C`` given by ``C[i] = L[i] + L1[i] (mod N)``
  511. to the ``i``-th element in the sublist, for each ``i``.
  512. 5. Assemble these lists ``C`` by concatenation into a new
  513. list of length ``n2``.
  514. 6. Compute from the new list a string ``ct`` of
  515. corresponding letters.
  516. Once it is known that the key is, say, `n` characters long,
  517. frequency analysis can be applied to every `n`-th letter of
  518. the ciphertext to determine the plaintext. This method is
  519. called *Kasiski examination* (although it was first discovered
  520. by Babbage). If they key is as long as the message and is
  521. comprised of randomly selected characters -- a one-time pad -- the
  522. message is theoretically unbreakable.
  523. The cipher Vigenere actually discovered is an "auto-key" cipher
  524. described as follows.
  525. ALGORITHM:
  526. INPUT:
  527. ``key``: a string of letters (the secret key)
  528. ``msg``: string of letters (the plaintext message)
  529. OUTPUT:
  530. ``ct``: string of upper-case letters (the ciphertext message)
  531. STEPS:
  532. 0. Number the letters of the alphabet from 0, ..., N
  533. 1. Compute from the string ``msg`` a list ``L2`` of
  534. corresponding integers. Let ``n2 = len(L2)``.
  535. 2. Let ``n1`` be the length of the key. Append to the
  536. string ``key`` the first ``n2 - n1`` characters of
  537. the plaintext message. Compute from this string (also of
  538. length ``n2``) a list ``L1`` of integers corresponding
  539. to the letter numbers in the first step.
  540. 3. Compute a new list ``C`` given by
  541. ``C[i] = L1[i] + L2[i] (mod N)``.
  542. 4. Compute from the new list a string ``ct`` of letters
  543. corresponding to the new integers.
  544. To decipher the auto-key ciphertext, the key is used to decipher
  545. the first ``n1`` characters and then those characters become the
  546. key to decipher the next ``n1`` characters, etc...:
  547. >>> m = AZ('go navy, beat army! yes you can'); m
  548. 'GONAVYBEATARMYYESYOUCAN'
  549. >>> key = AZ('gold bug'); n1 = len(key); n2 = len(m)
  550. >>> auto_key = key + m[:n2 - n1]; auto_key
  551. 'GOLDBUGGONAVYBEATARMYYE'
  552. >>> ct = encipher_vigenere(m, auto_key); ct
  553. 'MCYDWSHKOGAMKZCELYFGAYR'
  554. >>> n1 = len(key)
  555. >>> pt = []
  556. >>> while ct:
  557. ... part, ct = ct[:n1], ct[n1:]
  558. ... pt.append(decipher_vigenere(part, key))
  559. ... key = pt[-1]
  560. ...
  561. >>> ''.join(pt) == m
  562. True
  563. References
  564. ==========
  565. .. [1] https://en.wikipedia.org/wiki/Vigenere_cipher
  566. .. [2] https://web.archive.org/web/20071116100808/https://filebox.vt.edu/users/batman/kryptos.html
  567. (short URL: https://goo.gl/ijr22d)
  568. """
  569. msg, key, A = _prep(msg, key, symbols)
  570. map = {c: i for i, c in enumerate(A)}
  571. key = [map[c] for c in key]
  572. N = len(map)
  573. k = len(key)
  574. rv = []
  575. for i, m in enumerate(msg):
  576. rv.append(A[(map[m] + key[i % k]) % N])
  577. rv = ''.join(rv)
  578. return rv
  579. def decipher_vigenere(msg, key, symbols=None):
  580. """
  581. Decode using the Vigenere cipher.
  582. Examples
  583. ========
  584. >>> from sympy.crypto.crypto import decipher_vigenere
  585. >>> key = "encrypt"
  586. >>> ct = "QRGK kt HRZQE BPR"
  587. >>> decipher_vigenere(ct, key)
  588. 'MEETMEONMONDAY'
  589. """
  590. msg, key, A = _prep(msg, key, symbols)
  591. map = {c: i for i, c in enumerate(A)}
  592. N = len(A) # normally, 26
  593. K = [map[c] for c in key]
  594. n = len(K)
  595. C = [map[c] for c in msg]
  596. rv = ''.join([A[(-K[i % n] + c) % N] for i, c in enumerate(C)])
  597. return rv
  598. #################### Hill cipher ########################
  599. def encipher_hill(msg, key, symbols=None, pad="Q"):
  600. r"""
  601. Return the Hill cipher encryption of ``msg``.
  602. Explanation
  603. ===========
  604. The Hill cipher [1]_, invented by Lester S. Hill in the 1920's [2]_,
  605. was the first polygraphic cipher in which it was practical
  606. (though barely) to operate on more than three symbols at once.
  607. The following discussion assumes an elementary knowledge of
  608. matrices.
  609. First, each letter is first encoded as a number starting with 0.
  610. Suppose your message `msg` consists of `n` capital letters, with no
  611. spaces. This may be regarded an `n`-tuple M of elements of
  612. `Z_{26}` (if the letters are those of the English alphabet). A key
  613. in the Hill cipher is a `k x k` matrix `K`, all of whose entries
  614. are in `Z_{26}`, such that the matrix `K` is invertible (i.e., the
  615. linear transformation `K: Z_{N}^k \rightarrow Z_{N}^k`
  616. is one-to-one).
  617. Parameters
  618. ==========
  619. msg
  620. Plaintext message of `n` upper-case letters.
  621. key
  622. A `k \times k` invertible matrix `K`, all of whose entries are
  623. in `Z_{26}` (or whatever number of symbols are being used).
  624. pad
  625. Character (default "Q") to use to make length of text be a
  626. multiple of ``k``.
  627. Returns
  628. =======
  629. ct
  630. Ciphertext of upper-case letters.
  631. Notes
  632. =====
  633. ALGORITHM:
  634. STEPS:
  635. 0. Number the letters of the alphabet from 0, ..., N
  636. 1. Compute from the string ``msg`` a list ``L`` of
  637. corresponding integers. Let ``n = len(L)``.
  638. 2. Break the list ``L`` up into ``t = ceiling(n/k)``
  639. sublists ``L_1``, ..., ``L_t`` of size ``k`` (with
  640. the last list "padded" to ensure its size is
  641. ``k``).
  642. 3. Compute new list ``C_1``, ..., ``C_t`` given by
  643. ``C[i] = K*L_i`` (arithmetic is done mod N), for each
  644. ``i``.
  645. 4. Concatenate these into a list ``C = C_1 + ... + C_t``.
  646. 5. Compute from ``C`` a string ``ct`` of corresponding
  647. letters. This has length ``k*t``.
  648. References
  649. ==========
  650. .. [1] https://en.wikipedia.org/wiki/Hill_cipher
  651. .. [2] Lester S. Hill, Cryptography in an Algebraic Alphabet,
  652. The American Mathematical Monthly Vol.36, June-July 1929,
  653. pp.306-312.
  654. See Also
  655. ========
  656. decipher_hill
  657. """
  658. assert key.is_square
  659. assert len(pad) == 1
  660. msg, pad, A = _prep(msg, pad, symbols)
  661. map = {c: i for i, c in enumerate(A)}
  662. P = [map[c] for c in msg]
  663. N = len(A)
  664. k = key.cols
  665. n = len(P)
  666. m, r = divmod(n, k)
  667. if r:
  668. P = P + [map[pad]]*(k - r)
  669. m += 1
  670. rv = ''.join([A[c % N] for j in range(m) for c in
  671. list(key*Matrix(k, 1, [P[i]
  672. for i in range(k*j, k*(j + 1))]))])
  673. return rv
  674. def decipher_hill(msg, key, symbols=None):
  675. """
  676. Deciphering is the same as enciphering but using the inverse of the
  677. key matrix.
  678. Examples
  679. ========
  680. >>> from sympy.crypto.crypto import encipher_hill, decipher_hill
  681. >>> from sympy import Matrix
  682. >>> key = Matrix([[1, 2], [3, 5]])
  683. >>> encipher_hill("meet me on monday", key)
  684. 'UEQDUEODOCTCWQ'
  685. >>> decipher_hill(_, key)
  686. 'MEETMEONMONDAY'
  687. When the length of the plaintext (stripped of invalid characters)
  688. is not a multiple of the key dimension, extra characters will
  689. appear at the end of the enciphered and deciphered text. In order to
  690. decipher the text, those characters must be included in the text to
  691. be deciphered. In the following, the key has a dimension of 4 but
  692. the text is 2 short of being a multiple of 4 so two characters will
  693. be added.
  694. >>> key = Matrix([[1, 1, 1, 2], [0, 1, 1, 0],
  695. ... [2, 2, 3, 4], [1, 1, 0, 1]])
  696. >>> msg = "ST"
  697. >>> encipher_hill(msg, key)
  698. 'HJEB'
  699. >>> decipher_hill(_, key)
  700. 'STQQ'
  701. >>> encipher_hill(msg, key, pad="Z")
  702. 'ISPK'
  703. >>> decipher_hill(_, key)
  704. 'STZZ'
  705. If the last two characters of the ciphertext were ignored in
  706. either case, the wrong plaintext would be recovered:
  707. >>> decipher_hill("HD", key)
  708. 'ORMV'
  709. >>> decipher_hill("IS", key)
  710. 'UIKY'
  711. See Also
  712. ========
  713. encipher_hill
  714. """
  715. assert key.is_square
  716. msg, _, A = _prep(msg, '', symbols)
  717. map = {c: i for i, c in enumerate(A)}
  718. C = [map[c] for c in msg]
  719. N = len(A)
  720. k = key.cols
  721. n = len(C)
  722. m, r = divmod(n, k)
  723. if r:
  724. C = C + [0]*(k - r)
  725. m += 1
  726. key_inv = key.inv_mod(N)
  727. rv = ''.join([A[p % N] for j in range(m) for p in
  728. list(key_inv*Matrix(
  729. k, 1, [C[i] for i in range(k*j, k*(j + 1))]))])
  730. return rv
  731. #################### Bifid cipher ########################
  732. def encipher_bifid(msg, key, symbols=None):
  733. r"""
  734. Performs the Bifid cipher encryption on plaintext ``msg``, and
  735. returns the ciphertext.
  736. This is the version of the Bifid cipher that uses an `n \times n`
  737. Polybius square.
  738. Parameters
  739. ==========
  740. msg
  741. Plaintext string.
  742. key
  743. Short string for key.
  744. Duplicate characters are ignored and then it is padded with the
  745. characters in ``symbols`` that were not in the short key.
  746. symbols
  747. `n \times n` characters defining the alphabet.
  748. (default is string.printable)
  749. Returns
  750. =======
  751. ciphertext
  752. Ciphertext using Bifid5 cipher without spaces.
  753. See Also
  754. ========
  755. decipher_bifid, encipher_bifid5, encipher_bifid6
  756. References
  757. ==========
  758. .. [1] https://en.wikipedia.org/wiki/Bifid_cipher
  759. """
  760. msg, key, A = _prep(msg, key, symbols, bifid10)
  761. long_key = ''.join(uniq(key)) or A
  762. n = len(A)**.5
  763. if n != int(n):
  764. raise ValueError(
  765. 'Length of alphabet (%s) is not a square number.' % len(A))
  766. N = int(n)
  767. if len(long_key) < N**2:
  768. long_key = list(long_key) + [x for x in A if x not in long_key]
  769. # the fractionalization
  770. row_col = {ch: divmod(i, N) for i, ch in enumerate(long_key)}
  771. r, c = zip(*[row_col[x] for x in msg])
  772. rc = r + c
  773. ch = {i: ch for ch, i in row_col.items()}
  774. rv = ''.join(ch[i] for i in zip(rc[::2], rc[1::2]))
  775. return rv
  776. def decipher_bifid(msg, key, symbols=None):
  777. r"""
  778. Performs the Bifid cipher decryption on ciphertext ``msg``, and
  779. returns the plaintext.
  780. This is the version of the Bifid cipher that uses the `n \times n`
  781. Polybius square.
  782. Parameters
  783. ==========
  784. msg
  785. Ciphertext string.
  786. key
  787. Short string for key.
  788. Duplicate characters are ignored and then it is padded with the
  789. characters in symbols that were not in the short key.
  790. symbols
  791. `n \times n` characters defining the alphabet.
  792. (default=string.printable, a `10 \times 10` matrix)
  793. Returns
  794. =======
  795. deciphered
  796. Deciphered text.
  797. Examples
  798. ========
  799. >>> from sympy.crypto.crypto import (
  800. ... encipher_bifid, decipher_bifid, AZ)
  801. Do an encryption using the bifid5 alphabet:
  802. >>> alp = AZ().replace('J', '')
  803. >>> ct = AZ("meet me on monday!")
  804. >>> key = AZ("gold bug")
  805. >>> encipher_bifid(ct, key, alp)
  806. 'IEILHHFSTSFQYE'
  807. When entering the text or ciphertext, spaces are ignored so it
  808. can be formatted as desired. Re-entering the ciphertext from the
  809. preceding, putting 4 characters per line and padding with an extra
  810. J, does not cause problems for the deciphering:
  811. >>> decipher_bifid('''
  812. ... IEILH
  813. ... HFSTS
  814. ... FQYEJ''', key, alp)
  815. 'MEETMEONMONDAY'
  816. When no alphabet is given, all 100 printable characters will be
  817. used:
  818. >>> key = ''
  819. >>> encipher_bifid('hello world!', key)
  820. 'bmtwmg-bIo*w'
  821. >>> decipher_bifid(_, key)
  822. 'hello world!'
  823. If the key is changed, a different encryption is obtained:
  824. >>> key = 'gold bug'
  825. >>> encipher_bifid('hello world!', 'gold_bug')
  826. 'hg2sfuei7t}w'
  827. And if the key used to decrypt the message is not exact, the
  828. original text will not be perfectly obtained:
  829. >>> decipher_bifid(_, 'gold pug')
  830. 'heldo~wor6d!'
  831. """
  832. msg, _, A = _prep(msg, '', symbols, bifid10)
  833. long_key = ''.join(uniq(key)) or A
  834. n = len(A)**.5
  835. if n != int(n):
  836. raise ValueError(
  837. 'Length of alphabet (%s) is not a square number.' % len(A))
  838. N = int(n)
  839. if len(long_key) < N**2:
  840. long_key = list(long_key) + [x for x in A if x not in long_key]
  841. # the reverse fractionalization
  842. row_col = {
  843. ch: divmod(i, N) for i, ch in enumerate(long_key)}
  844. rc = [i for c in msg for i in row_col[c]]
  845. n = len(msg)
  846. rc = zip(*(rc[:n], rc[n:]))
  847. ch = {i: ch for ch, i in row_col.items()}
  848. rv = ''.join(ch[i] for i in rc)
  849. return rv
  850. def bifid_square(key):
  851. """Return characters of ``key`` arranged in a square.
  852. Examples
  853. ========
  854. >>> from sympy.crypto.crypto import (
  855. ... bifid_square, AZ, padded_key, bifid5)
  856. >>> bifid_square(AZ().replace('J', ''))
  857. Matrix([
  858. [A, B, C, D, E],
  859. [F, G, H, I, K],
  860. [L, M, N, O, P],
  861. [Q, R, S, T, U],
  862. [V, W, X, Y, Z]])
  863. >>> bifid_square(padded_key(AZ('gold bug!'), bifid5))
  864. Matrix([
  865. [G, O, L, D, B],
  866. [U, A, C, E, F],
  867. [H, I, K, M, N],
  868. [P, Q, R, S, T],
  869. [V, W, X, Y, Z]])
  870. See Also
  871. ========
  872. padded_key
  873. """
  874. A = ''.join(uniq(''.join(key)))
  875. n = len(A)**.5
  876. if n != int(n):
  877. raise ValueError(
  878. 'Length of alphabet (%s) is not a square number.' % len(A))
  879. n = int(n)
  880. f = lambda i, j: Symbol(A[n*i + j])
  881. rv = Matrix(n, n, f)
  882. return rv
  883. def encipher_bifid5(msg, key):
  884. r"""
  885. Performs the Bifid cipher encryption on plaintext ``msg``, and
  886. returns the ciphertext.
  887. Explanation
  888. ===========
  889. This is the version of the Bifid cipher that uses the `5 \times 5`
  890. Polybius square. The letter "J" is ignored so it must be replaced
  891. with something else (traditionally an "I") before encryption.
  892. ALGORITHM: (5x5 case)
  893. STEPS:
  894. 0. Create the `5 \times 5` Polybius square ``S`` associated
  895. to ``key`` as follows:
  896. a) moving from left-to-right, top-to-bottom,
  897. place the letters of the key into a `5 \times 5`
  898. matrix,
  899. b) if the key has less than 25 letters, add the
  900. letters of the alphabet not in the key until the
  901. `5 \times 5` square is filled.
  902. 1. Create a list ``P`` of pairs of numbers which are the
  903. coordinates in the Polybius square of the letters in
  904. ``msg``.
  905. 2. Let ``L1`` be the list of all first coordinates of ``P``
  906. (length of ``L1 = n``), let ``L2`` be the list of all
  907. second coordinates of ``P`` (so the length of ``L2``
  908. is also ``n``).
  909. 3. Let ``L`` be the concatenation of ``L1`` and ``L2``
  910. (length ``L = 2*n``), except that consecutive numbers
  911. are paired ``(L[2*i], L[2*i + 1])``. You can regard
  912. ``L`` as a list of pairs of length ``n``.
  913. 4. Let ``C`` be the list of all letters which are of the
  914. form ``S[i, j]``, for all ``(i, j)`` in ``L``. As a
  915. string, this is the ciphertext of ``msg``.
  916. Parameters
  917. ==========
  918. msg : str
  919. Plaintext string.
  920. Converted to upper case and filtered of anything but all letters
  921. except J.
  922. key
  923. Short string for key; non-alphabetic letters, J and duplicated
  924. characters are ignored and then, if the length is less than 25
  925. characters, it is padded with other letters of the alphabet
  926. (in alphabetical order).
  927. Returns
  928. =======
  929. ct
  930. Ciphertext (all caps, no spaces).
  931. Examples
  932. ========
  933. >>> from sympy.crypto.crypto import (
  934. ... encipher_bifid5, decipher_bifid5)
  935. "J" will be omitted unless it is replaced with something else:
  936. >>> round_trip = lambda m, k: \
  937. ... decipher_bifid5(encipher_bifid5(m, k), k)
  938. >>> key = 'a'
  939. >>> msg = "JOSIE"
  940. >>> round_trip(msg, key)
  941. 'OSIE'
  942. >>> round_trip(msg.replace("J", "I"), key)
  943. 'IOSIE'
  944. >>> j = "QIQ"
  945. >>> round_trip(msg.replace("J", j), key).replace(j, "J")
  946. 'JOSIE'
  947. Notes
  948. =====
  949. The Bifid cipher was invented around 1901 by Felix Delastelle.
  950. It is a *fractional substitution* cipher, where letters are
  951. replaced by pairs of symbols from a smaller alphabet. The
  952. cipher uses a `5 \times 5` square filled with some ordering of the
  953. alphabet, except that "J" is replaced with "I" (this is a so-called
  954. Polybius square; there is a `6 \times 6` analog if you add back in
  955. "J" and also append onto the usual 26 letter alphabet, the digits
  956. 0, 1, ..., 9).
  957. According to Helen Gaines' book *Cryptanalysis*, this type of cipher
  958. was used in the field by the German Army during World War I.
  959. See Also
  960. ========
  961. decipher_bifid5, encipher_bifid
  962. """
  963. msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
  964. key = padded_key(key, bifid5)
  965. return encipher_bifid(msg, '', key)
  966. def decipher_bifid5(msg, key):
  967. r"""
  968. Return the Bifid cipher decryption of ``msg``.
  969. Explanation
  970. ===========
  971. This is the version of the Bifid cipher that uses the `5 \times 5`
  972. Polybius square; the letter "J" is ignored unless a ``key`` of
  973. length 25 is used.
  974. Parameters
  975. ==========
  976. msg
  977. Ciphertext string.
  978. key
  979. Short string for key; duplicated characters are ignored and if
  980. the length is less then 25 characters, it will be padded with
  981. other letters from the alphabet omitting "J".
  982. Non-alphabetic characters are ignored.
  983. Returns
  984. =======
  985. plaintext
  986. Plaintext from Bifid5 cipher (all caps, no spaces).
  987. Examples
  988. ========
  989. >>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5
  990. >>> key = "gold bug"
  991. >>> encipher_bifid5('meet me on friday', key)
  992. 'IEILEHFSTSFXEE'
  993. >>> encipher_bifid5('meet me on monday', key)
  994. 'IEILHHFSTSFQYE'
  995. >>> decipher_bifid5(_, key)
  996. 'MEETMEONMONDAY'
  997. """
  998. msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
  999. key = padded_key(key, bifid5)
  1000. return decipher_bifid(msg, '', key)
  1001. def bifid5_square(key=None):
  1002. r"""
  1003. 5x5 Polybius square.
  1004. Produce the Polybius square for the `5 \times 5` Bifid cipher.
  1005. Examples
  1006. ========
  1007. >>> from sympy.crypto.crypto import bifid5_square
  1008. >>> bifid5_square("gold bug")
  1009. Matrix([
  1010. [G, O, L, D, B],
  1011. [U, A, C, E, F],
  1012. [H, I, K, M, N],
  1013. [P, Q, R, S, T],
  1014. [V, W, X, Y, Z]])
  1015. """
  1016. if not key:
  1017. key = bifid5
  1018. else:
  1019. _, key, _ = _prep('', key.upper(), None, bifid5)
  1020. key = padded_key(key, bifid5)
  1021. return bifid_square(key)
  1022. def encipher_bifid6(msg, key):
  1023. r"""
  1024. Performs the Bifid cipher encryption on plaintext ``msg``, and
  1025. returns the ciphertext.
  1026. This is the version of the Bifid cipher that uses the `6 \times 6`
  1027. Polybius square.
  1028. Parameters
  1029. ==========
  1030. msg
  1031. Plaintext string (digits okay).
  1032. key
  1033. Short string for key (digits okay).
  1034. If ``key`` is less than 36 characters long, the square will be
  1035. filled with letters A through Z and digits 0 through 9.
  1036. Returns
  1037. =======
  1038. ciphertext
  1039. Ciphertext from Bifid cipher (all caps, no spaces).
  1040. See Also
  1041. ========
  1042. decipher_bifid6, encipher_bifid
  1043. """
  1044. msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
  1045. key = padded_key(key, bifid6)
  1046. return encipher_bifid(msg, '', key)
  1047. def decipher_bifid6(msg, key):
  1048. r"""
  1049. Performs the Bifid cipher decryption on ciphertext ``msg``, and
  1050. returns the plaintext.
  1051. This is the version of the Bifid cipher that uses the `6 \times 6`
  1052. Polybius square.
  1053. Parameters
  1054. ==========
  1055. msg
  1056. Ciphertext string (digits okay); converted to upper case
  1057. key
  1058. Short string for key (digits okay).
  1059. If ``key`` is less than 36 characters long, the square will be
  1060. filled with letters A through Z and digits 0 through 9.
  1061. All letters are converted to uppercase.
  1062. Returns
  1063. =======
  1064. plaintext
  1065. Plaintext from Bifid cipher (all caps, no spaces).
  1066. Examples
  1067. ========
  1068. >>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6
  1069. >>> key = "gold bug"
  1070. >>> encipher_bifid6('meet me on monday at 8am', key)
  1071. 'KFKLJJHF5MMMKTFRGPL'
  1072. >>> decipher_bifid6(_, key)
  1073. 'MEETMEONMONDAYAT8AM'
  1074. """
  1075. msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
  1076. key = padded_key(key, bifid6)
  1077. return decipher_bifid(msg, '', key)
  1078. def bifid6_square(key=None):
  1079. r"""
  1080. 6x6 Polybius square.
  1081. Produces the Polybius square for the `6 \times 6` Bifid cipher.
  1082. Assumes alphabet of symbols is "A", ..., "Z", "0", ..., "9".
  1083. Examples
  1084. ========
  1085. >>> from sympy.crypto.crypto import bifid6_square
  1086. >>> key = "gold bug"
  1087. >>> bifid6_square(key)
  1088. Matrix([
  1089. [G, O, L, D, B, U],
  1090. [A, C, E, F, H, I],
  1091. [J, K, M, N, P, Q],
  1092. [R, S, T, V, W, X],
  1093. [Y, Z, 0, 1, 2, 3],
  1094. [4, 5, 6, 7, 8, 9]])
  1095. """
  1096. if not key:
  1097. key = bifid6
  1098. else:
  1099. _, key, _ = _prep('', key.upper(), None, bifid6)
  1100. key = padded_key(key, bifid6)
  1101. return bifid_square(key)
  1102. #################### RSA #############################
  1103. def _decipher_rsa_crt(i, d, factors):
  1104. """Decipher RSA using chinese remainder theorem from the information
  1105. of the relatively-prime factors of the modulus.
  1106. Parameters
  1107. ==========
  1108. i : integer
  1109. Ciphertext
  1110. d : integer
  1111. The exponent component.
  1112. factors : list of relatively-prime integers
  1113. The integers given must be coprime and the product must equal
  1114. the modulus component of the original RSA key.
  1115. Examples
  1116. ========
  1117. How to decrypt RSA with CRT:
  1118. >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
  1119. >>> primes = [61, 53]
  1120. >>> e = 17
  1121. >>> args = primes + [e]
  1122. >>> puk = rsa_public_key(*args)
  1123. >>> prk = rsa_private_key(*args)
  1124. >>> from sympy.crypto.crypto import encipher_rsa, _decipher_rsa_crt
  1125. >>> msg = 65
  1126. >>> crt_primes = primes
  1127. >>> encrypted = encipher_rsa(msg, puk)
  1128. >>> decrypted = _decipher_rsa_crt(encrypted, prk[1], primes)
  1129. >>> decrypted
  1130. 65
  1131. """
  1132. moduluses = [pow(i, d, p) for p in factors]
  1133. result = crt(factors, moduluses)
  1134. if not result:
  1135. raise ValueError("CRT failed")
  1136. return result[0]
  1137. def _rsa_key(*args, public=True, private=True, totient='Euler', index=None, multipower=None):
  1138. r"""A private subroutine to generate RSA key
  1139. Parameters
  1140. ==========
  1141. public, private : bool, optional
  1142. Flag to generate either a public key, a private key.
  1143. totient : 'Euler' or 'Carmichael'
  1144. Different notation used for totient.
  1145. multipower : bool, optional
  1146. Flag to bypass warning for multipower RSA.
  1147. """
  1148. if len(args) < 2:
  1149. return False
  1150. if totient not in ('Euler', 'Carmichael'):
  1151. raise ValueError(
  1152. "The argument totient={} should either be " \
  1153. "'Euler', 'Carmichalel'." \
  1154. .format(totient))
  1155. if totient == 'Euler':
  1156. _totient = _euler
  1157. else:
  1158. _totient = _carmichael
  1159. if index is not None:
  1160. index = as_int(index)
  1161. if totient != 'Carmichael':
  1162. raise ValueError(
  1163. "Setting the 'index' keyword argument requires totient"
  1164. "notation to be specified as 'Carmichael'.")
  1165. primes, e = args[:-1], args[-1]
  1166. if not all(isprime(p) for p in primes):
  1167. new_primes = []
  1168. for i in primes:
  1169. new_primes.extend(factorint(i, multiple=True))
  1170. primes = new_primes
  1171. n = reduce(lambda i, j: i*j, primes)
  1172. tally = multiset(primes)
  1173. if all(v == 1 for v in tally.values()):
  1174. phi = int(_totient(tally))
  1175. else:
  1176. if not multipower:
  1177. NonInvertibleCipherWarning(
  1178. 'Non-distinctive primes found in the factors {}. '
  1179. 'The cipher may not be decryptable for some numbers '
  1180. 'in the complete residue system Z[{}], but the cipher '
  1181. 'can still be valid if you restrict the domain to be '
  1182. 'the reduced residue system Z*[{}]. You can pass '
  1183. 'the flag multipower=True if you want to suppress this '
  1184. 'warning.'
  1185. .format(primes, n, n)
  1186. # stacklevel=4 because most users will call a function that
  1187. # calls this function
  1188. ).warn(stacklevel=4)
  1189. phi = int(_totient(tally))
  1190. if gcd(e, phi) == 1:
  1191. if public and not private:
  1192. if isinstance(index, int):
  1193. e = e % phi
  1194. e += index * phi
  1195. return n, e
  1196. if private and not public:
  1197. d = invert(e, phi)
  1198. if isinstance(index, int):
  1199. d += index * phi
  1200. return n, d
  1201. return False
  1202. def rsa_public_key(*args, **kwargs):
  1203. r"""Return the RSA *public key* pair, `(n, e)`
  1204. Parameters
  1205. ==========
  1206. args : naturals
  1207. If specified as `p, q, e` where `p` and `q` are distinct primes
  1208. and `e` is a desired public exponent of the RSA, `n = p q` and
  1209. `e` will be verified against the totient
  1210. `\phi(n)` (Euler totient) or `\lambda(n)` (Carmichael totient)
  1211. to be `\gcd(e, \phi(n)) = 1` or `\gcd(e, \lambda(n)) = 1`.
  1212. If specified as `p_1, p_2, \dots, p_n, e` where
  1213. `p_1, p_2, \dots, p_n` are specified as primes,
  1214. and `e` is specified as a desired public exponent of the RSA,
  1215. it will be able to form a multi-prime RSA, which is a more
  1216. generalized form of the popular 2-prime RSA.
  1217. It can also be possible to form a single-prime RSA by specifying
  1218. the argument as `p, e`, which can be considered a trivial case
  1219. of a multiprime RSA.
  1220. Furthermore, it can be possible to form a multi-power RSA by
  1221. specifying two or more pairs of the primes to be same.
  1222. However, unlike the two-distinct prime RSA or multi-prime
  1223. RSA, not every numbers in the complete residue system
  1224. (`\mathbb{Z}_n`) will be decryptable since the mapping
  1225. `\mathbb{Z}_{n} \rightarrow \mathbb{Z}_{n}`
  1226. will not be bijective.
  1227. (Only except for the trivial case when
  1228. `e = 1`
  1229. or more generally,
  1230. .. math::
  1231. e \in \left \{ 1 + k \lambda(n)
  1232. \mid k \in \mathbb{Z} \land k \geq 0 \right \}
  1233. when RSA reduces to the identity.)
  1234. However, the RSA can still be decryptable for the numbers in the
  1235. reduced residue system (`\mathbb{Z}_n^{\times}`), since the
  1236. mapping
  1237. `\mathbb{Z}_{n}^{\times} \rightarrow \mathbb{Z}_{n}^{\times}`
  1238. can still be bijective.
  1239. If you pass a non-prime integer to the arguments
  1240. `p_1, p_2, \dots, p_n`, the particular number will be
  1241. prime-factored and it will become either a multi-prime RSA or a
  1242. multi-power RSA in its canonical form, depending on whether the
  1243. product equals its radical or not.
  1244. `p_1 p_2 \dots p_n = \text{rad}(p_1 p_2 \dots p_n)`
  1245. totient : bool, optional
  1246. If ``'Euler'``, it uses Euler's totient `\phi(n)` which is
  1247. :meth:`sympy.functions.combinatorial.numbers.totient` in SymPy.
  1248. If ``'Carmichael'``, it uses Carmichael's totient `\lambda(n)`
  1249. which is :meth:`sympy.functions.combinatorial.numbers.reduced_totient` in SymPy.
  1250. Unlike private key generation, this is a trivial keyword for
  1251. public key generation because
  1252. `\gcd(e, \phi(n)) = 1 \iff \gcd(e, \lambda(n)) = 1`.
  1253. index : nonnegative integer, optional
  1254. Returns an arbitrary solution of a RSA public key at the index
  1255. specified at `0, 1, 2, \dots`. This parameter needs to be
  1256. specified along with ``totient='Carmichael'``.
  1257. Similarly to the non-uniquenss of a RSA private key as described
  1258. in the ``index`` parameter documentation in
  1259. :meth:`rsa_private_key`, RSA public key is also not unique and
  1260. there is an infinite number of RSA public exponents which
  1261. can behave in the same manner.
  1262. From any given RSA public exponent `e`, there are can be an
  1263. another RSA public exponent `e + k \lambda(n)` where `k` is an
  1264. integer, `\lambda` is a Carmichael's totient function.
  1265. However, considering only the positive cases, there can be
  1266. a principal solution of a RSA public exponent `e_0` in
  1267. `0 < e_0 < \lambda(n)`, and all the other solutions
  1268. can be canonicalzed in a form of `e_0 + k \lambda(n)`.
  1269. ``index`` specifies the `k` notation to yield any possible value
  1270. an RSA public key can have.
  1271. An example of computing any arbitrary RSA public key:
  1272. >>> from sympy.crypto.crypto import rsa_public_key
  1273. >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=0)
  1274. (3233, 17)
  1275. >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=1)
  1276. (3233, 797)
  1277. >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=2)
  1278. (3233, 1577)
  1279. multipower : bool, optional
  1280. Any pair of non-distinct primes found in the RSA specification
  1281. will restrict the domain of the cryptosystem, as noted in the
  1282. explanation of the parameter ``args``.
  1283. SymPy RSA key generator may give a warning before dispatching it
  1284. as a multi-power RSA, however, you can disable the warning if
  1285. you pass ``True`` to this keyword.
  1286. Returns
  1287. =======
  1288. (n, e) : int, int
  1289. `n` is a product of any arbitrary number of primes given as
  1290. the argument.
  1291. `e` is relatively prime (coprime) to the Euler totient
  1292. `\phi(n)`.
  1293. False
  1294. Returned if less than two arguments are given, or `e` is
  1295. not relatively prime to the modulus.
  1296. Examples
  1297. ========
  1298. >>> from sympy.crypto.crypto import rsa_public_key
  1299. A public key of a two-prime RSA:
  1300. >>> p, q, e = 3, 5, 7
  1301. >>> rsa_public_key(p, q, e)
  1302. (15, 7)
  1303. >>> rsa_public_key(p, q, 30)
  1304. False
  1305. A public key of a multiprime RSA:
  1306. >>> primes = [2, 3, 5, 7, 11, 13]
  1307. >>> e = 7
  1308. >>> args = primes + [e]
  1309. >>> rsa_public_key(*args)
  1310. (30030, 7)
  1311. Notes
  1312. =====
  1313. Although the RSA can be generalized over any modulus `n`, using
  1314. two large primes had became the most popular specification because a
  1315. product of two large primes is usually the hardest to factor
  1316. relatively to the digits of `n` can have.
  1317. However, it may need further understanding of the time complexities
  1318. of each prime-factoring algorithms to verify the claim.
  1319. See Also
  1320. ========
  1321. rsa_private_key
  1322. encipher_rsa
  1323. decipher_rsa
  1324. References
  1325. ==========
  1326. .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
  1327. .. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
  1328. .. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
  1329. .. [4] https://www.itiis.org/digital-library/manuscript/1381
  1330. """
  1331. return _rsa_key(*args, public=True, private=False, **kwargs)
  1332. def rsa_private_key(*args, **kwargs):
  1333. r"""Return the RSA *private key* pair, `(n, d)`
  1334. Parameters
  1335. ==========
  1336. args : naturals
  1337. The keyword is identical to the ``args`` in
  1338. :meth:`rsa_public_key`.
  1339. totient : bool, optional
  1340. If ``'Euler'``, it uses Euler's totient convention `\phi(n)`
  1341. which is :meth:`sympy.functions.combinatorial.numbers.totient` in SymPy.
  1342. If ``'Carmichael'``, it uses Carmichael's totient convention
  1343. `\lambda(n)` which is
  1344. :meth:`sympy.functions.combinatorial.numbers.reduced_totient` in SymPy.
  1345. There can be some output differences for private key generation
  1346. as examples below.
  1347. Example using Euler's totient:
  1348. >>> from sympy.crypto.crypto import rsa_private_key
  1349. >>> rsa_private_key(61, 53, 17, totient='Euler')
  1350. (3233, 2753)
  1351. Example using Carmichael's totient:
  1352. >>> from sympy.crypto.crypto import rsa_private_key
  1353. >>> rsa_private_key(61, 53, 17, totient='Carmichael')
  1354. (3233, 413)
  1355. index : nonnegative integer, optional
  1356. Returns an arbitrary solution of a RSA private key at the index
  1357. specified at `0, 1, 2, \dots`. This parameter needs to be
  1358. specified along with ``totient='Carmichael'``.
  1359. RSA private exponent is a non-unique solution of
  1360. `e d \mod \lambda(n) = 1` and it is possible in any form of
  1361. `d + k \lambda(n)`, where `d` is an another
  1362. already-computed private exponent, and `\lambda` is a
  1363. Carmichael's totient function, and `k` is any integer.
  1364. However, considering only the positive cases, there can be
  1365. a principal solution of a RSA private exponent `d_0` in
  1366. `0 < d_0 < \lambda(n)`, and all the other solutions
  1367. can be canonicalzed in a form of `d_0 + k \lambda(n)`.
  1368. ``index`` specifies the `k` notation to yield any possible value
  1369. an RSA private key can have.
  1370. An example of computing any arbitrary RSA private key:
  1371. >>> from sympy.crypto.crypto import rsa_private_key
  1372. >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=0)
  1373. (3233, 413)
  1374. >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=1)
  1375. (3233, 1193)
  1376. >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=2)
  1377. (3233, 1973)
  1378. multipower : bool, optional
  1379. The keyword is identical to the ``multipower`` in
  1380. :meth:`rsa_public_key`.
  1381. Returns
  1382. =======
  1383. (n, d) : int, int
  1384. `n` is a product of any arbitrary number of primes given as
  1385. the argument.
  1386. `d` is the inverse of `e` (mod `\phi(n)`) where `e` is the
  1387. exponent given, and `\phi` is a Euler totient.
  1388. False
  1389. Returned if less than two arguments are given, or `e` is
  1390. not relatively prime to the totient of the modulus.
  1391. Examples
  1392. ========
  1393. >>> from sympy.crypto.crypto import rsa_private_key
  1394. A private key of a two-prime RSA:
  1395. >>> p, q, e = 3, 5, 7
  1396. >>> rsa_private_key(p, q, e)
  1397. (15, 7)
  1398. >>> rsa_private_key(p, q, 30)
  1399. False
  1400. A private key of a multiprime RSA:
  1401. >>> primes = [2, 3, 5, 7, 11, 13]
  1402. >>> e = 7
  1403. >>> args = primes + [e]
  1404. >>> rsa_private_key(*args)
  1405. (30030, 823)
  1406. See Also
  1407. ========
  1408. rsa_public_key
  1409. encipher_rsa
  1410. decipher_rsa
  1411. References
  1412. ==========
  1413. .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
  1414. .. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
  1415. .. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
  1416. .. [4] https://www.itiis.org/digital-library/manuscript/1381
  1417. """
  1418. return _rsa_key(*args, public=False, private=True, **kwargs)
  1419. def _encipher_decipher_rsa(i, key, factors=None):
  1420. n, d = key
  1421. if not factors:
  1422. return pow(i, d, n)
  1423. def _is_coprime_set(l):
  1424. is_coprime_set = True
  1425. for i in range(len(l)):
  1426. for j in range(i+1, len(l)):
  1427. if gcd(l[i], l[j]) != 1:
  1428. is_coprime_set = False
  1429. break
  1430. return is_coprime_set
  1431. prod = reduce(lambda i, j: i*j, factors)
  1432. if prod == n and _is_coprime_set(factors):
  1433. return _decipher_rsa_crt(i, d, factors)
  1434. return _encipher_decipher_rsa(i, key, factors=None)
  1435. def encipher_rsa(i, key, factors=None):
  1436. r"""Encrypt the plaintext with RSA.
  1437. Parameters
  1438. ==========
  1439. i : integer
  1440. The plaintext to be encrypted for.
  1441. key : (n, e) where n, e are integers
  1442. `n` is the modulus of the key and `e` is the exponent of the
  1443. key. The encryption is computed by `i^e \bmod n`.
  1444. The key can either be a public key or a private key, however,
  1445. the message encrypted by a public key can only be decrypted by
  1446. a private key, and vice versa, as RSA is an asymmetric
  1447. cryptography system.
  1448. factors : list of coprime integers
  1449. This is identical to the keyword ``factors`` in
  1450. :meth:`decipher_rsa`.
  1451. Notes
  1452. =====
  1453. Some specifications may make the RSA not cryptographically
  1454. meaningful.
  1455. For example, `0`, `1` will remain always same after taking any
  1456. number of exponentiation, thus, should be avoided.
  1457. Furthermore, if `i^e < n`, `i` may easily be figured out by taking
  1458. `e` th root.
  1459. And also, specifying the exponent as `1` or in more generalized form
  1460. as `1 + k \lambda(n)` where `k` is an nonnegative integer,
  1461. `\lambda` is a carmichael totient, the RSA becomes an identity
  1462. mapping.
  1463. Examples
  1464. ========
  1465. >>> from sympy.crypto.crypto import encipher_rsa
  1466. >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
  1467. Public Key Encryption:
  1468. >>> p, q, e = 3, 5, 7
  1469. >>> puk = rsa_public_key(p, q, e)
  1470. >>> msg = 12
  1471. >>> encipher_rsa(msg, puk)
  1472. 3
  1473. Private Key Encryption:
  1474. >>> p, q, e = 3, 5, 7
  1475. >>> prk = rsa_private_key(p, q, e)
  1476. >>> msg = 12
  1477. >>> encipher_rsa(msg, prk)
  1478. 3
  1479. Encryption using chinese remainder theorem:
  1480. >>> encipher_rsa(msg, prk, factors=[p, q])
  1481. 3
  1482. """
  1483. return _encipher_decipher_rsa(i, key, factors=factors)
  1484. def decipher_rsa(i, key, factors=None):
  1485. r"""Decrypt the ciphertext with RSA.
  1486. Parameters
  1487. ==========
  1488. i : integer
  1489. The ciphertext to be decrypted for.
  1490. key : (n, d) where n, d are integers
  1491. `n` is the modulus of the key and `d` is the exponent of the
  1492. key. The decryption is computed by `i^d \bmod n`.
  1493. The key can either be a public key or a private key, however,
  1494. the message encrypted by a public key can only be decrypted by
  1495. a private key, and vice versa, as RSA is an asymmetric
  1496. cryptography system.
  1497. factors : list of coprime integers
  1498. As the modulus `n` created from RSA key generation is composed
  1499. of arbitrary prime factors
  1500. `n = {p_1}^{k_1}{p_2}^{k_2}\dots{p_n}^{k_n}` where
  1501. `p_1, p_2, \dots, p_n` are distinct primes and
  1502. `k_1, k_2, \dots, k_n` are positive integers, chinese remainder
  1503. theorem can be used to compute `i^d \bmod n` from the
  1504. fragmented modulo operations like
  1505. .. math::
  1506. i^d \bmod {p_1}^{k_1}, i^d \bmod {p_2}^{k_2}, \dots,
  1507. i^d \bmod {p_n}^{k_n}
  1508. or like
  1509. .. math::
  1510. i^d \bmod {p_1}^{k_1}{p_2}^{k_2},
  1511. i^d \bmod {p_3}^{k_3}, \dots ,
  1512. i^d \bmod {p_n}^{k_n}
  1513. as long as every moduli does not share any common divisor each
  1514. other.
  1515. The raw primes used in generating the RSA key pair can be a good
  1516. option.
  1517. Note that the speed advantage of using this is only viable for
  1518. very large cases (Like 2048-bit RSA keys) since the
  1519. overhead of using pure Python implementation of
  1520. :meth:`sympy.ntheory.modular.crt` may overcompensate the
  1521. theoretical speed advantage.
  1522. Notes
  1523. =====
  1524. See the ``Notes`` section in the documentation of
  1525. :meth:`encipher_rsa`
  1526. Examples
  1527. ========
  1528. >>> from sympy.crypto.crypto import decipher_rsa, encipher_rsa
  1529. >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
  1530. Public Key Encryption and Decryption:
  1531. >>> p, q, e = 3, 5, 7
  1532. >>> prk = rsa_private_key(p, q, e)
  1533. >>> puk = rsa_public_key(p, q, e)
  1534. >>> msg = 12
  1535. >>> new_msg = encipher_rsa(msg, prk)
  1536. >>> new_msg
  1537. 3
  1538. >>> decipher_rsa(new_msg, puk)
  1539. 12
  1540. Private Key Encryption and Decryption:
  1541. >>> p, q, e = 3, 5, 7
  1542. >>> prk = rsa_private_key(p, q, e)
  1543. >>> puk = rsa_public_key(p, q, e)
  1544. >>> msg = 12
  1545. >>> new_msg = encipher_rsa(msg, puk)
  1546. >>> new_msg
  1547. 3
  1548. >>> decipher_rsa(new_msg, prk)
  1549. 12
  1550. Decryption using chinese remainder theorem:
  1551. >>> decipher_rsa(new_msg, prk, factors=[p, q])
  1552. 12
  1553. See Also
  1554. ========
  1555. encipher_rsa
  1556. """
  1557. return _encipher_decipher_rsa(i, key, factors=factors)
  1558. #################### kid krypto (kid RSA) #############################
  1559. def kid_rsa_public_key(a, b, A, B):
  1560. r"""
  1561. Kid RSA is a version of RSA useful to teach grade school children
  1562. since it does not involve exponentiation.
  1563. Explanation
  1564. ===========
  1565. Alice wants to talk to Bob. Bob generates keys as follows.
  1566. Key generation:
  1567. * Select positive integers `a, b, A, B` at random.
  1568. * Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
  1569. `n = (e d - 1)//M`.
  1570. * The *public key* is `(n, e)`. Bob sends these to Alice.
  1571. * The *private key* is `(n, d)`, which Bob keeps secret.
  1572. Encryption: If `p` is the plaintext message then the
  1573. ciphertext is `c = p e \pmod n`.
  1574. Decryption: If `c` is the ciphertext message then the
  1575. plaintext is `p = c d \pmod n`.
  1576. Examples
  1577. ========
  1578. >>> from sympy.crypto.crypto import kid_rsa_public_key
  1579. >>> a, b, A, B = 3, 4, 5, 6
  1580. >>> kid_rsa_public_key(a, b, A, B)
  1581. (369, 58)
  1582. """
  1583. M = a*b - 1
  1584. e = A*M + a
  1585. d = B*M + b
  1586. n = (e*d - 1)//M
  1587. return n, e
  1588. def kid_rsa_private_key(a, b, A, B):
  1589. """
  1590. Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
  1591. `n = (e d - 1) / M`. The *private key* is `d`, which Bob
  1592. keeps secret.
  1593. Examples
  1594. ========
  1595. >>> from sympy.crypto.crypto import kid_rsa_private_key
  1596. >>> a, b, A, B = 3, 4, 5, 6
  1597. >>> kid_rsa_private_key(a, b, A, B)
  1598. (369, 70)
  1599. """
  1600. M = a*b - 1
  1601. e = A*M + a
  1602. d = B*M + b
  1603. n = (e*d - 1)//M
  1604. return n, d
  1605. def encipher_kid_rsa(msg, key):
  1606. """
  1607. Here ``msg`` is the plaintext and ``key`` is the public key.
  1608. Examples
  1609. ========
  1610. >>> from sympy.crypto.crypto import (
  1611. ... encipher_kid_rsa, kid_rsa_public_key)
  1612. >>> msg = 200
  1613. >>> a, b, A, B = 3, 4, 5, 6
  1614. >>> key = kid_rsa_public_key(a, b, A, B)
  1615. >>> encipher_kid_rsa(msg, key)
  1616. 161
  1617. """
  1618. n, e = key
  1619. return (msg*e) % n
  1620. def decipher_kid_rsa(msg, key):
  1621. """
  1622. Here ``msg`` is the plaintext and ``key`` is the private key.
  1623. Examples
  1624. ========
  1625. >>> from sympy.crypto.crypto import (
  1626. ... kid_rsa_public_key, kid_rsa_private_key,
  1627. ... decipher_kid_rsa, encipher_kid_rsa)
  1628. >>> a, b, A, B = 3, 4, 5, 6
  1629. >>> d = kid_rsa_private_key(a, b, A, B)
  1630. >>> msg = 200
  1631. >>> pub = kid_rsa_public_key(a, b, A, B)
  1632. >>> pri = kid_rsa_private_key(a, b, A, B)
  1633. >>> ct = encipher_kid_rsa(msg, pub)
  1634. >>> decipher_kid_rsa(ct, pri)
  1635. 200
  1636. """
  1637. n, d = key
  1638. return (msg*d) % n
  1639. #################### Morse Code ######################################
  1640. morse_char = {
  1641. ".-": "A", "-...": "B",
  1642. "-.-.": "C", "-..": "D",
  1643. ".": "E", "..-.": "F",
  1644. "--.": "G", "....": "H",
  1645. "..": "I", ".---": "J",
  1646. "-.-": "K", ".-..": "L",
  1647. "--": "M", "-.": "N",
  1648. "---": "O", ".--.": "P",
  1649. "--.-": "Q", ".-.": "R",
  1650. "...": "S", "-": "T",
  1651. "..-": "U", "...-": "V",
  1652. ".--": "W", "-..-": "X",
  1653. "-.--": "Y", "--..": "Z",
  1654. "-----": "0", ".----": "1",
  1655. "..---": "2", "...--": "3",
  1656. "....-": "4", ".....": "5",
  1657. "-....": "6", "--...": "7",
  1658. "---..": "8", "----.": "9",
  1659. ".-.-.-": ".", "--..--": ",",
  1660. "---...": ":", "-.-.-.": ";",
  1661. "..--..": "?", "-....-": "-",
  1662. "..--.-": "_", "-.--.": "(",
  1663. "-.--.-": ")", ".----.": "'",
  1664. "-...-": "=", ".-.-.": "+",
  1665. "-..-.": "/", ".--.-.": "@",
  1666. "...-..-": "$", "-.-.--": "!"}
  1667. char_morse = {v: k for k, v in morse_char.items()}
  1668. def encode_morse(msg, sep='|', mapping=None):
  1669. """
  1670. Encodes a plaintext into popular Morse Code with letters
  1671. separated by ``sep`` and words by a double ``sep``.
  1672. Examples
  1673. ========
  1674. >>> from sympy.crypto.crypto import encode_morse
  1675. >>> msg = 'ATTACK RIGHT FLANK'
  1676. >>> encode_morse(msg)
  1677. '.-|-|-|.-|-.-.|-.-||.-.|..|--.|....|-||..-.|.-..|.-|-.|-.-'
  1678. References
  1679. ==========
  1680. .. [1] https://en.wikipedia.org/wiki/Morse_code
  1681. """
  1682. mapping = mapping or char_morse
  1683. assert sep not in mapping
  1684. word_sep = 2*sep
  1685. mapping[" "] = word_sep
  1686. suffix = msg and msg[-1] in whitespace
  1687. # normalize whitespace
  1688. msg = (' ' if word_sep else '').join(msg.split())
  1689. # omit unmapped chars
  1690. chars = set(''.join(msg.split()))
  1691. ok = set(mapping.keys())
  1692. msg = translate(msg, None, ''.join(chars - ok))
  1693. morsestring = []
  1694. words = msg.split()
  1695. for word in words:
  1696. morseword = []
  1697. for letter in word:
  1698. morseletter = mapping[letter]
  1699. morseword.append(morseletter)
  1700. word = sep.join(morseword)
  1701. morsestring.append(word)
  1702. return word_sep.join(morsestring) + (word_sep if suffix else '')
  1703. def decode_morse(msg, sep='|', mapping=None):
  1704. """
  1705. Decodes a Morse Code with letters separated by ``sep``
  1706. (default is '|') and words by `word_sep` (default is '||)
  1707. into plaintext.
  1708. Examples
  1709. ========
  1710. >>> from sympy.crypto.crypto import decode_morse
  1711. >>> mc = '--|---|...-|.||.|.-|...|-'
  1712. >>> decode_morse(mc)
  1713. 'MOVE EAST'
  1714. References
  1715. ==========
  1716. .. [1] https://en.wikipedia.org/wiki/Morse_code
  1717. """
  1718. mapping = mapping or morse_char
  1719. word_sep = 2*sep
  1720. characterstring = []
  1721. words = msg.strip(word_sep).split(word_sep)
  1722. for word in words:
  1723. letters = word.split(sep)
  1724. chars = [mapping[c] for c in letters]
  1725. word = ''.join(chars)
  1726. characterstring.append(word)
  1727. rv = " ".join(characterstring)
  1728. return rv
  1729. #################### LFSRs ##########################################
  1730. @doctest_depends_on(ground_types=['python', 'gmpy'])
  1731. def lfsr_sequence(key, fill, n):
  1732. r"""
  1733. This function creates an LFSR sequence.
  1734. Parameters
  1735. ==========
  1736. key : list
  1737. A list of finite field elements, `[c_0, c_1, \ldots, c_k].`
  1738. fill : list
  1739. The list of the initial terms of the LFSR sequence,
  1740. `[x_0, x_1, \ldots, x_k].`
  1741. n
  1742. Number of terms of the sequence that the function returns.
  1743. Returns
  1744. =======
  1745. L
  1746. The LFSR sequence defined by
  1747. `x_{n+1} = c_k x_n + \ldots + c_0 x_{n-k}`, for
  1748. `n \leq k`.
  1749. Notes
  1750. =====
  1751. S. Golomb [G]_ gives a list of three statistical properties a
  1752. sequence of numbers `a = \{a_n\}_{n=1}^\infty`,
  1753. `a_n \in \{0,1\}`, should display to be considered
  1754. "random". Define the autocorrelation of `a` to be
  1755. .. math::
  1756. C(k) = C(k,a) = \lim_{N\rightarrow \infty} {1\over N}\sum_{n=1}^N (-1)^{a_n + a_{n+k}}.
  1757. In the case where `a` is periodic with period
  1758. `P` then this reduces to
  1759. .. math::
  1760. C(k) = {1\over P}\sum_{n=1}^P (-1)^{a_n + a_{n+k}}.
  1761. Assume `a` is periodic with period `P`.
  1762. - balance:
  1763. .. math::
  1764. \left|\sum_{n=1}^P(-1)^{a_n}\right| \leq 1.
  1765. - low autocorrelation:
  1766. .. math::
  1767. C(k) = \left\{ \begin{array}{cc} 1,& k = 0,\\ \epsilon, & k \ne 0. \end{array} \right.
  1768. (For sequences satisfying these first two properties, it is known
  1769. that `\epsilon = -1/P` must hold.)
  1770. - proportional runs property: In each period, half the runs have
  1771. length `1`, one-fourth have length `2`, etc.
  1772. Moreover, there are as many runs of `1`'s as there are of
  1773. `0`'s.
  1774. Examples
  1775. ========
  1776. >>> from sympy.crypto.crypto import lfsr_sequence
  1777. >>> from sympy.polys.domains import FF
  1778. >>> F = FF(2)
  1779. >>> fill = [F(1), F(1), F(0), F(1)]
  1780. >>> key = [F(1), F(0), F(0), F(1)]
  1781. >>> lfsr_sequence(key, fill, 10)
  1782. [1 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 0 mod 2,
  1783. 1 mod 2, 1 mod 2, 0 mod 2, 0 mod 2, 1 mod 2]
  1784. References
  1785. ==========
  1786. .. [G] Solomon Golomb, Shift register sequences, Aegean Park Press,
  1787. Laguna Hills, Ca, 1967
  1788. """
  1789. if not isinstance(key, list):
  1790. raise TypeError("key must be a list")
  1791. if not isinstance(fill, list):
  1792. raise TypeError("fill must be a list")
  1793. p = key[0].modulus()
  1794. F = FF(p)
  1795. s = fill
  1796. k = len(fill)
  1797. L = []
  1798. for i in range(n):
  1799. s0 = s[:]
  1800. L.append(s[0])
  1801. s = s[1:k]
  1802. x = sum(int(key[i]*s0[i]) for i in range(k))
  1803. s.append(F(x))
  1804. return L # use [int(x) for x in L] for int version
  1805. def lfsr_autocorrelation(L, P, k):
  1806. """
  1807. This function computes the LFSR autocorrelation function.
  1808. Parameters
  1809. ==========
  1810. L
  1811. A periodic sequence of elements of `GF(2)`.
  1812. L must have length larger than P.
  1813. P
  1814. The period of L.
  1815. k : int
  1816. An integer `k` (`0 < k < P`).
  1817. Returns
  1818. =======
  1819. autocorrelation
  1820. The k-th value of the autocorrelation of the LFSR L.
  1821. Examples
  1822. ========
  1823. >>> from sympy.crypto.crypto import (
  1824. ... lfsr_sequence, lfsr_autocorrelation)
  1825. >>> from sympy.polys.domains import FF
  1826. >>> F = FF(2)
  1827. >>> fill = [F(1), F(1), F(0), F(1)]
  1828. >>> key = [F(1), F(0), F(0), F(1)]
  1829. >>> s = lfsr_sequence(key, fill, 20)
  1830. >>> lfsr_autocorrelation(s, 15, 7)
  1831. -1/15
  1832. >>> lfsr_autocorrelation(s, 15, 0)
  1833. 1
  1834. """
  1835. if not isinstance(L, list):
  1836. raise TypeError("L (=%s) must be a list" % L)
  1837. P = int(P)
  1838. k = int(k)
  1839. L0 = L[:P] # slices makes a copy
  1840. L1 = L0 + L0[:k]
  1841. L2 = [(-1)**(int(L1[i]) + int(L1[i + k])) for i in range(P)]
  1842. tot = sum(L2)
  1843. return Rational(tot, P)
  1844. def lfsr_connection_polynomial(s):
  1845. """
  1846. This function computes the LFSR connection polynomial.
  1847. Parameters
  1848. ==========
  1849. s
  1850. A sequence of elements of even length, with entries in a finite
  1851. field.
  1852. Returns
  1853. =======
  1854. C(x)
  1855. The connection polynomial of a minimal LFSR yielding s.
  1856. This implements the algorithm in section 3 of J. L. Massey's
  1857. article [M]_.
  1858. Examples
  1859. ========
  1860. >>> from sympy.crypto.crypto import (
  1861. ... lfsr_sequence, lfsr_connection_polynomial)
  1862. >>> from sympy.polys.domains import FF
  1863. >>> F = FF(2)
  1864. >>> fill = [F(1), F(1), F(0), F(1)]
  1865. >>> key = [F(1), F(0), F(0), F(1)]
  1866. >>> s = lfsr_sequence(key, fill, 20)
  1867. >>> lfsr_connection_polynomial(s)
  1868. x**4 + x + 1
  1869. >>> fill = [F(1), F(0), F(0), F(1)]
  1870. >>> key = [F(1), F(1), F(0), F(1)]
  1871. >>> s = lfsr_sequence(key, fill, 20)
  1872. >>> lfsr_connection_polynomial(s)
  1873. x**3 + 1
  1874. >>> fill = [F(1), F(0), F(1)]
  1875. >>> key = [F(1), F(1), F(0)]
  1876. >>> s = lfsr_sequence(key, fill, 20)
  1877. >>> lfsr_connection_polynomial(s)
  1878. x**3 + x**2 + 1
  1879. >>> fill = [F(1), F(0), F(1)]
  1880. >>> key = [F(1), F(0), F(1)]
  1881. >>> s = lfsr_sequence(key, fill, 20)
  1882. >>> lfsr_connection_polynomial(s)
  1883. x**3 + x + 1
  1884. References
  1885. ==========
  1886. .. [M] James L. Massey, "Shift-Register Synthesis and BCH Decoding."
  1887. IEEE Trans. on Information Theory, vol. 15(1), pp. 122-127,
  1888. Jan 1969.
  1889. """
  1890. # Initialization:
  1891. p = s[0].modulus()
  1892. x = Symbol("x")
  1893. C = 1*x**0
  1894. B = 1*x**0
  1895. m = 1
  1896. b = 1*x**0
  1897. L = 0
  1898. N = 0
  1899. while N < len(s):
  1900. if L > 0:
  1901. dC = Poly(C).degree()
  1902. r = min(L + 1, dC + 1)
  1903. coeffsC = [C.subs(x, 0)] + [C.coeff(x**i)
  1904. for i in range(1, dC + 1)]
  1905. d = (int(s[N]) + sum(coeffsC[i]*int(s[N - i])
  1906. for i in range(1, r))) % p
  1907. if L == 0:
  1908. d = int(s[N])*x**0
  1909. if d == 0:
  1910. m += 1
  1911. N += 1
  1912. if d > 0:
  1913. if 2*L > N:
  1914. C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
  1915. m += 1
  1916. N += 1
  1917. else:
  1918. T = C
  1919. C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
  1920. L = N + 1 - L
  1921. m = 1
  1922. b = d
  1923. B = T
  1924. N += 1
  1925. dC = Poly(C).degree()
  1926. coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)]
  1927. return sum(coeffsC[i] % p*x**i for i in range(dC + 1)
  1928. if coeffsC[i] is not None)
  1929. #################### ElGamal #############################
  1930. def elgamal_private_key(digit=10, seed=None):
  1931. r"""
  1932. Return three number tuple as private key.
  1933. Explanation
  1934. ===========
  1935. Elgamal encryption is based on the mathematical problem
  1936. called the Discrete Logarithm Problem (DLP). For example,
  1937. `a^{b} \equiv c \pmod p`
  1938. In general, if ``a`` and ``b`` are known, ``ct`` is easily
  1939. calculated. If ``b`` is unknown, it is hard to use
  1940. ``a`` and ``ct`` to get ``b``.
  1941. Parameters
  1942. ==========
  1943. digit : int
  1944. Minimum number of binary digits for key.
  1945. Returns
  1946. =======
  1947. tuple : (p, r, d)
  1948. p = prime number.
  1949. r = primitive root.
  1950. d = random number.
  1951. Notes
  1952. =====
  1953. For testing purposes, the ``seed`` parameter may be set to control
  1954. the output of this routine. See sympy.core.random._randrange.
  1955. Examples
  1956. ========
  1957. >>> from sympy.crypto.crypto import elgamal_private_key
  1958. >>> from sympy.ntheory import is_primitive_root, isprime
  1959. >>> a, b, _ = elgamal_private_key()
  1960. >>> isprime(a)
  1961. True
  1962. >>> is_primitive_root(b, a)
  1963. True
  1964. """
  1965. randrange = _randrange(seed)
  1966. p = nextprime(2**digit)
  1967. return p, primitive_root(p), randrange(2, p)
  1968. def elgamal_public_key(key):
  1969. r"""
  1970. Return three number tuple as public key.
  1971. Parameters
  1972. ==========
  1973. key : (p, r, e)
  1974. Tuple generated by ``elgamal_private_key``.
  1975. Returns
  1976. =======
  1977. tuple : (p, r, e)
  1978. `e = r**d \bmod p`
  1979. `d` is a random number in private key.
  1980. Examples
  1981. ========
  1982. >>> from sympy.crypto.crypto import elgamal_public_key
  1983. >>> elgamal_public_key((1031, 14, 636))
  1984. (1031, 14, 212)
  1985. """
  1986. p, r, e = key
  1987. return p, r, pow(r, e, p)
  1988. def encipher_elgamal(i, key, seed=None):
  1989. r"""
  1990. Encrypt message with public key.
  1991. Explanation
  1992. ===========
  1993. ``i`` is a plaintext message expressed as an integer.
  1994. ``key`` is public key (p, r, e). In order to encrypt
  1995. a message, a random number ``a`` in ``range(2, p)``
  1996. is generated and the encrypted message is returned as
  1997. `c_{1}` and `c_{2}` where:
  1998. `c_{1} \equiv r^{a} \pmod p`
  1999. `c_{2} \equiv m e^{a} \pmod p`
  2000. Parameters
  2001. ==========
  2002. msg
  2003. int of encoded message.
  2004. key
  2005. Public key.
  2006. Returns
  2007. =======
  2008. tuple : (c1, c2)
  2009. Encipher into two number.
  2010. Notes
  2011. =====
  2012. For testing purposes, the ``seed`` parameter may be set to control
  2013. the output of this routine. See sympy.core.random._randrange.
  2014. Examples
  2015. ========
  2016. >>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key
  2017. >>> pri = elgamal_private_key(5, seed=[3]); pri
  2018. (37, 2, 3)
  2019. >>> pub = elgamal_public_key(pri); pub
  2020. (37, 2, 8)
  2021. >>> msg = 36
  2022. >>> encipher_elgamal(msg, pub, seed=[3])
  2023. (8, 6)
  2024. """
  2025. p, r, e = key
  2026. if i < 0 or i >= p:
  2027. raise ValueError(
  2028. 'Message (%s) should be in range(%s)' % (i, p))
  2029. randrange = _randrange(seed)
  2030. a = randrange(2, p)
  2031. return pow(r, a, p), i*pow(e, a, p) % p
  2032. def decipher_elgamal(msg, key):
  2033. r"""
  2034. Decrypt message with private key.
  2035. `msg = (c_{1}, c_{2})`
  2036. `key = (p, r, d)`
  2037. According to extended Eucliden theorem,
  2038. `u c_{1}^{d} + p n = 1`
  2039. `u \equiv 1/{{c_{1}}^d} \pmod p`
  2040. `u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p`
  2041. `\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p`
  2042. Examples
  2043. ========
  2044. >>> from sympy.crypto.crypto import decipher_elgamal
  2045. >>> from sympy.crypto.crypto import encipher_elgamal
  2046. >>> from sympy.crypto.crypto import elgamal_private_key
  2047. >>> from sympy.crypto.crypto import elgamal_public_key
  2048. >>> pri = elgamal_private_key(5, seed=[3])
  2049. >>> pub = elgamal_public_key(pri); pub
  2050. (37, 2, 8)
  2051. >>> msg = 17
  2052. >>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg
  2053. True
  2054. """
  2055. p, _, d = key
  2056. c1, c2 = msg
  2057. u = pow(c1, -d, p)
  2058. return u * c2 % p
  2059. ################ Diffie-Hellman Key Exchange #########################
  2060. def dh_private_key(digit=10, seed=None):
  2061. r"""
  2062. Return three integer tuple as private key.
  2063. Explanation
  2064. ===========
  2065. Diffie-Hellman key exchange is based on the mathematical problem
  2066. called the Discrete Logarithm Problem (see ElGamal).
  2067. Diffie-Hellman key exchange is divided into the following steps:
  2068. * Alice and Bob agree on a base that consist of a prime ``p``
  2069. and a primitive root of ``p`` called ``g``
  2070. * Alice choses a number ``a`` and Bob choses a number ``b`` where
  2071. ``a`` and ``b`` are random numbers in range `[2, p)`. These are
  2072. their private keys.
  2073. * Alice then publicly sends Bob `g^{a} \pmod p` while Bob sends
  2074. Alice `g^{b} \pmod p`
  2075. * They both raise the received value to their secretly chosen
  2076. number (``a`` or ``b``) and now have both as their shared key
  2077. `g^{ab} \pmod p`
  2078. Parameters
  2079. ==========
  2080. digit
  2081. Minimum number of binary digits required in key.
  2082. Returns
  2083. =======
  2084. tuple : (p, g, a)
  2085. p = prime number.
  2086. g = primitive root of p.
  2087. a = random number from 2 through p - 1.
  2088. Notes
  2089. =====
  2090. For testing purposes, the ``seed`` parameter may be set to control
  2091. the output of this routine. See sympy.core.random._randrange.
  2092. Examples
  2093. ========
  2094. >>> from sympy.crypto.crypto import dh_private_key
  2095. >>> from sympy.ntheory import isprime, is_primitive_root
  2096. >>> p, g, _ = dh_private_key()
  2097. >>> isprime(p)
  2098. True
  2099. >>> is_primitive_root(g, p)
  2100. True
  2101. >>> p, g, _ = dh_private_key(5)
  2102. >>> isprime(p)
  2103. True
  2104. >>> is_primitive_root(g, p)
  2105. True
  2106. """
  2107. p = nextprime(2**digit)
  2108. g = primitive_root(p)
  2109. randrange = _randrange(seed)
  2110. a = randrange(2, p)
  2111. return p, g, a
  2112. def dh_public_key(key):
  2113. r"""
  2114. Return three number tuple as public key.
  2115. This is the tuple that Alice sends to Bob.
  2116. Parameters
  2117. ==========
  2118. key : (p, g, a)
  2119. A tuple generated by ``dh_private_key``.
  2120. Returns
  2121. =======
  2122. tuple : int, int, int
  2123. A tuple of `(p, g, g^a \mod p)` with `p`, `g` and `a` given as
  2124. parameters.s
  2125. Examples
  2126. ========
  2127. >>> from sympy.crypto.crypto import dh_private_key, dh_public_key
  2128. >>> p, g, a = dh_private_key();
  2129. >>> _p, _g, x = dh_public_key((p, g, a))
  2130. >>> p == _p and g == _g
  2131. True
  2132. >>> x == pow(g, a, p)
  2133. True
  2134. """
  2135. p, g, a = key
  2136. return p, g, pow(g, a, p)
  2137. def dh_shared_key(key, b):
  2138. """
  2139. Return an integer that is the shared key.
  2140. This is what Bob and Alice can both calculate using the public
  2141. keys they received from each other and their private keys.
  2142. Parameters
  2143. ==========
  2144. key : (p, g, x)
  2145. Tuple `(p, g, x)` generated by ``dh_public_key``.
  2146. b
  2147. Random number in the range of `2` to `p - 1`
  2148. (Chosen by second key exchange member (Bob)).
  2149. Returns
  2150. =======
  2151. int
  2152. A shared key.
  2153. Examples
  2154. ========
  2155. >>> from sympy.crypto.crypto import (
  2156. ... dh_private_key, dh_public_key, dh_shared_key)
  2157. >>> prk = dh_private_key();
  2158. >>> p, g, x = dh_public_key(prk);
  2159. >>> sk = dh_shared_key((p, g, x), 1000)
  2160. >>> sk == pow(x, 1000, p)
  2161. True
  2162. """
  2163. p, _, x = key
  2164. if 1 >= b or b >= p:
  2165. raise ValueError(filldedent('''
  2166. Value of b should be greater 1 and less
  2167. than prime %s.''' % p))
  2168. return pow(x, b, p)
  2169. ################ Goldwasser-Micali Encryption #########################
  2170. def _legendre(a, p):
  2171. """
  2172. Returns the legendre symbol of a and p
  2173. assuming that p is a prime.
  2174. i.e. 1 if a is a quadratic residue mod p
  2175. -1 if a is not a quadratic residue mod p
  2176. 0 if a is divisible by p
  2177. Parameters
  2178. ==========
  2179. a : int
  2180. The number to test.
  2181. p : prime
  2182. The prime to test ``a`` against.
  2183. Returns
  2184. =======
  2185. int
  2186. Legendre symbol (a / p).
  2187. """
  2188. sig = pow(a, (p - 1)//2, p)
  2189. if sig == 1:
  2190. return 1
  2191. elif sig == 0:
  2192. return 0
  2193. else:
  2194. return -1
  2195. def _random_coprime_stream(n, seed=None):
  2196. randrange = _randrange(seed)
  2197. while True:
  2198. y = randrange(n)
  2199. if gcd(y, n) == 1:
  2200. yield y
  2201. def gm_private_key(p, q, a=None):
  2202. r"""
  2203. Check if ``p`` and ``q`` can be used as private keys for
  2204. the Goldwasser-Micali encryption. The method works
  2205. roughly as follows.
  2206. Explanation
  2207. ===========
  2208. #. Pick two large primes $p$ and $q$.
  2209. #. Call their product $N$.
  2210. #. Given a message as an integer $i$, write $i$ in its bit representation $b_0, \dots, b_n$.
  2211. #. For each $k$,
  2212. if $b_k = 0$:
  2213. let $a_k$ be a random square
  2214. (quadratic residue) modulo $p q$
  2215. such that ``jacobi_symbol(a, p*q) = 1``
  2216. if $b_k = 1$:
  2217. let $a_k$ be a random non-square
  2218. (non-quadratic residue) modulo $p q$
  2219. such that ``jacobi_symbol(a, p*q) = 1``
  2220. returns $\left[a_1, a_2, \dots\right]$
  2221. $b_k$ can be recovered by checking whether or not
  2222. $a_k$ is a residue. And from the $b_k$'s, the message
  2223. can be reconstructed.
  2224. The idea is that, while ``jacobi_symbol(a, p*q)``
  2225. can be easily computed (and when it is equal to $-1$ will
  2226. tell you that $a$ is not a square mod $p q$), quadratic
  2227. residuosity modulo a composite number is hard to compute
  2228. without knowing its factorization.
  2229. Moreover, approximately half the numbers coprime to $p q$ have
  2230. :func:`~.jacobi_symbol` equal to $1$ . And among those, approximately half
  2231. are residues and approximately half are not. This maximizes the
  2232. entropy of the code.
  2233. Parameters
  2234. ==========
  2235. p, q, a
  2236. Initialization variables.
  2237. Returns
  2238. =======
  2239. tuple : (p, q)
  2240. The input value ``p`` and ``q``.
  2241. Raises
  2242. ======
  2243. ValueError
  2244. If ``p`` and ``q`` are not distinct odd primes.
  2245. """
  2246. if p == q:
  2247. raise ValueError("expected distinct primes, "
  2248. "got two copies of %i" % p)
  2249. elif not isprime(p) or not isprime(q):
  2250. raise ValueError("first two arguments must be prime, "
  2251. "got %i of %i" % (p, q))
  2252. elif p == 2 or q == 2:
  2253. raise ValueError("first two arguments must not be even, "
  2254. "got %i of %i" % (p, q))
  2255. return p, q
  2256. def gm_public_key(p, q, a=None, seed=None):
  2257. """
  2258. Compute public keys for ``p`` and ``q``.
  2259. Note that in Goldwasser-Micali Encryption,
  2260. public keys are randomly selected.
  2261. Parameters
  2262. ==========
  2263. p, q, a : int, int, int
  2264. Initialization variables.
  2265. Returns
  2266. =======
  2267. tuple : (a, N)
  2268. ``a`` is the input ``a`` if it is not ``None`` otherwise
  2269. some random integer coprime to ``p`` and ``q``.
  2270. ``N`` is the product of ``p`` and ``q``.
  2271. """
  2272. p, q = gm_private_key(p, q)
  2273. N = p * q
  2274. if a is None:
  2275. randrange = _randrange(seed)
  2276. while True:
  2277. a = randrange(N)
  2278. if _legendre(a, p) == _legendre(a, q) == -1:
  2279. break
  2280. else:
  2281. if _legendre(a, p) != -1 or _legendre(a, q) != -1:
  2282. return False
  2283. return (a, N)
  2284. def encipher_gm(i, key, seed=None):
  2285. """
  2286. Encrypt integer 'i' using public_key 'key'
  2287. Note that gm uses random encryption.
  2288. Parameters
  2289. ==========
  2290. i : int
  2291. The message to encrypt.
  2292. key : (a, N)
  2293. The public key.
  2294. Returns
  2295. =======
  2296. list : list of int
  2297. The randomized encrypted message.
  2298. """
  2299. if i < 0:
  2300. raise ValueError(
  2301. "message must be a non-negative "
  2302. "integer: got %d instead" % i)
  2303. a, N = key
  2304. bits = []
  2305. while i > 0:
  2306. bits.append(i % 2)
  2307. i //= 2
  2308. gen = _random_coprime_stream(N, seed)
  2309. rev = reversed(bits)
  2310. encode = lambda b: next(gen)**2*pow(a, b) % N
  2311. return [ encode(b) for b in rev ]
  2312. def decipher_gm(message, key):
  2313. """
  2314. Decrypt message 'message' using public_key 'key'.
  2315. Parameters
  2316. ==========
  2317. message : list of int
  2318. The randomized encrypted message.
  2319. key : (p, q)
  2320. The private key.
  2321. Returns
  2322. =======
  2323. int
  2324. The encrypted message.
  2325. """
  2326. p, q = key
  2327. res = lambda m, p: _legendre(m, p) > 0
  2328. bits = [res(m, p) * res(m, q) for m in message]
  2329. m = 0
  2330. for b in bits:
  2331. m <<= 1
  2332. m += not b
  2333. return m
  2334. ########### RailFence Cipher #############
  2335. def encipher_railfence(message,rails):
  2336. """
  2337. Performs Railfence Encryption on plaintext and returns ciphertext
  2338. Examples
  2339. ========
  2340. >>> from sympy.crypto.crypto import encipher_railfence
  2341. >>> message = "hello world"
  2342. >>> encipher_railfence(message,3)
  2343. 'horel ollwd'
  2344. Parameters
  2345. ==========
  2346. message : string, the message to encrypt.
  2347. rails : int, the number of rails.
  2348. Returns
  2349. =======
  2350. The Encrypted string message.
  2351. References
  2352. ==========
  2353. .. [1] https://en.wikipedia.org/wiki/Rail_fence_cipher
  2354. """
  2355. r = list(range(rails))
  2356. p = cycle(r + r[-2:0:-1])
  2357. return ''.join(sorted(message, key=lambda i: next(p)))
  2358. def decipher_railfence(ciphertext,rails):
  2359. """
  2360. Decrypt the message using the given rails
  2361. Examples
  2362. ========
  2363. >>> from sympy.crypto.crypto import decipher_railfence
  2364. >>> decipher_railfence("horel ollwd",3)
  2365. 'hello world'
  2366. Parameters
  2367. ==========
  2368. message : string, the message to encrypt.
  2369. rails : int, the number of rails.
  2370. Returns
  2371. =======
  2372. The Decrypted string message.
  2373. """
  2374. r = list(range(rails))
  2375. p = cycle(r + r[-2:0:-1])
  2376. idx = sorted(range(len(ciphertext)), key=lambda i: next(p))
  2377. res = [''] * len(ciphertext)
  2378. for i, c in zip(idx, ciphertext):
  2379. res[i] = c
  2380. return ''.join(res)
  2381. ################ Blum-Goldwasser cryptosystem #########################
  2382. def bg_private_key(p, q):
  2383. """
  2384. Check if p and q can be used as private keys for
  2385. the Blum-Goldwasser cryptosystem.
  2386. Explanation
  2387. ===========
  2388. The three necessary checks for p and q to pass
  2389. so that they can be used as private keys:
  2390. 1. p and q must both be prime
  2391. 2. p and q must be distinct
  2392. 3. p and q must be congruent to 3 mod 4
  2393. Parameters
  2394. ==========
  2395. p, q
  2396. The keys to be checked.
  2397. Returns
  2398. =======
  2399. p, q
  2400. Input values.
  2401. Raises
  2402. ======
  2403. ValueError
  2404. If p and q do not pass the above conditions.
  2405. """
  2406. if not isprime(p) or not isprime(q):
  2407. raise ValueError("the two arguments must be prime, "
  2408. "got %i and %i" %(p, q))
  2409. elif p == q:
  2410. raise ValueError("the two arguments must be distinct, "
  2411. "got two copies of %i. " %p)
  2412. elif (p - 3) % 4 != 0 or (q - 3) % 4 != 0:
  2413. raise ValueError("the two arguments must be congruent to 3 mod 4, "
  2414. "got %i and %i" %(p, q))
  2415. return p, q
  2416. def bg_public_key(p, q):
  2417. """
  2418. Calculates public keys from private keys.
  2419. Explanation
  2420. ===========
  2421. The function first checks the validity of
  2422. private keys passed as arguments and
  2423. then returns their product.
  2424. Parameters
  2425. ==========
  2426. p, q
  2427. The private keys.
  2428. Returns
  2429. =======
  2430. N
  2431. The public key.
  2432. """
  2433. p, q = bg_private_key(p, q)
  2434. N = p * q
  2435. return N
  2436. def encipher_bg(i, key, seed=None):
  2437. """
  2438. Encrypts the message using public key and seed.
  2439. Explanation
  2440. ===========
  2441. ALGORITHM:
  2442. 1. Encodes i as a string of L bits, m.
  2443. 2. Select a random element r, where 1 < r < key, and computes
  2444. x = r^2 mod key.
  2445. 3. Use BBS pseudo-random number generator to generate L random bits, b,
  2446. using the initial seed as x.
  2447. 4. Encrypted message, c_i = m_i XOR b_i, 1 <= i <= L.
  2448. 5. x_L = x^(2^L) mod key.
  2449. 6. Return (c, x_L)
  2450. Parameters
  2451. ==========
  2452. i
  2453. Message, a non-negative integer
  2454. key
  2455. The public key
  2456. Returns
  2457. =======
  2458. Tuple
  2459. (encrypted_message, x_L)
  2460. Raises
  2461. ======
  2462. ValueError
  2463. If i is negative.
  2464. """
  2465. if i < 0:
  2466. raise ValueError(
  2467. "message must be a non-negative "
  2468. "integer: got %d instead" % i)
  2469. enc_msg = []
  2470. while i > 0:
  2471. enc_msg.append(i % 2)
  2472. i //= 2
  2473. enc_msg.reverse()
  2474. L = len(enc_msg)
  2475. r = _randint(seed)(2, key - 1)
  2476. x = r**2 % key
  2477. x_L = pow(int(x), int(2**L), int(key))
  2478. rand_bits = []
  2479. for _ in range(L):
  2480. rand_bits.append(x % 2)
  2481. x = x**2 % key
  2482. encrypt_msg = [m ^ b for (m, b) in zip(enc_msg, rand_bits)]
  2483. return (encrypt_msg, x_L)
  2484. def decipher_bg(message, key):
  2485. """
  2486. Decrypts the message using private keys.
  2487. Explanation
  2488. ===========
  2489. ALGORITHM:
  2490. 1. Let, c be the encrypted message, y the second number received,
  2491. and p and q be the private keys.
  2492. 2. Compute, r_p = y^((p+1)/4 ^ L) mod p and
  2493. r_q = y^((q+1)/4 ^ L) mod q.
  2494. 3. Compute x_0 = (q(q^-1 mod p)r_p + p(p^-1 mod q)r_q) mod N.
  2495. 4. From, recompute the bits using the BBS generator, as in the
  2496. encryption algorithm.
  2497. 5. Compute original message by XORing c and b.
  2498. Parameters
  2499. ==========
  2500. message
  2501. Tuple of encrypted message and a non-negative integer.
  2502. key
  2503. Tuple of private keys.
  2504. Returns
  2505. =======
  2506. orig_msg
  2507. The original message
  2508. """
  2509. p, q = key
  2510. encrypt_msg, y = message
  2511. public_key = p * q
  2512. L = len(encrypt_msg)
  2513. p_t = ((p + 1)/4)**L
  2514. q_t = ((q + 1)/4)**L
  2515. r_p = pow(int(y), int(p_t), int(p))
  2516. r_q = pow(int(y), int(q_t), int(q))
  2517. x = (q * invert(q, p) * r_p + p * invert(p, q) * r_q) % public_key
  2518. orig_bits = []
  2519. for _ in range(L):
  2520. orig_bits.append(x % 2)
  2521. x = x**2 % public_key
  2522. orig_msg = 0
  2523. for (m, b) in zip(encrypt_msg, orig_bits):
  2524. orig_msg = orig_msg * 2
  2525. orig_msg += (m ^ b)
  2526. return orig_msg