[Principle and Practice of Cryptography] (6) Implementation of Replacement Code in Java Code

Replacement password

The replacement password is different from the previous replacement password. The replacement password keeps all the letters of the plaintext unchanged, but uses replacement to disrupt the position and order of the plaintext letters.

First, you need to understand that permutation is both injective and surjective

definition

Let m be a positive integer, P=C= (Z 26) m (Z_{26})^m( Z26)m ,K is the permutation composition defined on the set {1, 2...m} on the left and right. For any secret key π, the definition:ex (x 1, x 2... xm) = (x π (1), x π (2),... x π (m)) e_x(x_1,x_2...x_m)=(x_(π(1)),x_(π(2)),...x_(π(m) )})ex(x1,x2...xm)=(xp ( 1 ),xp ( 2 ),...xπ ( m ))d π (y 1, y 2... Ym) = (y π - 1 (1), and π - 1 (2),.. Y π - 1 (m)) d_π (y_1, y_2 .. .y_m) = (y_ {π ^ {- 1} (1)}, y_ {π ^ {- 1} (2)}, .. y_ {π ^ {- 1} (m)})dFr.( and1,and2. . . andm)=( andPi1(1),andPi1(2),. . andPi1(m)) Whereπ − 1 π^{-1}Pi1 is the inverse permutation of permutation π.

for example

Set m=6, the key is the following permutation π:

x 1 2 3 4 5 6
π (x) 3 5 1 6 4 2

From the above, the inverse replacement is

x 1 2 3 4 5 6
π - 1 (x) π ^ {- 1} (x) Pi1(x) 3 6 1 5 2 4

Suppose the plaintext we encrypt is: shesellsseashellsbytheseashore

We need to divide the plaintext into groups of 6 according to the length of the key

shesel|lsseas|hellsb|ythese|ashore

Then the 6 letters of each group are encrypted and transformed, you can get:

EESLSH | SALSES | LSHSES | HSYEET | HRAEOS

Decryption works in the same way, except that permutation is replaced by π − 1 π^{-1}Pi1

Code

package com.slp.cryptography;

/**
 * @ClassName PermutationSipher
 * @Description 置换密码
 * @Author sanglp
 * @Date 2020/12/1 8:31
 * @Version 1.0
 **/
public class PermutationSipher {
    
    

    static int[] key = {
    
    3,5,1,6,4,2};

    public static void main(String[] args) {
    
    
        encrypt("shesellsseashellsbytheseashore");
    }

    /**
     * 加密函数
     * 解密函数同理 不再重写
     * @param resource
     */
    private static void encrypt(String resource){
    
    
        char[] resarr = resource.toUpperCase().toCharArray();
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < resarr.length/key.length; i++) {
    
    
            for (int j = 0; j <key.length ; j++) {
    
    
                result.append(resarr[i*key.length+key[j]-1]);//这里需要注意一下 数组下标从0开始 否则会数组越界
            }
        }
        System.out.println(result);

    }
}

Guess you like

Origin blog.csdn.net/weixin_51656605/article/details/110421527