Fence Plus decrypt Python implementation (key encryption supported)

Source: Internet
Author: User
Tags decrypt

Fence plus decryption is a way to handle shorter strings. Given the row number row, the column number is computed from the string length to form a square.

The encryption process is to arrange the clear text from top to bottom in columns, and then scramble the rows according to the key. The text is then merged from left to right in line order to form ciphertext.

Decryption process: The above process is reversed, each line according to the order of the key back to the original square order, and restore the original square from the ciphertext, and finally in the order of columns from top to bottom from left to right decryption.

Detailed implementations such as the following: All implementations are encapsulated into a class railfence, which can be initialized with the number of columns and keys specified, the default number of columns is 2, no key. Initialization functions such as the following:

    def __init__ (self, row = 2, mask = None):        if row < 2:            raise ValueError (U ' not acceptable row number or mask Valu E ') Self        . Row    = row        if mask! = None and not isinstance (mask, types. StringType, types. Unicodetype)):            Raise ValueError (U ' not acceptable mask value ') Self        . Mask   = Mask self        . Length = 0 Self        . Column = 0
The encryption process allows you to choose whether to remove whitespace characters. The first is the type check, the calculation of the number of columns, the core is to get the gird of the two-dimensional list represented by the calculation of the square, but also the core of the fence encryption. Detailed implementations such as the following:

    def encrypt (self, src, nowhitespace = False): If is not isinstance (SRC, (types). StringType, types. Unicodetype)): Raise TypeError (U ' encryption src text is not string ') if nowhitespace:self. Nowhitespace = ' For i in Src:if I in string.whitespace:continue self. Nowhitespace + = i else:self. Nowhitespace = src self. Length = Len (self. Nowhitespace) self. Column = Int (Math.ceil (self). Length/self.        Row)) Try:self.__check () except Exception, Msg:print msg #get Mask Order Self.__getorder () Grid = [[] for I in range (self. Row)] for the C in range (self. Column): EndIndex = (c + 1) * self. Row if EndIndex > self. Length:endindex = self. Length r = self. Nowhitespace[c * Self. Row:endindex] for I,j in Enumerate (R): if self. Mask! = None and Len (Self. Order) > 0:grid[self. Order[i]].append (j) Else:grid[i].append (j) return ". Join ([". Join (L) for L in G RID])
The basic method is to iterate through the number of columns, each time a string from the clear text is stored in the traversal R, which is required to handle the end of the last column if the subscript exceeds the string length.

The column string is then incremented sequentially to the corresponding positions of the columns in the square grid.

The decryption process is a bit more complicated due to the disruption of the key pair sequence. The order of the scrambled rows needs to be resumed first. After the previous phalanx is obtained, the concatenated string is followed in the order of the columns to get the decrypted string. Detailed implementations such as the following:

    Def decrypt (self, DST): If not isinstance (DST, (types). StringType, types. Unicodetype)): Raise TypeError (U ' decryption DST text is not a string ') self. Length = Len (DST) self. Column = Int (Math.ceil (self). Length/self.        Row)) Try:self.__check () except Exception, Msg:print msg #get Mask Order Self.__getorder () Grid = [[] for I in range (self. ROW)] space = self. Row * Self. Column-self. Length ns = self. Row-space Preve = 0 for I in range (self. ROW): if self. Mask! = none:s = Preve O = 0 for x, y in enumerate (self. Order): if i = = Y:o = x break if O < n S:e = s + self. Column Else:e = s + (self.       Column-1) R = dst[s:e] Preve = e Grid[o] = list (r) Else:         StartIndex = 0 EndIndex = 0 if i < self. Row-space:startindex = i * self. Column EndIndex = StartIndex + self. Column Else:startindex = ns * Self. Column + (I-NS) * (self. Column-1) EndIndex = StartIndex + (self. Column-1) R = dst[startindex:endindex] grid[i] = List (r) res = ' for C in R Ange (self. Column): For I in range (self.                    Row): line = grid[i [] If len (line) = = C:res + = ' Else: Res + = Line[c] return res
Actual execution

Test code such as the following. With 4 lines of encryption, the key is BCAF:

    RF = Railfence (4, ' BCAF ')    e = Rf.encrypt (' The anwser is wctf{c01umnar},if u are a big new,u can help us think more ques Tion,tks. ')    Print "Encrypt:", e    print "Decrypt:", Rf.decrypt (E)
The results are for example:



Description: The decryption process given here is the number of known encrypted columns. Assuming the unknown, only need to traverse the number of columns, repeatedly call the decryption function can be.

Full code is here: https://github.com/OshynSong/web/blob/master/RailFence.py

Fence Plus decrypt Python implementation (key encryption supported)

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.