📜  围栏密码-加密和解密

📅  最后修改于: 2021-04-24 19:50:09             🧑  作者: Mango

给定纯文本消息和数字键,请使用Rail Fence算法对给定文本进行加密/解密。
栅栏密码(也称为之字形密码)是换位密码的一种形式。它的名称来自其编码方式。
例子:

Encryption
Input :  "GeeksforGeeks "
Key = 3
Output : GsGsekfrek eoe
Decryption
Input : GsGsekfrek eoe
Key = 3
Output :  "GeeksforGeeks "

Encryption
Input :  "defend the east wall"
Key = 3
Output : dnhaweedtees alf  tl
Decryption
Input : dnhaweedtees alf  tl
Key = 3
Output : defend the east wall

Encryption
Input : "attack at once"
Key = 2 
Output : atc toctaka ne 
Decryption
Input : "atc toctaka ne"
Key = 2
Output : attack at once

加密

在换位密码中,重新排列字母的顺序以获得密文。

  • 在围栏密码中,纯文本向下且对角地写在假想围栏的连续轨道上。
  • 当我们到达底部导轨时,我们沿对角线向上移动,到达顶部导轨后,方向又改变了。因此,消息的字母以Z字形的方式书写。
  • 写入每个字母后,将各个行合并以获得密文。

例如,如果消息是“ GeeksforGeeks”,并且rails的数量= 3,则将密码准备为:
围栏算法

解密方式

正如我们前面所看到的,围栏密码中的列数保持等于纯文本消息的长度。并且键对应于滑轨的数量。

  • 因此,可以相应地构造轨道矩阵。一旦有了矩阵,我们就可以找出应该放置文本的位置(使用相同的方法,即沿对角线上下交替移动)。
  • 然后,我们将密文行明智地填充。填充后,我们以之字形方式遍历矩阵以获得原始文本。

执行:
令cipher-text =“ GsGsekfrek eoe”,并且Key = 3

  • 矩阵中的列数= len(密文)= 12
  • 行数=键= 3

因此,原始矩阵将为3 * 12,现在将带有文本的地方标记为“ *”,我们得到

* _ _ _ * _ _ _ * _ _ _ *
_ * _ * _ * _ * _ * _ * 
_ _ * _ _ _ *  _ _ _ * _ 

以下是使用上述算法对消息进行加密/解密的程序。

C++
// C++ program to illustrate Rail Fence Cipher
// Encryption and Decryption
#include 
using namespace std;
  
// function to encrypt a message
string encryptRailFence(string text, int key)
{
    // create the matrix to cipher plain text
    // key = rows , length(text) = columns
    char rail[key][(text.length())];
  
    // filling the rail matrix to distinguish filled
    // spaces from blank ones
    for (int i=0; i < key; i++)
        for (int j = 0; j < text.length(); j++)
            rail[i][j] = '\n';
  
    // to find the direction
    bool dir_down = false;
    int row = 0, col = 0;
  
    for (int i=0; i < text.length(); i++)
    {
        // check the direction of flow
        // reverse the direction if we've just
        // filled the top or bottom rail
        if (row == 0 || row == key-1)
            dir_down = !dir_down;
  
        // fill the corresponding alphabet
        rail[row][col++] = text[i];
  
        // find the next row using direction flag
        dir_down?row++ : row--;
    }
  
    //now we can construct the cipher using the rail matrix
    string result;
    for (int i=0; i < key; i++)
        for (int j=0; j < text.length(); j++)
            if (rail[i][j]!='\n')
                result.push_back(rail[i][j]);
  
    return result;
}
  
// This function receives cipher-text and key
// and returns the original text after decryption
string decryptRailFence(string cipher, int key)
{
    // create the matrix to cipher plain text
    // key = rows , length(text) = columns
    char rail[key][cipher.length()];
  
    // filling the rail matrix to distinguish filled
    // spaces from blank ones
    for (int i=0; i < key; i++)
        for (int j=0; j < cipher.length(); j++)
            rail[i][j] = '\n';
  
    // to find the direction
    bool dir_down;
  
    int row = 0, col = 0;
  
    // mark the places with '*'
    for (int i=0; i < cipher.length(); i++)
    {
        // check the direction of flow
        if (row == 0)
            dir_down = true;
        if (row == key-1)
            dir_down = false;
  
        // place the marker
        rail[row][col++] = '*';
  
        // find the next row using direction flag
        dir_down?row++ : row--;
    }
  
    // now we can construct the fill the rail matrix
    int index = 0;
    for (int i=0; i


Python3
# Python3 program to illustrate 
# Rail Fence Cipher Encryption
# and Decryption
  
# function to encrypt a message
def encryptRailFence(text, key):
  
    # create the matrix to cipher 
    # plain text key = rows , 
    # length(text) = columns
    # filling the rail matrix 
    # to distinguish filled 
    # spaces from blank ones
    rail = [['\n' for i in range(len(text))]
                  for j in range(key)]
      
    # to find the direction
    dir_down = False
    row, col = 0, 0
      
    for i in range(len(text)):
          
        # check the direction of flow
        # reverse the direction if we've just
        # filled the top or bottom rail
        if (row == 0) or (row == key - 1):
            dir_down = not dir_down
          
        # fill the corresponding alphabet
        rail[row][col] = text[i]
        col += 1
          
        # find the next row using
        # direction flag
        if dir_down:
            row += 1
        else:
            row -= 1
    # now we can construct the cipher 
    # using the rail matrix
    result = []
    for i in range(key):
        for j in range(len(text)):
            if rail[i][j] != '\n':
                result.append(rail[i][j])
    return("" . join(result))
      
# This function receives cipher-text 
# and key and returns the original 
# text after decryption
def decryptRailFence(cipher, key):
  
    # create the matrix to cipher 
    # plain text key = rows , 
    # length(text) = columns
    # filling the rail matrix to 
    # distinguish filled spaces
    # from blank ones
    rail = [['\n' for i in range(len(cipher))] 
                  for j in range(key)]
      
    # to find the direction
    dir_down = None
    row, col = 0, 0
      
    # mark the places with '*'
    for i in range(len(cipher)):
        if row == 0:
            dir_down = True
        if row == key - 1:
            dir_down = False
          
        # place the marker
        rail[row][col] = '*'
        col += 1
          
        # find the next row 
        # using direction flag
        if dir_down:
            row += 1
        else:
            row -= 1
              
    # now we can construct the 
    # fill the rail matrix
    index = 0
    for i in range(key):
        for j in range(len(cipher)):
            if ((rail[i][j] == '*') and
               (index < len(cipher))):
                rail[i][j] = cipher[index]
                index += 1
          
    # now read the matrix in 
    # zig-zag manner to construct
    # the resultant text
    result = []
    row, col = 0, 0
    for i in range(len(cipher)):
          
        # check the direction of flow
        if row == 0:
            dir_down = True
        if row == key-1:
            dir_down = False
              
        # place the marker
        if (rail[row][col] != '*'):
            result.append(rail[row][col])
            col += 1
              
        # find the next row using
        # direction flag
        if dir_down:
            row += 1
        else:
            row -= 1
    return("".join(result))
  
# Driver code
if __name__ == "__main__":
    print(encryptRailFence("attack at once", 2))
    print(encryptRailFence("GeeksforGeeks ", 3))
    print(encryptRailFence("defend the east wall", 3))
      
    # Now decryption of the
    # same cipher-text
    print(decryptRailFence("GsGsekfrek eoe", 3))
    print(decryptRailFence("atc toctaka ne", 2))
    print(decryptRailFence("dnhaweedtees alf tl", 3))
  
# This code is contributed 
# by Pratik Somwanshi


输出:

atc toctaka ne
GsGsekfrek eoe
dnhaweedtees alf  tl
GeeksforGeeks 
attack at once
delendfthe east wal


参考:

https://en.wikipedia.org/wiki/Rail_fence_cipher