Python Cryptography Programming

Source: Internet
Author: User
Tags decrypt

I'm reading a book Recently. The name is Python cryptography programming. Make some notes here, and also provide some references for those in Need.

********************************************************************

* Quote: "http://inventwithpython.com/" *

* python-version:2.7.11 *

********************************************************************

1. The first method of Encryption. Inversion encryption Method.

That is, it is encrypted by reversing the output message. For example, "Hello world" is encrypted into "dlrow olleh"

This is a very weak encryption Method. Doing said it cleared to be still you, encrypt the doctrine of the interest

1 " three can keep a secret,if of them is Dead. " 2 "' 3 4 i = Len (message)-15 while I >= 0:6     translated = translated +< c13> message[i]7     i = i-18print translated

The idea of implementation is also very simple. is to stitch a string from back to front onto another string.

As for Decryption. You can make the message the encrypted ciphertext, and the printed text is clear.

2. Caesar Encryption method

Caesar encryption (Caesar Cipher) is a simple message encoding method: it moves each letter in the message with a constant bit of k according to the Alphabet. For example, if K equals 3, in the encoded message, each letter will move forward 3 bits: A will be replaced with d;b and will be replaced by e; The end of the alphabet will roll back to the beginning of the letter Table. As a result, w will be replaced with a z,x will be replaced by a

1Message ="This is my secret message"2Key = 133 4mode ="Encrypt"5LETTERS ='abcdefghijklmnopqrstuvwxyz'6translated ="'7Message =Message.upper ()8 9  forSymbolinchmessage:Ten     ifSymbolinchLETTERS: onenum =Letters.find (symbol) a         ifmode = ="Encrypt": -num = num +Key -         elifmode = ="Decrypt": thenum = num-Key -          -         ifNum >=Len (LETTERS): -num = num-Len (LETTERS) +         elifNum <0: -num = num +Len (LETTERS) +          atranslated = translated +letters[num] at      -     Else: -translated = translated +symbol -  - PrintTranslated

First of all. Message holds messages to be Encrypted. Key holds the secret Key. Mode represents the pattern, encrypt is encrypted, and decrypt is Decrypted. Translated is the encrypted string: the upper () method is used to ignore the Case.

Concrete Implementation. Iterates through each character in a message.

If the character belongs to 26 letters of English.

When the pattern is encrypted, the position of the character in the alphabet is added to the secret key. Replace with the characters of the new Position. If the value after the secret key exceeds the length of the alphabet, we need to roll back, minus the length of an alphabet to determine its new Position.

When the pattern is decrypted, the key is Subtracted. Note the length of the alphabet to be added when the position is less than 0.

When the character is not an English letter, it can be stitched directly onto the new string without replacing it.

3. Brute Force Caesar encryption method

In the case of Caesar encryption, we can see that there are only 26 possible keys. So we can try a brute force hack, which is to try every possible secret key.

1Message ="GUVF VF ZL Frperg zrffntr"2LETTERS ='abcdefghijklmnopqrstuvwxyz'3 4  forKeyinchRange (len (LETTERS)):5translated ="'6      forSymbolinchmessage:7         ifSymbolinchLETTERS:8num =Letters.find (symbol)9num = num-KeyTen             ifNum <0: onenum + =Len (LETTERS) aTranslated + =letters[num] -         Else: -Translated + =symbol the     Print "Key%s:%s"% (key, Translated)

This code has a lot in common with the above Code.

The message Stores Ciphertext. The rest of the code corresponds to the decrypt pattern Above.

We have printed out the possible decryption in 26.

4. Transposition Encryption method

The transposition encryption method is not a replacement character, but rather a sequence of confusing message symbols.

For example the message Common sense was not so Common.

Assume that the number 8 is used as the secret key. That is, we will put a maximum of 8 characters in each LINE. (contains spaces and Punctuation)

For the above message, we can draw a square chart

C O M M O N S
E N S E I S
N O T S O C
O M M O N .

The last line of the two lattice blacked out ignores them.

The normal way of reading should be to read horizontally. If we show the message in columns, it's confusing enough to make the message Invisible.

Ciphertext is Cenoonommstmme oo snnio. s s c (the spaces in the table need to be indicated, the black squares are ignored directly)

1 defMain ():2Mymessage ="Common sense isn't so Common."3MyKey = 84     5ciphertext =encryptmessage (myKey, Mymessage)6     7     PrintCiphertext +"|"8     9 defencryptmessage (key, message):Tenciphertext = ["']*Key one      a      forColinchRange (key): -pointer =Col -          the          whilePointer <Len (message): -ciphertext[col] + =message[pointer] -pointer + =Key -     return "'. Join (ciphertext) +          - if __name__=="__main__": +Main ()

Specific to the Encryptmessage Function. We first created a list that contains 8 (key) empty Elements. This corresponds to the 8 (key) column in the table Above.

We traverse these 8 columns.

In the first column, we stitch the original message in turn 0,8,16,24 ... characters. Until the length of the message is Exceeded.

In the second column, we stitch the original message in turn 1,9,17,25 ... characters. Until the length of the message is Exceeded.

And so on

The. Join method converts the list to a string and then Return.

The decryption process of the transposition encryption method:

After we receive the cipher and the secret key. We need to draw a table. The number of table rows equals the secret key, and the number of columns equals the cipher length divided by the secret key and rounded up.

such as ciphertext "cenoonommstmme oo Snnio. s s c "length 30, keys key = 8, We need to draw a table of 8 rows and 4 columns

From the upper left corner, fill in the Right. Then we'll see the clear text from the top down (in fact, the relationship between the two tables is similar to the inverse of the matrix).

C E N O
O N O M
M S T M
M E O
O S N
N I O .
S
S C
1 ImportMath2 3 defMain ():4Mymessage ="Cenoonommstmme Oo snnio. s s c"5MyKey = 86     7ciphertext =decryptmessage (myKey, Mymessage)8     9     PrintCiphertext +"|"Ten      one defdecryptmessage (key, message): anumofcolumns = int (math.ceil (len (message)/float (key))) -Numofrows =Key -numofshadeboxes = (numofcolumns * numofrows)-Len (message) theplaintext = ["'] *Numofcolumns -      -Col =0 -row =0 +      forSymbolinchmessage: -plaintext[col] + =symbol +Col + = 1 a          at         ifCol = = NumofcolumnsorCol = = NumOfColumns-1 andRow >= numofrows-numofshadeboxes: -Col =0 -Row + = 1 -     return "'. Join (plaintext) -      - if __name__=="__main__": inMain ()

This procedure is done in exactly the same way as the previous fill-in form.

Start with line No. 0, fill in the 0th column, the first column, the second column, and the third column

Then jump to the next line, and then click

which Numofshadedboxes represents the number of black squares, which is the default position for non-filled Characters. The program skips these places to fill in Characters.

Good. Now let's write a test program to prove that the previous encryption and decryption programs do work correctly when they correspond to different message and key.
1 ImportRandom,sys,transpositionencrypt,transpositiondecrypt2 3 defMain ():4Random.seed (42)5      forIinchXrange (20):6Message ="abcdefghijklmnopqrstuvwxyz"* Random.randint (4,40)7Message =List (message)8 random.shuffle (message)9Message ="'. Join (message)Ten         Print "Test #%s:%s ..."% (i+1,message[:50]) one          a          forKeyinchXrange (1, Len (message)): -             ifmessage! =transpositiondecrypt.decryptmessage (key, transpositionencrypt.encryptmessage (key, message)): -                 Print "mismatch with key%s and message%s"%(key, Message) the sys.exit () -     Print "Transposition cipher Test Passed." -      - if __name__=="__main__": +Main ()

which Import Statement. transpositionencrypt, Transpositiondecrypt is the name of the PY program that we wrote before to encrypt and decrypt the transposition Method.

During the test, we generated a random string of all English letters and scrambled the order to determine whether the program was working correctly by testing if the string was encrypted and then Decrypted.

Python Cryptography Programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.