Barrier encryption and decryption python implementation (key encryption supported)

Source: Internet
Author: User

Barrier encryption and decryption python implementation (key encryption supported)

Fence encryption and decryption is a processing method for short strings. Given the Row number, the Column number is calculated based on the string length to form a square matrix.

Encryption process: the plaintext is arranged from top to bottom by column, and then the lines are disrupted by key. Finally, the ciphertext is merged from left to right in the row order.

Decryption process: the above process is reversed, and each row is returned to the original phalanx Sequence Based on the Key sequence, and the original phalanx is returned from the ciphertext, finally, decryption is performed from top to bottom from left to right in the column order.

The specific implementation is as follows: All implementations are encapsulated into a class RailFence. during initialization, you can specify the number of columns and keys. The default number of columns is 2 and no key is available. The initialization function is as follows:

 

    def __init__(self, row = 2, mask = None):        if row < 2:            raise ValueError(u'Not acceptable row number or mask value')        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
Encryption process, you can choose whether to remove white spaces. The first is type check and column number calculation. The core is to obtain the square matrix represented by the two-dimensional list of gird through calculation parameters, which is also the core of fence encryption. The specific implementation is as follows:

 

 

    def encrypt(self, src, nowhitespace = False):        if 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 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 grid])
The main method is to traverse by number of columns. Each time you extract the number of columns from the text, the string is saved in traversal r. You need to check whether the ending subscript of the last column exceeds the length of the string. Then, the column strings are sequentially added to the corresponding positions of each column in The Matrix grid.

 

The decryption process is complicated. Because of the disordered order of key pairs, you must first restore the disordered order of each row. After obtaining the square matrix, then, connect the string in the column order to obtain the decrypted string. The specific implementation is as follows:

 

    def decrypt(self, dst):        if not isinstance(dst, (types.StringType, types.UnicodeType)):            raise TypeError(u'Decryption dst text is not 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 < ns: 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 range(self.Column):            for i in range(self.Row):                line = grid[i]                if len(line) == c:                    res += ' '                else:                    res += line[c]        return res
Actual Operation

 

The test code is as follows, encrypted with four lines and the key is bcaf:

 

    rf = RailFence(4, 'bcaf')    e = rf.encrypt('the anwser is wctf{C01umnar},if u is a big new,u can help us think more question,tks.')    print Encrypt: ,e    print Decrypt: , rf.decrypt(e)
The result is as follows:

 



Note: The decryption process provided here is known to encrypt the number of columns. If it is unknown, you only need to traverse the number of columns and call the decryption function again.

 

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.