到目前为止我的代码是:
public class TripleDES {
/**
* @param args the command line arguments
* @throws java.security.NoSuchAlgorithmException
* @throws javax.crypto.NoSuchPaddingException
* @throws java.security.InvalidKeyException
* @throws javax.crypto.IllegalBlockSizeException
* @throws javax.crypto.BadPaddingException
*/
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
//Encrypt: C = EK3(DK2(EK1(P)))
//Decrypt: P = DK3(EK2(DK1(C)))
Scanner sc = new Scanner(System.in);
//Generate key for DES
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
SecretKey secretKey = keyGenerator.generateKey();
SecretKey secretKey2 = keyGenerator.generateKey();
SecretKey secretKey3 = keyGenerator.generateKey();
//Text Enc & Dec
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
//enter msg
System.out.print("Enter a string: ");
String x= sc.nextLine();
//enc
cipher.init(Cipher.ENCRYPT_MODE,secretKey);
byte[] message = x.getBytes();//text
byte[] messageEnc = cipher.doFinal(message);//encryption with key1
cipher.init(Cipher.DECRYPT_MODE,secretKey2);
byte[] deck2 = cipher.doFinal(messageEnc);//decryption with key2
cipher.init(Cipher.ENCRYPT_MODE,secretKey3);
byte[] messageEnc1 = cipher.doFinal(deck2);//encryption with key3
System.out.println("Cipher Text: " + new String(messageEnc1));
//dec
cipher.init(Cipher.DECRYPT_MODE,secretKey3);
byte[] dec = cipher.doFinal(messageEnc1);//decryption with key1
cipher.init(Cipher.ENCRYPT_MODE,secretKey2);
byte[] messageEnc2 = cipher.doFinal(dec);//encryption with key2
cipher.init(Cipher.DECRYPT_MODE,secretKey);
byte[] deck3 = cipher.doFinal(messageEnc2);//decryption with key3
System.out.println("Plain Text: " + new String(deck3));
}
}我知道错误:
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:991)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:847)
at com.sun.crypto.provider.DESCipher.engineDoFinal(DESCipher.java:314)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at tripledes.TripleDES.main(TripleDES.java:45)我的猜测是,当我尝试在第45行用一个不同的密钥解密时,它给出了上面的错误,这是因为加密的文本比生成的密钥大,但我不太确定。
有人能帮忙吗?因为我找不出问题。
发布于 2021-04-26 21:06:49
我指的是最初发布的带有cipher、cipher2和cipher3实例的代码:问题在于cipher2和cipher3的填充。只有cipher才能使用PKCS5Padding,cipher2和cipher3必须应用NoPadding。
生成的密文实际上与3 3DES生成的密文相同,条件是将secretKey、secretKey2和secretKey3的级联字节用作3 3DES密钥。
顺便说一句,欧洲央行是一种不安全的模式,s. here.
关于评论意见:
有关使用字符集编码的密文的解码,请参见例如。关于缺少的编码规范,例如。
https://stackoverflow.com/questions/67273314
复制相似问题