defrailfence(data:str, key:int): return"".join(data[i::key] for i inrange(key))
# 获取 x 的所有因数 deffactor(x:int): for i inrange(2, math.floor(math.sqrt(x))+1): if x % i == 0: yield i yield x // i
defcrack(data:str, needkeys:bool=False): if needkeys: facs = [i for i in factor(len(data))] return facs, [railfence(data, i) for i in facs] else: return [railfence(data, i) for i in factor(len(data))]
defprint_crack(data:str): keys, msg = crack(data, True) for k, m inzip(keys, msg): print(f"{k}栏: {m}")
defrailfence_plus_encode(data:str, key:list): return"".join([data[i::len(key)] for i inrange(len(key))][i-1] for i in key) defrailfence_plus_decode(data:str, key:list): k = len(data)//len(key) return"".join([data[key.index(i+1)*k + j] for j inrange(k) for i inrange(len(key))])
# 获取 w 型矩阵 defrailfence_w(data:str, key:int): mat = [[None]*len(data) for i inrange(key)] row = 0 upflag = False for col inrange(len(data)): mat[row][col] = data[col] if row == key-1: upflag = True if row == 0: upflag = False if upflag: row -= 1 else: row += 1 return mat
# 加密 defrailfence_w_encode(data, key): mat = railfence_w(data, key) msg = [] for row inrange(key): for col inrange(len(data)): if mat[row][col] != None: msg.append(mat[row][col]) return mat, msg
# 解密 defrailfence_w_decode(data, key): mat = railfence_w(data, key) sub = 0 for row inrange(key): for col inrange(len(data)): if mat[row][col] != None: mat[row][col] = data[sub] sub += 1 msg = [] for col inrange(len(data)): for row inrange(key): if mat[row][col] != None: msg.append(mat[row][col]) return mat, msg
# 爆破算法 defcrack_w(data:str, needkeys:bool=False): if needkeys: keys = [i for i inrange(2, len(data))] return keys, [''.join(railfence_w_decode(data, k)[1]) for k in keys] else: return [''.join(railfence_w_decode(data, k)[1]) for k inrange(2, len(data))]
defprint_crack_w(data:str): keys, msg = crack_w(data, True) for k, m inzip(keys, msg): print(f"{k}栏: {m}")