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)

结果如下图:

说明:这里给出的解密过程是已知加密的列数,如果未知,只需要遍历列数,重复调用解密函数即可。

完整代码详见这里

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。