[Cryptography Principles and Practice] (4) Java code implementation of Virginia cipher

Vigenere Cipher

Please reprint the source

Whether it is a shift password or a substitution password, once the secret key is selected, the number corresponding to each letter is encrypted and transformed into a corresponding unique number. We call this a single-table substitution password, and this article is about a multi-table substitution password.

definition

Let m be a positive integer, define P=C=K=(Z 26 ) m , and define E k (x 1 ,x 2 , for any secret key K=(k 1 ,k 2 ,k 3 …k m ) X . 3 ... X m ) = (X . 1 + K . 1 , X . 3 + K 2 ... X m + K m ), and D K (Y . 1 , Y 2 ... Y K ) = (Y . 1 -k . 1 , Y 2 - k 2 …y m -k m )

All the above calculations are performed on Z 26 .

Corresponding to the previous alphabet, each key K is equivalent to a string of length m, called a key word. The Virginia password encrypts m name letters at a time.

The size of the key space of the Virginia cipher is 26 m , so even if the value of m is small, it takes a long time to use the exhaustive key. Generally speaking, multiple table substitution passwords are more secure than single table substitution passwords.

Give a chestnut

Assuming m=6, the key word is CIPHER, which corresponds to the following number string (2,8,15,7,4,17), the plaintext to be encrypted is: encode and decode, the secret key is mykey
Insert picture description here

Code

package com.slp.cryptography;

/**
 * @ClassName VigenereCipher
 * @Description 维吉尼亚密码
 * @Author sanglp
 * @Date 2020/11/30 15:55
 * @Version 1.0
 **/
public class VigenereCipher {
    
    
    static int [] arr = {
    
    12,24,10,4,24};
    public static void main(String[] args) {
    
    
        encrypt("encodeanddecode");
        decrypt("QLMSBQYXHBQAYHC");
    }

    /**
     * 加密函数
     * @param resource
     */
    public static void encrypt(String resource){
    
    
        char [] souarr = resource.toUpperCase().toCharArray();
        int len = arr.length;//密钥串的长度
        StringBuilder result = new StringBuilder();
        for(int i=0;i<souarr.length;i++){
    
    
            int temp =(souarr[i]-'A'+arr[i%len])%26<0?(souarr[i]-'A'+arr[i%len])%26+26:(souarr[i]-'A'+arr[i%len])%26;
            result.append((char)('A'+temp));
        }
        System.out.println(result.toString());
    }

    /**
     * 解密函数
     * @param resource
     */
    public static void decrypt(String resource){
    
    
        char [] souarr = resource.toUpperCase().toCharArray();
        int len = arr.length;//密钥串的长度
        StringBuilder result = new StringBuilder();
        for(int i=0;i<souarr.length;i++){
    
    
            int temp =(souarr[i]-'A'-arr[i%len])%26<0?(souarr[i]-'A'-arr[i%len])%26+26:(souarr[i]-'A'-arr[i%len])%26;
            result.append((char)('A'+temp));
        }
        System.out.println(result.toString());
    }
}

Guess you like

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