小编典典
在更改代码之前先对其进行回答。
您正在尝试仅使用两个键而不是三个键来进行DESede。
这通常可能会奏效,但并非如您所写。问题是填充。在第二步中,您尝试使用不同于加密密钥的其他密钥解密密文,因此解密将失败超过256次中的255次,因为填充将是错误的(还因为您在其中使用Base64编码)没有必要)。
如果您确实想这样做,则必须解密而无需填充和Base64编码。好消息是,未编码的密文已经是块大小的倍数,因此不会阻止您使用"DES/ECB/NoPadding"。
public static void main(String[] args) {
// First I would like to create keys by giving Strings
SecretKey k1 = generateDESkey();
SecretKey k2 = generateDESkey();
// encryption
byte[] firstEncryption = desEncryption("plaintext".getBytes("UTF-8"), k1, false);
byte[] decryption = desDecryption(firstEncryption, k2, true);
byte[] secondEncryption = desEncryption(decryption, k1, true);
// decryption
byte[] firstDecryption = desDecryption(secondEncryption, k1, true);
byte[] encryption = desEncryption(firstDecryption, k2, true);
byte[] secondDecryption = desDecryption(encryption, k1, false);
System.out.println(new String(secondDecryption)); // plaintext
}
public static byte[] desEncryption(byte[] strToEncrypt, SecretKey desKey, boolean noPadding) {
try {
Cipher cipher = Cipher.getInstance(noPadding ? "DES/ECB/NoPadding" : "DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, desKey);
return cipher.doFinal(strToEncrypt);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static byte[] desDecryption(byte[] strToDecrypt, SecretKey desKey, boolean noPadding) {
try {
Cipher cipher = Cipher.getInstance(noPadding ? "DES/ECB/NoPadding" : "DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, desKey);
return cipher.doFinal(strToDecrypt);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
当以这种方式构造通用密钥时,这实际上是具有两个密钥的DESede的等效实现:
SecretKey k1 = generateDESkey();
SecretKey k2 = generateDESkey();
byte[] edeKeyBytes = new byte[24];
System.arraycopy(k1.getEncoded(), 0, edeKeyBytes, 0, 8);
System.arraycopy(k2.getEncoded(), 0, edeKeyBytes, 8, 8);
System.arraycopy(k1.getEncoded(), 0, edeKeyBytes, 16, 8);
edeKey = new SecretKeySpec(edeKeyBytes, "DESede");
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, edeKey);
System.out.println(Base64.encode(cipher.doFinal("plaintext".getBytes("UTF-8"))));
DESede使用三个密钥,我们将其称为k1,k2和k3。所有这些都串联到一个字节数组中。在您的情况下,第二次使用k1代替k3。
2020-11-19