我正在尝试使用具有两个不同密钥的三重 DES 加密数据,因此给定两个密钥 k1 和 k2,密文将是 Ek1(Dk2(Ek1(plaintext))),其中 E 是加密和 D 解密。我正在尝试使用 java 中的 DES 算法来模拟这一点。这是代码:
public static void main(String[] args) {
SecretKey k1 = generateDESkey();
SecretKey k2 = generateDESkey();
String firstEncryption = desEncryption("plaintext", k1);
String decryption = desDecryption(firstEncryption, k2);
String secondEncryption = desEncryption(decryption, k1);
}
public static SecretKey generateDESkey() {
KeyGenerator keyGen = null;
try {
keyGen = KeyGenerator.getInstance("DES");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
}
keyGen.init(56); // key length 56
SecretKey secretKey = keyGen.generateKey();
return secretKey;
}
public static String desEncryption(String strToEncrypt, SecretKey desKey) {
try {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, desKey);
String encryptedString = Base64.encode(cipher.doFinal(strToEncrypt.getBytes()));
return encryptedString;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public static String desDecryption(String strToDecrypt, SecretKey desKey) {
try {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, desKey);
String decryptedString = new String(cipher.doFinal(Base64.decode(strToDecrypt)));
return decryptedString;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
} catch (Base64DecodingException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
我有这个错误:javax.crypto.BadPaddingException:在这行代码尝试解密时,给定最终块未正确填充:
String decryptedString = new String(cipher.doFinal(Base64.decode(strToDecrypt)));
您能帮我解决这个问题吗,或者您知道使用三重 DES 和两个不同密钥(总密钥长度为 128 位)加密数据的直接方法吗?我没有找到任何算法,所以我尝试使用简单的 DES 来模拟它。