栅栏加解密python实现(支持密钥加密)

栅栏加解密是对较短字符串的一种处理方式。给定行数Row,依据字符串长度计算出列数Column,构成一个方阵。

加密过程:就是按列依次从上到下对明文进行排列,然后依照密钥对各行进行打乱。最后以行顺序从左至右进行合并形成密文。

解密过程:将上述过程进行逆推,对每一行依据密钥的顺序回复到原始的方阵的顺序,并从密文回复原始的方阵,最后按列的顺序从上到下从左至右解密。

详细实现例如以下:全部实现封装到一个类RailFence中,初始化时能够指定列数和密钥,默认列数为2,无密钥。初始化函数例如以下:

    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
加密过程,能够选择是否去除空白字符。首先是类型检查,列数计算等工作,核心是通过计算的參数得到gird这个二维列表表示的方阵,也是栅栏加密的核心。详细实现例如以下:

    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])
当中基本的方法是依照列数遍历,每次从明文中取列数个数的字符串保存在遍历 r 中,当中须要处理最后一列的结束下标是否超过字符串长度。

然后将这一列字符串依次依照顺序增加到方阵grid的各列相应位置。

解密过程复杂一些,由于有密钥对顺序的打乱。须要先恢复打乱的各行的顺序。得到之前的方阵之后,再依照列的顺序依次连接字符串得到解密后的字符串。详细实现例如以下:

    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
实际执行

測试代码例如以下。以4行加密,密钥为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)
结果例如以下图:



说明:这里给出的解密过程是已知加密的列数。假设未知,仅仅须要遍历列数,反复调用解密函数就可以。

完整代码详见这里:https://github.com/OshynSong/web/blob/master/RailFence.py

原文地址:https://www.cnblogs.com/hrhguanli/p/5080785.html