crypto.py 87 KB

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