输出结果相同

时间:2018-03-16 16:35:05

标签: java algorithm encryption cypher

我试图运行此代码,但它提供相同的输出: 我要做的是要求用户输入要加密的文本。然后输入他想用来加密128,192或256的密钥。但是当我输入任何内容时我测试它会给出相同的输出:( 这是我试图打电话的方法

package test;

public class MARS {
    public static byte[] encrypt(byte[] in,byte[] key){
        K = expandKey(key);
        int lenght=0;
        byte[] padding = new byte[1];
        int i;
        lenght = 16 - in.length % 16;
        padding = new byte[lenght];
        padding[0] = (byte) 0x80;

        for (i = 1; i < lenght; i++)
            padding[i] = 0;

        byte[] tmp = new byte[in.length + lenght];
        byte[] bloc = new byte[16];

        int count = 0;

        for (i = 0; i < in.length + lenght; i++) {
            if (i > 0 && i % 16 == 0) {
                bloc = encryptBloc(bloc);
                System.arraycopy(bloc, 0, tmp, i - 16, bloc.length);
            }
            if (i < in.length)
                bloc[i % 16] = in[i];
            else{
                bloc[i % 16] = padding[count % 16];
                count++;
            }
        }
        if(bloc.length == 16){
            bloc = encryptBloc(bloc);
            System.arraycopy(bloc, 0, tmp, i - 16, bloc.length);
        }

        return tmp;
    }
}

这是调用方法的类

package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Call {
    public static void main(String[] args) throws Exception {
        byte[] array = "going to encrypt".getBytes();
        byte[] key = "the key you want to use".getBytes();
        byte[] encryptBloc = MARS.encrypt(array,key);
        BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
        String plainText = userInput.readLine();
        System.out.println("Enter Text that you want to Encrypt: " + plainText);

        BufferedReader ke = new BufferedReader(new InputStreamReader(System.in));
        String kee = userInput.readLine();
        System.out.println("Enter The Key you want to use to encrypt this message: " + new String(key));
        System.out.println("plain Text: "+ plainText);
        System.out.println("Encrypted Text: " + new String(encryptBloc));
    }
}

1 个答案:

答案 0 :(得分:1)

你的代码只是扁平化而没有多大意义。您将字符串文字的字节作为明文和密钥,并且(基本上)忽略了用户输入。您还要创建多个未使用的输入流,并在奇怪的时候提示用户输入。

这是它应该是什么样子:

// Create input reader
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));

// Prompt, then wait and get user input for the plaintext 
System.out.println("Enter Text that you want to encrypt:");
String plainText = userInput.readLine();

// Prompt, then wait and get user input for the key
System.out.println("Enter the key:");
String key = userInput.readLine();

// Actually encrypt it
byte[] encrypted = MARS.encrypt(plainText.getBytes(), key.getBytes());

// Print encrypted and unencrypted
System.out.println("Plain text: " + plainText);
System.out.println("Encrypted Text: " + new String(encrypted));