我正在制作一个可以使用各种方法加密和解密文本的程序,对于DES加密,我的程序通过执行生成密钥
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
提供的文本字符串已成功加密,使用toString()方法转换为字符串的键看起来像这样
com.sun.crypto.provider.DESKey@18738
但是,当我提供相同的密钥(toString one)时,就像这样
byte[] decodedKey = com.sun.crypto.provider.DESKey@18738.getBytes();
它说"密钥长度无效:36字节" 这很奇怪,因为相同的密钥用于加密和解密相同的文本字符串。
以下是我加密的方式:
try {
Cipher desCipher;
byte[] decodedKey = pass.getText().getBytes();//the password is supplied here
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "DES");
desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
byte[] text = input.getText().getBytes();
desCipher.init(Cipher.DECRYPT_MODE, originalKey);
byte[] textDecrypted = desCipher.doFinal(input.getText().getBytes());
output.setText(Arrays.toString(textDecrypted));
} catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException ex) {
Error(ex.getMessage());
Logger(ex.getMessage());
}
以下是我的解密方式:
try {
Cipher desCipher;
byte[] decodedKey = pass.getText().getBytes();
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "DES");
desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
byte[] text = input.getText().getBytes();
desCipher.init(Cipher.DECRYPT_MODE, originalKey);
byte[] textDecrypted = desCipher.doFinal(input.getText().getBytes());
output.setText(Arrays.toString(textDecrypted));
} catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException ex) {
Error(ex.getMessage());
Logger(ex.getMessage());
}
出于某种原因,即使我使用netbeans来修复它,代码也很难缩进,可能是因为它像10个开关块一样......
感谢您的帮助!