我正在尝试编写一个程序来加密和解密用户输入的String
。我的代码有效,但是每次运行程序时都不会生成更改的密钥。无论我输入什么,我都会得到相同的结果。我有什么想法可以改变这个?
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);
}
}
答案 0 :(得分:1)
我认为您错过了基于算法初始化密钥生成器的重要步骤。请参阅Java Docs on KeyGenerator init methods。
您的构造函数将被修改为:
keyGen = KeyGenerator.getInstance(algorithm);
keyGen.init(..); // your choice as to which one works best for your needs
symKey = keyGen.generateKey();