Java 加密和解密用户输入字符串

Java 加密和解密用户输入字符串,java,encryption,Java,Encryption,我正在尝试编写一个程序,对用户输入的字符串进行加密和解密。我的代码可以工作,但不会生成每次运行程序时都会更改的密钥。无论我键入什么,我都会得到相同的结果。我能做些什么来改变这一切 package SimpleCryptHandler; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import javax.cry

我正在尝试编写一个程序,对用户输入的
字符串进行加密和解密。我的代码可以工作,但不会生成每次运行程序时都会更改的密钥。无论我键入什么,我都会得到相同的结果。我能做些什么来改变这一切

package SimpleCryptHandler;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;

import java.util.Scanner;

public class SimpleCryptHandler {

    private Key symKey;
    private Cipher cipher; 

    public SimpleCryptHandler(String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException {               
        symKey = KeyGenerator.getInstance(algorithm).generateKey();     
        cipher = Cipher.getInstance(algorithm);
    }

    public byte[] encrypt(String toEncrypt) 
            throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        cipher.init(Cipher.ENCRYPT_MODE, symKey);
        byte[] inputBytes = toEncrypt.getBytes();
        return cipher.doFinal(inputBytes);
    }

    public String decrypt(byte[] toDecrypt) 
            throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        cipher.init(Cipher.DECRYPT_MODE, symKey);
        byte[] decrypt = cipher.doFinal(toDecrypt);
        String decrypted = new String(decrypt);
        return decrypted;
    }

    public static void main(String[] args) throws Exception {
        Scanner input = new Scanner (System.in);
        String encrypttype;

        System.out.println("What encrytion type would you like to use? (AES, Blowfish, DES, DESede, RC2)");
            encrypttype = input.nextLine();

        String algorithm = encrypttype;   //successfully tested with AES, Blowfish, DES, DESede, RC2
        SimpleCryptHandler cryptHandler = new SimpleCryptHandler(algorithm);

        Scanner input2 = new Scanner (System.in);
        String pw;

        System.out.println("What would you like to encrypt?");
            pw = input2.nextLine();

        String input1 = pw;

        //Encryption
        byte[] encryptedBytes = cryptHandler.encrypt(input1);
        System.out.println(encrypttype + " Encrypted result of " + pw + ": " + encryptedBytes);

        //Decryption
        String decryptedStr = cryptHandler.decrypt(encryptedBytes);
        System.out.println("Decrypted result of: " + decryptedStr);
    }
}

我认为您缺少了一个重要步骤,即基于该算法初始化密钥生成器。看

您的构造函数将被修改为:

keyGen = KeyGenerator.getInstance(algorithm);
keyGen.init(..); // your choice as to which one works best for your needs
symKey = keyGen.generateKey();