Basic Cryptography Module¶
Warning
This module is intended for educational purposes only. Do not use the functions in this module for real cryptographic applications. If you wish to encrypt real data, we recommend using something like the cryptography module.
Encryption is the process of hiding a message and a cipher is a means of doing so. Included in this module are both block and stream ciphers:
 Shift cipher
 Affine cipher
 substitution ciphers
 Vigenere’s cipher
 Hill’s cipher
 Bifid ciphers
 RSA
 Kid RSA
 linearfeedback shift registers (for stream ciphers)
 ElGamal encryption
In a substitution cipher “units” (not necessarily single characters) of plaintext are replaced with ciphertext according to a regular system.
A transposition cipher is a method of encryption by which the positions held by “units” of plaintext are replaced by a permutation of the plaintext. That is, the order of the units is changed using a bijective function on the position of the characters to perform the encryption.
A monoalphabetic cipher uses fixed substitution over the entire message, whereas a polyalphabetic cipher uses a number of substitutions at different times in the message.

sympy.crypto.crypto.
AZ
(s=None)[source]¶ Return the letters of
s
in uppercase. In case more than one string is passed, each of them will be processed and a list of upper case strings will be returned.See also
Examples
>>> from sympy.crypto.crypto import AZ >>> AZ('Hello, world!') 'HELLOWORLD' >>> AZ('Hello, world!'.split()) ['HELLO', 'WORLD']

sympy.crypto.crypto.
padded_key
(key, symbols, filter=True)[source]¶ Return a string of the distinct characters of
symbols
with those ofkey
appearing first, omitting characters inkey
that are not insymbols
. A ValueError is raised if a) there are duplicate characters insymbols
or b) there are characters inkey
that are not insymbols
.Examples
>>> from sympy.crypto.crypto import padded_key >>> padded_key('PUPPY', 'OPQRSTUVWXY') 'PUYOQRSTVWX' >>> padded_key('RSA', 'ARTIST') Traceback (most recent call last): ... ValueError: duplicate characters in symbols: T

sympy.crypto.crypto.
check_and_join
(phrase, symbols=None, filter=None)[source]¶ Joins characters of \(phrase\) and if
symbols
is given, raises an error if any character inphrase
is not insymbols
.Parameters: phrase: string or list of strings to be returned as a string
symbols: iterable of characters allowed in ``phrase``;
if
symbols
is None, no checking is performedExamples
>>> from sympy.crypto.crypto import check_and_join >>> check_and_join('a phrase') 'a phrase' >>> check_and_join('a phrase'.upper().split()) 'APHRASE' >>> check_and_join('a phrase!'.upper().split(), 'ARE', filter=True) 'ARAE' >>> check_and_join('a phrase!'.upper().split(), 'ARE') Traceback (most recent call last): ... ValueError: characters in phrase but not symbols: "!HPS"

sympy.crypto.crypto.
cycle_list
(k, n)[source]¶ Returns the elements of the list
range(n)
shifted to the left byk
(so the list starts withk
(modn
)).Examples
>>> from sympy.crypto.crypto import cycle_list >>> cycle_list(3, 10) [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]

sympy.crypto.crypto.
encipher_shift
(msg, key, symbols=None)[source]¶ Performs shift cipher encryption on plaintext msg, and returns the ciphertext.
Notes
The shift cipher is also called the Caesar cipher, after Julius Caesar, who, according to Suetonius, used it with a shift of three to protect messages of military significance. Caesar’s nephew Augustus reportedly used a similar cipher, but with a right shift of 1.
ALGORITHM:
INPUT:
key
: an integer (the secret key)msg
: plaintext of uppercase lettersOUTPUT:
ct
: ciphertext of uppercase letters STEPS:
 Number the letters of the alphabet from 0, …, N
 Compute from the string
msg
a listL1
of corresponding integers.  Compute from the list
L1
a new listL2
, given by adding(k mod 26)
to each element inL1
.  Compute from the list
L2
a stringct
of corresponding letters.
Examples
>>> from sympy.crypto.crypto import encipher_shift, decipher_shift >>> msg = "GONAVYBEATARMY" >>> ct = encipher_shift(msg, 1); ct 'HPOBWZCFBUBSNZ'
To decipher the shifted text, change the sign of the key:
>>> encipher_shift(ct, 1) 'GONAVYBEATARMY'
There is also a convenience function that does this with the original key:
>>> decipher_shift(ct, 1) 'GONAVYBEATARMY'

sympy.crypto.crypto.
decipher_shift
(msg, key, symbols=None)[source]¶ Return the text by shifting the characters of
msg
to the left by the amount given bykey
.Examples
>>> from sympy.crypto.crypto import encipher_shift, decipher_shift >>> msg = "GONAVYBEATARMY" >>> ct = encipher_shift(msg, 1); ct 'HPOBWZCFBUBSNZ'
To decipher the shifted text, change the sign of the key:
>>> encipher_shift(ct, 1) 'GONAVYBEATARMY'
Or use this function with the original key:
>>> decipher_shift(ct, 1) 'GONAVYBEATARMY'

sympy.crypto.crypto.
encipher_affine
(msg, key, symbols=None, _inverse=False)[source]¶ Performs the affine cipher encryption on plaintext
msg
, and returns the ciphertext.Encryption is based on the map \(x \rightarrow ax+b\) (mod \(N\)) where
N
is the number of characters in the alphabet. Decryption is based on the map \(x \rightarrow cx+d\) (mod \(N\)), where \(c = a^{1}\) (mod \(N\)) and \(d = a^{1}b\) (mod \(N\)). In particular, for the map to be invertible, we need \(\mathrm{gcd}(a, N) = 1\) and an error will be raised if this is not true.See also
Notes
This is a straightforward generalization of the shift cipher with the added complexity of requiring 2 characters to be deciphered in order to recover the key.
ALGORITHM:
INPUT:
msg
: string of characters that appear insymbols
a, b
: a pair integers, withgcd(a, N) = 1
(the secret key)symbols
: string of characters (default = uppercase letters). When no symbols are given,msg
is converted to upper case letters and all other charactes are ignored.OUTPUT:
ct
: string of characters (the ciphertext message) STEPS:
 Number the letters of the alphabet from 0, …, N
 Compute from the string
msg
a listL1
of corresponding integers.  Compute from the list
L1
a new listL2
, given by replacingx
bya*x + b (mod N)
, for each elementx
inL1
.  Compute from the list
L2
a stringct
of corresponding letters.

sympy.crypto.crypto.
decipher_affine
(msg, key, symbols=None)[source]¶ Return the deciphered text that was made from the mapping, \(x \rightarrow ax+b\) (mod \(N\)), where
N
is the number of characters in the alphabet. Deciphering is done by reciphering with a new key: \(x \rightarrow cx+d\) (mod \(N\)), where \(c = a^{1}\) (mod \(N\)) and \(d = a^{1}b\) (mod \(N\)).Examples
>>> from sympy.crypto.crypto import encipher_affine, decipher_affine >>> msg = "GO NAVY BEAT ARMY" >>> key = (3, 1) >>> encipher_affine(msg, key) 'TROBMVENBGBALV' >>> decipher_affine(_, key) 'GONAVYBEATARMY'

sympy.crypto.crypto.
encipher_substitution
(msg, old, new=None)[source]¶ Returns the ciphertext obtained by replacing each character that appears in
old
with the corresponding character innew
. Ifold
is a mapping, then new is ignored and the replacements defined byold
are used.Notes
This is a more general than the affine cipher in that the key can only be recovered by determining the mapping for each symbol. Though in practice, once a few symbols are recognized the mappings for other characters can be quickly guessed.
Examples
>>> from sympy.crypto.crypto import encipher_substitution, AZ >>> old = 'OEYAG' >>> new = '034^6' >>> msg = AZ("go navy! beat army!") >>> ct = encipher_substitution(msg, old, new); ct '60N^V4B3^T^RM4'
To decrypt a substitution, reverse the last two arguments:
>>> encipher_substitution(ct, new, old) 'GONAVYBEATARMY'
In the special case where
old
andnew
are a permutation of order 2 (representing a transposition of characters) their order is immaterial:>>> old = 'NAVY' >>> new = 'ANYV' >>> encipher = lambda x: encipher_substitution(x, old, new) >>> encipher('NAVY') 'ANYV' >>> encipher(_) 'NAVY'
The substitution cipher, in general, is a method whereby “units” (not necessarily single characters) of plaintext are replaced with ciphertext according to a regular system.
>>> ords = dict(zip('abc', ['\\%i' % ord(i) for i in 'abc'])) >>> print(encipher_substitution('abc', ords)) \97\98\99

sympy.crypto.crypto.
encipher_vigenere
(msg, key, symbols=None)[source]¶ Performs the Vigenère cipher encryption on plaintext
msg
, and returns the ciphertext.Notes
The Vigenère cipher is named after Blaise de Vigenère, a sixteenth century diplomat and cryptographer, by a historical accident. Vigenère actually invented a different and more complicated cipher. The socalled Vigenère cipher was actually invented by Giovan Batista Belaso in 1553.
This cipher was used in the 1800’s, for example, during the American Civil War. The Confederacy used a brass cipher disk to implement the Vigenère cipher (now on display in the NSA Museum in Fort Meade) [R76].
The Vigenère cipher is a generalization of the shift cipher. Whereas the shift cipher shifts each letter by the same amount (that amount being the key of the shift cipher) the Vigenère cipher shifts a letter by an amount determined by the key (which is a word or phrase known only to the sender and receiver).
For example, if the key was a single letter, such as “C”, then the socalled Vigenere cipher is actually a shift cipher with a shift of \(2\) (since “C” is the 2nd letter of the alphabet, if you start counting at \(0\)). If the key was a word with two letters, such as “CA”, then the socalled Vigenère cipher will shift letters in even positions by \(2\) and letters in odd positions are left alone (shifted by \(0\), since “A” is the 0th letter, if you start counting at \(0\)).
ALGORITHM:
INPUT:
msg
: string of characters that appear insymbols
(the plaintext)key
: a string of characters that appear insymbols
(the secret key)symbols
: a string of letters defining the alphabetOUTPUT:
ct
: string of characters (the ciphertext message) STEPS:
 Number the letters of the alphabet from 0, …, N
 Compute from the string
key
a listL1
of corresponding integers. Letn1 = len(L1)
.  Compute from the string
msg
a listL2
of corresponding integers. Letn2 = len(L2)
.  Break
L2
up sequentially into sublists of sizen1
; the last sublist may be smaller thann1
 For each of these sublists
L
ofL2
, compute a new listC
given byC[i] = L[i] + L1[i] (mod N)
to thei
th element in the sublist, for eachi
.  Assemble these lists
C
by concatenation into a new list of lengthn2
.  Compute from the new list a string
ct
of corresponding letters.
Once it is known that the key is, say, \(n\) characters long, frequency analysis can be applied to every \(n\)th letter of the ciphertext to determine the plaintext. This method is called Kasiski examination (although it was first discovered by Babbage). If they key is as long as the message and is comprised of randomly selected characters – a onetime pad – the message is theoretically unbreakable.
The cipher Vigenère actually discovered is an “autokey” cipher described as follows.
ALGORITHM:
INPUT:
key
: a string of letters (the secret key)msg
: string of letters (the plaintext message)OUTPUT:
ct
: string of uppercase letters (the ciphertext message) STEPS:
 Number the letters of the alphabet from 0, …, N
 Compute from the string
msg
a listL2
of corresponding integers. Letn2 = len(L2)
.  Let
n1
be the length of the key. Append to the stringkey
the firstn2  n1
characters of the plaintext message. Compute from this string (also of lengthn2
) a listL1
of integers corresponding to the letter numbers in the first step.  Compute a new list
C
given byC[i] = L1[i] + L2[i] (mod N)
.  Compute from the new list a string
ct
of letters corresponding to the new integers.
To decipher the autokey ciphertext, the key is used to decipher the first
n1
characters and then those characters become the key to decipher the nextn1
characters, etc…:>>> m = AZ('go navy, beat army! yes you can'); m 'GONAVYBEATARMYYESYOUCAN' >>> key = AZ('gold bug'); n1 = len(key); n2 = len(m) >>> auto_key = key + m[:n2  n1]; auto_key 'GOLDBUGGONAVYBEATARMYYE' >>> ct = encipher_vigenere(m, auto_key); ct 'MCYDWSHKOGAMKZCELYFGAYR' >>> n1 = len(key) >>> pt = [] >>> while ct: ... part, ct = ct[:n1], ct[n1:] ... pt.append(decipher_vigenere(part, key)) ... key = pt[1] ... >>> ''.join(pt) == m True
References
[R76] (1, 2) http://en.wikipedia.org/wiki/Vigenere_cipher [R77] (1, 2) http://web.archive.org/web/20071116100808/ http://filebox.vt.edu/users/batman/kryptos.html (short URL: https://goo.gl/ijr22d) Examples
>>> from sympy.crypto.crypto import encipher_vigenere, AZ >>> key = "encrypt" >>> msg = "meet me on monday" >>> encipher_vigenere(msg, key) 'QRGKKTHRZQEBPR'
Section 1 of the Kryptos sculpture at the CIA headquarters uses this cipher and also changes the order of the the alphabet [R77]. Here is the first line of that section of the sculpture:
>>> from sympy.crypto.crypto import decipher_vigenere, padded_key >>> alp = padded_key('KRYPTOS', AZ()) >>> key = 'PALIMPSEST' >>> msg = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJ' >>> decipher_vigenere(msg, key, alp) 'BETWEENSUBTLESHADINGANDTHEABSENC'

sympy.crypto.crypto.
decipher_vigenere
(msg, key, symbols=None)[source]¶ Decode using the Vigenère cipher.
Examples
>>> from sympy.crypto.crypto import decipher_vigenere >>> key = "encrypt" >>> ct = "QRGK kt HRZQE BPR" >>> decipher_vigenere(ct, key) 'MEETMEONMONDAY'

sympy.crypto.crypto.
encipher_hill
(msg, key, symbols=None, pad='Q')[source]¶ Return the Hill cipher encryption of
msg
.See also
Notes
The Hill cipher [R78], invented by Lester S. Hill in the 1920’s [R79], was the first polygraphic cipher in which it was practical (though barely) to operate on more than three symbols at once. The following discussion assumes an elementary knowledge of matrices.
First, each letter is first encoded as a number starting with 0. Suppose your message \(msg\) consists of \(n\) capital letters, with no spaces. This may be regarded an \(n\)tuple M of elements of \(Z_{26}\) (if the letters are those of the English alphabet). A key in the Hill cipher is a \(k x k\) matrix \(K\), all of whose entries are in \(Z_{26}\), such that the matrix \(K\) is invertible (i.e., the linear transformation \(K: Z_{N}^k \rightarrow Z_{N}^k\) is onetoone).
ALGORITHM:
INPUT:
msg
: plaintext message of \(n\) uppercase letterskey
: a \(k x k\) invertible matrix \(K\), all of whose entries are in \(Z_{26}\) (or whatever number of symbols are being used).pad
: character (default “Q”) to use to make length of text be a multiple ofk
OUTPUT:
ct
: ciphertext of uppercase letters STEPS:
 Number the letters of the alphabet from 0, …, N
 Compute from the string
msg
a listL
of corresponding integers. Letn = len(L)
.  Break the list
L
up intot = ceiling(n/k)
sublistsL_1
, …,L_t
of sizek
(with the last list “padded” to ensure its size isk
).  Compute new list
C_1
, …,C_t
given byC[i] = K*L_i
(arithmetic is done mod N), for eachi
.  Concatenate these into a list
C = C_1 + ... + C_t
.  Compute from
C
a stringct
of corresponding letters. This has lengthk*t
.
References
[R78] (1, 2) en.wikipedia.org/wiki/Hill_cipher [R79] (1, 2) Lester S. Hill, Cryptography in an Algebraic Alphabet, The American Mathematical Monthly Vol.36, JuneJuly 1929, pp.306312.

sympy.crypto.crypto.
decipher_hill
(msg, key, symbols=None)[source]¶ Deciphering is the same as enciphering but using the inverse of the key matrix.
Examples
>>> from sympy.crypto.crypto import encipher_hill, decipher_hill >>> from sympy import Matrix
>>> key = Matrix([[1, 2], [3, 5]]) >>> encipher_hill("meet me on monday", key) 'UEQDUEODOCTCWQ' >>> decipher_hill(_, key) 'MEETMEONMONDAY'
When the length of the plaintext (stripped of invalid characters) is not a multiple of the key dimension, extra characters will appear at the end of the enciphered and deciphered text. In order to decipher the text, those characters must be included in the text to be deciphered. In the following, the key has a dimension of 4 but the text is 2 short of being a multiple of 4 so two characters will be added.
>>> key = Matrix([[1, 1, 1, 2], [0, 1, 1, 0], ... [2, 2, 3, 4], [1, 1, 0, 1]]) >>> msg = "ST" >>> encipher_hill(msg, key) 'HJEB' >>> decipher_hill(_, key) 'STQQ' >>> encipher_hill(msg, key, pad="Z") 'ISPK' >>> decipher_hill(_, key) 'STZZ'
If the last two characters of the ciphertext were ignored in either case, the wrong plaintext would be recovered:
>>> decipher_hill("HD", key) 'ORMV' >>> decipher_hill("IS", key) 'UIKY'

sympy.crypto.crypto.
encipher_bifid
(msg, key, symbols=None)[source]¶ Performs the Bifid cipher encryption on plaintext
msg
, and returns the ciphertext.This is the version of the Bifid cipher that uses an \(n \times n\) Polybius square.
INPUT:
msg
: plaintext stringkey
: short string for key; duplicate characters are ignored and then it is padded with the characters insymbols
that were not in the short keysymbols
: \(n \times n\) characters defining the alphabet (default is string.printable)OUTPUT:
ciphertext (using Bifid5 cipher without spaces)See also

sympy.crypto.crypto.
decipher_bifid
(msg, key, symbols=None)[source]¶ Performs the Bifid cipher decryption on ciphertext
msg
, and returns the plaintext.This is the version of the Bifid cipher that uses the \(n \times n\) Polybius square.
INPUT:
msg
: ciphertext stringkey
: short string for key; duplicate characters are ignored and then it is padded with the characters insymbols
that were not in the short keysymbols
: \(n \times n\) characters defining the alphabet (default=string.printable, a \(10 \times 10\) matrix)OUTPUT:
deciphered textExamples
>>> from sympy.crypto.crypto import ( ... encipher_bifid, decipher_bifid, AZ)
Do an encryption using the bifid5 alphabet:
>>> alp = AZ().replace('J', '') >>> ct = AZ("meet me on monday!") >>> key = AZ("gold bug") >>> encipher_bifid(ct, key, alp) 'IEILHHFSTSFQYE'
When entering the text or ciphertext, spaces are ignored so it can be formatted as desired. Reentering the ciphertext from the preceding, putting 4 characters per line and padding with an extra J, does not cause problems for the deciphering:
>>> decipher_bifid(''' ... IEILH ... HFSTS ... FQYEJ''', key, alp) 'MEETMEONMONDAY'
When no alphabet is given, all 100 printable characters will be used:
>>> key = '' >>> encipher_bifid('hello world!', key) 'bmtwmgbIo*w' >>> decipher_bifid(_, key) 'hello world!'
If the key is changed, a different encryption is obtained:
>>> key = 'gold bug' >>> encipher_bifid('hello world!', 'gold_bug') 'hg2sfuei7t}w'
And if the key used to decrypt the message is not exact, the original text will not be perfectly obtained:
>>> decipher_bifid(_, 'gold pug') 'heldo~wor6d!'

sympy.crypto.crypto.
bifid5_square
(key=None)[source]¶ 5x5 Polybius square.
Produce the Polybius square for the \(5 \times 5\) Bifid cipher.
Examples
>>> from sympy.crypto.crypto import bifid5_square >>> bifid5_square("gold bug") Matrix([ [G, O, L, D, B], [U, A, C, E, F], [H, I, K, M, N], [P, Q, R, S, T], [V, W, X, Y, Z]])

sympy.crypto.crypto.
encipher_bifid5
(msg, key)[source]¶ Performs the Bifid cipher encryption on plaintext
msg
, and returns the ciphertext.This is the version of the Bifid cipher that uses the \(5 \times 5\) Polybius square. The letter “J” is ignored so it must be replaced with something else (traditionally an “I”) before encryption.
See also
Notes
The Bifid cipher was invented around 1901 by Felix Delastelle. It is a fractional substitution cipher, where letters are replaced by pairs of symbols from a smaller alphabet. The cipher uses a \(5 \times 5\) square filled with some ordering of the alphabet, except that “J” is replaced with “I” (this is a socalled Polybius square; there is a \(6 \times 6\) analog if you add back in “J” and also append onto the usual 26 letter alphabet, the digits 0, 1, …, 9). According to Helen Gaines’ book Cryptanalysis, this type of cipher was used in the field by the German Army during World War I.
ALGORITHM: (5x5 case)
INPUT:
msg
: plaintext string; converted to upper case and filtered of anything but all letters except J.key
: short string for key; nonalphabetic letters, J and duplicated characters are ignored and then, if the length is less than 25 characters, it is padded with other letters of the alphabet (in alphabetical order).OUTPUT:
ciphertext (all caps, no spaces) STEPS:
Create the \(5 \times 5\) Polybius square
S
associated tokey
as follows: moving from lefttoright, toptobottom, place the letters of the key into a \(5 \times 5\) matrix,
 if the key has less than 25 letters, add the letters of the alphabet not in the key until the \(5 \times 5\) square is filled.
Create a list
P
of pairs of numbers which are the coordinates in the Polybius square of the letters inmsg
.Let
L1
be the list of all first coordinates ofP
(length ofL1 = n
), letL2
be the list of all second coordinates ofP
(so the length ofL2
is alson
).Let
L
be the concatenation ofL1
andL2
(lengthL = 2*n
), except that consecutive numbers are paired(L[2*i], L[2*i + 1])
. You can regardL
as a list of pairs of lengthn
.Let
C
be the list of all letters which are of the formS[i, j]
, for all(i, j)
inL
. As a string, this is the ciphertext ofmsg
.
Examples
>>> from sympy.crypto.crypto import ( ... encipher_bifid5, decipher_bifid5)
“J” will be omitted unless it is replaced with something else:
>>> round_trip = lambda m, k: \ ... decipher_bifid5(encipher_bifid5(m, k), k) >>> key = 'a' >>> msg = "JOSIE" >>> round_trip(msg, key) 'OSIE' >>> round_trip(msg.replace("J", "I"), key) 'IOSIE' >>> j = "QIQ" >>> round_trip(msg.replace("J", j), key).replace(j, "J") 'JOSIE'

sympy.crypto.crypto.
decipher_bifid5
(msg, key)[source]¶ Return the Bifid cipher decryption of
msg
.This is the version of the Bifid cipher that uses the \(5 \times 5\) Polybius square; the letter “J” is ignored unless a
key
of length 25 is used.INPUT:
msg
: ciphertext stringkey
: short string for key; duplicated characters are ignored and if the length is less then 25 characters, it will be padded with other letters from the alphabet omitting “J”. Nonalphabetic characters are ignored.OUTPUT:
plaintext from Bifid5 cipher (all caps, no spaces)Examples
>>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5 >>> key = "gold bug" >>> encipher_bifid5('meet me on friday', key) 'IEILEHFSTSFXEE' >>> encipher_bifid5('meet me on monday', key) 'IEILHHFSTSFQYE' >>> decipher_bifid5(_, key) 'MEETMEONMONDAY'

sympy.crypto.crypto.
bifid5_square
(key=None)[source] 5x5 Polybius square.
Produce the Polybius square for the \(5 \times 5\) Bifid cipher.
Examples
>>> from sympy.crypto.crypto import bifid5_square >>> bifid5_square("gold bug") Matrix([ [G, O, L, D, B], [U, A, C, E, F], [H, I, K, M, N], [P, Q, R, S, T], [V, W, X, Y, Z]])

sympy.crypto.crypto.
encipher_bifid6
(msg, key)[source]¶ Performs the Bifid cipher encryption on plaintext
msg
, and returns the ciphertext.This is the version of the Bifid cipher that uses the \(6 \times 6\) Polybius square.
INPUT:
msg
: plaintext string (digits okay)key
: short string for key (digits okay). Ifkey
is less than 36 characters long, the square will be filled with letters A through Z and digits 0 through 9.OUTPUT:
ciphertext from Bifid cipher (all caps, no spaces)See also

sympy.crypto.crypto.
decipher_bifid6
(msg, key)[source]¶ Performs the Bifid cipher decryption on ciphertext
msg
, and returns the plaintext.This is the version of the Bifid cipher that uses the \(6 \times 6\) Polybius square.
INPUT:
msg
: ciphertext string (digits okay); converted to upper casekey
: short string for key (digits okay). Ifkey
is less than 36 characters long, the square will be filled with letters A through Z and digits 0 through 9. All letters are converted to uppercase.OUTPUT:
plaintext from Bifid cipher (all caps, no spaces)Examples
>>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6 >>> key = "gold bug" >>> encipher_bifid6('meet me on monday at 8am', key) 'KFKLJJHF5MMMKTFRGPL' >>> decipher_bifid6(_, key) 'MEETMEONMONDAYAT8AM'

sympy.crypto.crypto.
bifid6_square
(key=None)[source]¶ 6x6 Polybius square.
Produces the Polybius square for the \(6 \times 6\) Bifid cipher. Assumes alphabet of symbols is “A”, …, “Z”, “0”, …, “9”.
Examples
>>> from sympy.crypto.crypto import bifid6_square >>> key = "gold bug" >>> bifid6_square(key) Matrix([ [G, O, L, D, B, U], [A, C, E, F, H, I], [J, K, M, N, P, Q], [R, S, T, V, W, X], [Y, Z, 0, 1, 2, 3], [4, 5, 6, 7, 8, 9]])

sympy.crypto.crypto.
rsa_public_key
(p, q, e)[source]¶ Return the RSA public key pair, \((n, e)\), where \(n\) is a product of two primes and \(e\) is relatively prime (coprime) to the Euler totient \(\phi(n)\). False is returned if any assumption is violated.
Examples
>>> from sympy.crypto.crypto import rsa_public_key >>> p, q, e = 3, 5, 7 >>> rsa_public_key(p, q, e) (15, 7) >>> rsa_public_key(p, q, 30) False

sympy.crypto.crypto.
rsa_private_key
(p, q, e)[source]¶ Return the RSA private key, \((n,d)\), where \(n\) is a product of two primes and \(d\) is the inverse of \(e\) (mod \(\phi(n)\)). False is returned if any assumption is violated.
Examples
>>> from sympy.crypto.crypto import rsa_private_key >>> p, q, e = 3, 5, 7 >>> rsa_private_key(p, q, e) (15, 7) >>> rsa_private_key(p, q, 30) False

sympy.crypto.crypto.
encipher_rsa
(i, key)[source]¶ Return encryption of
i
by computing \(i^e\) (mod \(n\)), wherekey
is the public key \((n, e)\).Examples
>>> from sympy.crypto.crypto import encipher_rsa, rsa_public_key >>> p, q, e = 3, 5, 7 >>> puk = rsa_public_key(p, q, e) >>> msg = 12 >>> encipher_rsa(msg, puk) 3

sympy.crypto.crypto.
decipher_rsa
(i, key)[source]¶ Return decyption of
i
by computing \(i^d\) (mod \(n\)), wherekey
is the private key \((n, d)\).Examples
>>> from sympy.crypto.crypto import decipher_rsa, rsa_private_key >>> p, q, e = 3, 5, 7 >>> prk = rsa_private_key(p, q, e) >>> msg = 3 >>> decipher_rsa(msg, prk) 12

sympy.crypto.crypto.
kid_rsa_public_key
(a, b, A, B)[source]¶ Kid RSA is a version of RSA useful to teach grade school children since it does not involve exponentiation.
Alice wants to talk to Bob. Bob generates keys as follows. Key generation:
 Select positive integers \(a, b, A, B\) at random.
 Compute \(M = a b  1\), \(e = A M + a\), \(d = B M + b\), \(n = (e d  1)//M\).
 The public key is \((n, e)\). Bob sends these to Alice.
 The private key is \((n, d)\), which Bob keeps secret.
Encryption: If \(p\) is the plaintext message then the ciphertext is \(c = p e \pmod n\).
Decryption: If \(c\) is the ciphertext message then the plaintext is \(p = c d \pmod n\).
Examples
>>> from sympy.crypto.crypto import kid_rsa_public_key >>> a, b, A, B = 3, 4, 5, 6 >>> kid_rsa_public_key(a, b, A, B) (369, 58)

sympy.crypto.crypto.
kid_rsa_private_key
(a, b, A, B)[source]¶ Compute \(M = a b  1\), \(e = A M + a\), \(d = B M + b\), \(n = (e d  1) / M\). The private key is \(d\), which Bob keeps secret.
Examples
>>> from sympy.crypto.crypto import kid_rsa_private_key >>> a, b, A, B = 3, 4, 5, 6 >>> kid_rsa_private_key(a, b, A, B) (369, 70)

sympy.crypto.crypto.
encipher_kid_rsa
(msg, key)[source]¶ Here
msg
is the plaintext andkey
is the public key.Examples
>>> from sympy.crypto.crypto import ( ... encipher_kid_rsa, kid_rsa_public_key) >>> msg = 200 >>> a, b, A, B = 3, 4, 5, 6 >>> key = kid_rsa_public_key(a, b, A, B) >>> encipher_kid_rsa(msg, key) 161

sympy.crypto.crypto.
decipher_kid_rsa
(msg, key)[source]¶ Here
msg
is the plaintext andkey
is the private key.Examples
>>> from sympy.crypto.crypto import ( ... kid_rsa_public_key, kid_rsa_private_key, ... decipher_kid_rsa, encipher_kid_rsa) >>> a, b, A, B = 3, 4, 5, 6 >>> d = kid_rsa_private_key(a, b, A, B) >>> msg = 200 >>> pub = kid_rsa_public_key(a, b, A, B) >>> pri = kid_rsa_private_key(a, b, A, B) >>> ct = encipher_kid_rsa(msg, pub) >>> decipher_kid_rsa(ct, pri) 200

sympy.crypto.crypto.
encode_morse
(msg, sep='', mapping=None)[source]¶ Encodes a plaintext into popular Morse Code with letters separated by \(sep\) and words by a double \(sep\).
References
[R80] http://en.wikipedia.org/wiki/Morse_code Examples
>>> from sympy.crypto.crypto import encode_morse >>> msg = 'ATTACK RIGHT FLANK' >>> encode_morse(msg) '.......................'

sympy.crypto.crypto.
decode_morse
(msg, sep='', mapping=None)[source]¶ Decodes a Morse Code with letters separated by \(sep\) (default is ‘’) and words by \(word_sep\) (default is ‘) into plaintext.
References
[R81] http://en.wikipedia.org/wiki/Morse_code Examples
>>> from sympy.crypto.crypto import decode_morse >>> mc = '.........' >>> decode_morse(mc) 'MOVE EAST'

sympy.crypto.crypto.
lfsr_sequence
(key, fill, n)[source]¶ This function creates an lfsr sequence.
INPUT:
key
: a list of finite field elements, \([c_0, c_1, \ldots, c_k].\)
fill
: the list of the initial terms of the lfsr sequence, \([x_0, x_1, \ldots, x_k].\)
n
: number of terms of the sequence that the function returns.
OUTPUT:
The lfsr sequence defined by \(x_{n+1} = c_k x_n + \ldots + c_0 x_{nk}\), for \(n \leq k\).Notes
S. Golomb [G81] gives a list of three statistical properties a sequence of numbers \(a = \{a_n\}_{n=1}^\infty\), \(a_n \in \{0,1\}\), should display to be considered “random”. Define the autocorrelation of \(a\) to be
\[C(k) = C(k,a) = \lim_{N\rightarrow \infty} {1\over N}\sum_{n=1}^N (1)^{a_n + a_{n+k}}.\]In the case where \(a\) is periodic with period \(P\) then this reduces to
\[C(k) = {1\over P}\sum_{n=1}^P (1)^{a_n + a_{n+k}}.\]Assume \(a\) is periodic with period \(P\).
balance:
\[\left\sum_{n=1}^P(1)^{a_n}\right \leq 1.\]low autocorrelation:
\[\begin{split}C(k) = \left\{ \begin{array}{cc} 1,& k = 0,\\ \epsilon, & k \ne 0. \end{array} \right.\end{split}\](For sequences satisfying these first two properties, it is known that \(\epsilon = 1/P\) must hold.)
proportional runs property: In each period, half the runs have length \(1\), onefourth have length \(2\), etc. Moreover, there are as many runs of \(1\)‘s as there are of \(0\)‘s.
References
[G81] (1, 2) Solomon Golomb, Shift register sequences, Aegean Park Press, Laguna Hills, Ca, 1967 Examples
>>> from sympy.crypto.crypto import lfsr_sequence >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> lfsr_sequence(key, fill, 10) [1 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 1 mod 2, 0 mod 2, 0 mod 2, 1 mod 2]

sympy.crypto.crypto.
lfsr_autocorrelation
(L, P, k)[source]¶ This function computes the LFSR autocorrelation function.
INPUT:
L
: is a periodic sequence of elements of \(GF(2)\).L
must have length larger thanP
.P
: the period ofL
k
: an integer (\(0 < k < p\))OUTPUT:
thek
th value of the autocorrelation of the LFSRL
Examples
>>> from sympy.crypto.crypto import ( ... lfsr_sequence, lfsr_autocorrelation) >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_autocorrelation(s, 15, 7) 1/15 >>> lfsr_autocorrelation(s, 15, 0) 1

sympy.crypto.crypto.
lfsr_connection_polynomial
(s)[source]¶ This function computes the LFSR connection polynomial.
INPUT:
s
: a sequence of elements of even length, with entries in a finite fieldOUTPUT:
C(x)
: the connection polynomial of a minimal LFSR yieldings
.This implements the algorithm in section 3 of J. L. Massey’s article [M82].
References
[M82] (1, 2) James L. Massey, “ShiftRegister Synthesis and BCH Decoding.” IEEE Trans. on Information Theory, vol. 15(1), pp. 122127, Jan 1969. Examples
>>> from sympy.crypto.crypto import ( ... lfsr_sequence, lfsr_connection_polynomial) >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**4 + x + 1 >>> fill = [F(1), F(0), F(0), F(1)] >>> key = [F(1), F(1), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + 1 >>> fill = [F(1), F(0), F(1)] >>> key = [F(1), F(1), F(0)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + x**2 + 1 >>> fill = [F(1), F(0), F(1)] >>> key = [F(1), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + x + 1

sympy.crypto.crypto.
elgamal_public_key
(key)[source]¶ Return three number tuple as public key.
Parameters: key : Tuple (p, r, e) generated by elgamal_private_key
Returns: (p, r, e = r**d mod p) : d is a random number in private key. Examples
>>> from sympy.crypto.crypto import elgamal_public_key >>> elgamal_public_key((1031, 14, 636)) (1031, 14, 212)

sympy.crypto.crypto.
elgamal_private_key
(digit=10, seed=None)[source]¶ Return three number tuple as private key.
Elgamal encryption is based on the mathmatical problem called the Discrete Logarithm Problem (DLP). For example,
\(a^{b} \equiv c \pmod p\)
In general, if
a
andb
are known,ct
is easily calculated. Ifb
is unknown, it is hard to usea
andct
to getb
.Parameters: digit : minimum number of binary digits for key Returns: (p, r, d) : p = prime number, r = primitive root, d = random number Notes
For testing purposes, the
seed
parameter may be set to control the output of this routine. See sympy.utilities.randtest._randrange.Examples
>>> from sympy.crypto.crypto import elgamal_private_key >>> from sympy.ntheory import is_primitive_root, isprime >>> a, b, _ = elgamal_private_key() >>> isprime(a) True >>> is_primitive_root(b, a) True

sympy.crypto.crypto.
encipher_elgamal
(i, key, seed=None)[source]¶ Encrypt message with public key
i
is a plaintext message expressed as an integer.key
is public key (p, r, e). In order to encrypt a message, a random numbera
inrange(2, p)
is generated and the encryped message is returned as \(c_{1}\) and \(c_{2}\) where:\(c_{1} \equiv r^{a} \pmod p\)
\(c_{2} \equiv m e^{a} \pmod p\)
Parameters: msg : int of encoded message
key : public key
Returns: (c1, c2) : Encipher into two number
Notes
For testing purposes, the
seed
parameter may be set to control the output of this routine. See sympy.utilities.randtest._randrange.Examples
>>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key >>> pri = elgamal_private_key(5, seed=[3]); pri (37, 2, 3) >>> pub = elgamal_public_key(pri); pub (37, 2, 8) >>> msg = 36 >>> encipher_elgamal(msg, pub, seed=[3]) (8, 6)

sympy.crypto.crypto.
decipher_elgamal
(msg, key)[source]¶ Decrypt message with private key
\(msg = (c_{1}, c_{2})\)
\(key = (p, r, d)\)
According to extended Eucliden theorem, \(u c_{1}^{d} + p n = 1\)
\(u \equiv 1/{{c_{1}}^d} \pmod p\)
\(u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p\)
\(\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p\)
Examples
>>> from sympy.crypto.crypto import decipher_elgamal >>> from sympy.crypto.crypto import encipher_elgamal >>> from sympy.crypto.crypto import elgamal_private_key >>> from sympy.crypto.crypto import elgamal_public_key
>>> pri = elgamal_private_key(5, seed=[3]) >>> pub = elgamal_public_key(pri); pub (37, 2, 8) >>> msg = 17 >>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg True

sympy.crypto.crypto.
dh_public_key
(key)[source]¶ Return three number tuple as public key.
This is the tuple that Alice sends to Bob.
Parameters: key: Tuple (p, g, a) generated by ``dh_private_key`` Returns: (p, g, g^a mod p) : p, g and a as in Parameters Examples
>>> from sympy.crypto.crypto import dh_private_key, dh_public_key >>> p, g, a = dh_private_key(); >>> _p, _g, x = dh_public_key((p, g, a)) >>> p == _p and g == _g True >>> x == pow(g, a, p) True

sympy.crypto.crypto.
dh_private_key
(digit=10, seed=None)[source]¶ Return three integer tuple as private key.
DiffieHellman key exchange is based on the mathematical problem called the Discrete Logarithm Problem (see ElGamal).
DiffieHellman key exchange is divided into the following steps:
 Alice and Bob agree on a base that consist of a prime
p
and a primitive root ofp
calledg
 Alice choses a number
a
and Bob choses a numberb
wherea
andb
are random numbers in range \([2, p)\). These are their private keys.  Alice then publicly sends Bob \(g^{a} \pmod p\) while Bob sends Alice \(g^{b} \pmod p\)
 They both raise the received value to their secretly chosen
number (
a
orb
) and now have both as their shared key \(g^{ab} \pmod p\)
Parameters: digit: minimum number of binary digits required in key
Returns: (p, g, a) : p = prime number, g = primitive root of p,
a = random number from 2 through p  1
Notes
For testing purposes, the
seed
parameter may be set to control the output of this routine. See sympy.utilities.randtest._randrange.Examples
>>> from sympy.crypto.crypto import dh_private_key >>> from sympy.ntheory import isprime, is_primitive_root >>> p, g, _ = dh_private_key() >>> isprime(p) True >>> is_primitive_root(g, p) True >>> p, g, _ = dh_private_key(5) >>> isprime(p) True >>> is_primitive_root(g, p) True
 Alice and Bob agree on a base that consist of a prime
Return an integer that is the shared key.
This is what Bob and Alice can both calculate using the public keys they received from each other and their private keys.
Parameters: key: Tuple (p, g, x) generated by ``dh_public_key``
b: Random number in the range of 2 to p  1
(Chosen by second key exchange member (Bob))
Returns: shared key (int)
Examples
>>> from sympy.crypto.crypto import ( ... dh_private_key, dh_public_key, dh_shared_key) >>> prk = dh_private_key(); >>> p, g, x = dh_public_key(prk); >>> sk = dh_shared_key((p, g, x), 1000) >>> sk == pow(x, 1000, p) True

sympy.crypto.crypto.
encipher_elgamal
(i, key, seed=None)[source] Encrypt message with public key
i
is a plaintext message expressed as an integer.key
is public key (p, r, e). In order to encrypt a message, a random numbera
inrange(2, p)
is generated and the encryped message is returned as \(c_{1}\) and \(c_{2}\) where:\(c_{1} \equiv r^{a} \pmod p\)
\(c_{2} \equiv m e^{a} \pmod p\)
Parameters: msg : int of encoded message
key : public key
Returns: (c1, c2) : Encipher into two number
Notes
For testing purposes, the
seed
parameter may be set to control the output of this routine. See sympy.utilities.randtest._randrange.Examples
>>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key >>> pri = elgamal_private_key(5, seed=[3]); pri (37, 2, 3) >>> pub = elgamal_public_key(pri); pub (37, 2, 8) >>> msg = 36 >>> encipher_elgamal(msg, pub, seed=[3]) (8, 6)

sympy.crypto.crypto.
decipher_elgamal
(msg, key)[source] Decrypt message with private key
\(msg = (c_{1}, c_{2})\)
\(key = (p, r, d)\)
According to extended Eucliden theorem, \(u c_{1}^{d} + p n = 1\)
\(u \equiv 1/{{c_{1}}^d} \pmod p\)
\(u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p\)
\(\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p\)
Examples
>>> from sympy.crypto.crypto import decipher_elgamal >>> from sympy.crypto.crypto import encipher_elgamal >>> from sympy.crypto.crypto import elgamal_private_key >>> from sympy.crypto.crypto import elgamal_public_key
>>> pri = elgamal_private_key(5, seed=[3]) >>> pub = elgamal_public_key(pri); pub (37, 2, 8) >>> msg = 17 >>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg True

sympy.crypto.crypto.
gm_public_key
(p, q, a=None, seed=None)[source]¶ Compute public keys for p and q. Note that in GoldwasserMicali Encrpytion, public keys are randomly selected.
Parameters: p, q, a : (int) initialization variables
Returns: (a, N) : tuple[int]
a is the input a if it is not None otherwise some random integer coprime to p and q.
N is the product of p and q

sympy.crypto.crypto.
gm_private_key
(p, q, a=None)[source]¶ Check if p and q can be used as private keys for the GoldwasserMicali encryption. The method works roughly as follows.
Pick two large primes p ands q. Call their product N. Given a message as an integer i, write i in its bit representation b_0,…,b_n. For each k,
 if b_k = 0:
 let a_k be a random square (quadratic residue) modulo p * q such that jacobi_symbol(a, p * q) = 1
 if b_k = 1:
 let a_k be a random nonsquare (nonquadratic residue) modulo p * q such that jacobi_symbol(a, p * q) = 1
return [a_1, a_2,…]
b_k can be recovered by checking whether or not a_k is a residue. And from the b_k’s, the message can be reconstructed.
The idea is that, while jacobi_symbol(a, p * q) can be easily computed (and when it is equal to 1 will tell you that a is not a square mod p * q), quadratic residuosity modulo a composite number is hard to compute without knowing its factorization.
Moreover, approximately half the numbers coprime to p * q have jacobi_symbol equal to 1. And among those, approximately half are residues and approximately half are not. This maximizes the entropy of the code.
Parameters: p, q, a : initialization variables Returns: p, q : the input value p and q Raises: ValueError : if p and q are not distinct odd primes