这篇文章主要为大家详细介绍了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 !=None and not isinstance(mask, (types.stringtype, types.unicodetype)): self.mask=mask self.length=0 self.column=0 <i style="color:transparent">来源gaodai$ma#com搞$$代**码)网</i><pre></div><p>加密过程,可以选择是否去除空白字符。首先是类型检查,列数计算等工作,核心是通过计算的参数得到gird这个二维列表表示的方阵,也是栅栏加密的核心。具体实现如下:</p><div class="gaodaimacode"><pre class="prettyprint linenums"> 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: s (self.column - 1) r=dst[s : e] preve=e grid[o]=list(r) startindex endindex=0 if i </div><p>实际运行</p><p>测试代码如下,以4行加密,密钥为bcaf:</p><div class="gaodaimacode"><pre class="prettyprint linenums"> 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)
结果如下图:
说明:这里给出的解密过程是已知加密的列数,如果未知,只需要遍历列数,重复调用解密函数即可。
完整代码详见这里
以上就是python实现栅栏加解密 支持密钥加密的详细内容,更多请关注gaodaima搞代码网其它相关文章!