【发布时间】:2015-03-05 10:34:35
【问题描述】:
我正在开发一个需要我使用两个键的 Java 应用程序 从不同的字符串生成用于加密和解密。一 字符串来自用户,其他是主密钥。我在网上看了 并找到了一些关于它的参考资料。我真的很想要一些 帮助了解如何实现这一点。我会展示我现在拥有的。
正如您从代码中看到的那样,我使用了其他 stackoverflow 帖子中的一些代码并对其进行了一些修改。我只是不知道如何从 2 个字符串生成 2 个密钥,以及从哪里可以获得用于解密的 SecretKey desKey。
代码:
public class Encryption {
public void doStuff() {
String plaintext = "abc";
SecretKey k1 = generateDESkey();
SecretKey k2 = generateDESkey();
String firstEncryption = desEncryption(plaintext, k1);
String decryption = desDecryption(firstEncryption, k2);
String secondEncryption = desEncryption(decryption, k1);
System.out.println(firstEncryption);
System.out.println(decryption);
System.out.println(secondEncryption);
}
public static SecretKey generateDESkey() {
KeyGenerator keyGen = null;
try {
keyGen = KeyGenerator.getInstance("DESede");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
}
try {
assert keyGen != null;
keyGen.init(112); // key length 56
return keyGen.generateKey();
} catch (NullPointerException ex){
return null;
}
}
public static String desEncryption(String strToEncrypt, SecretKey desKey) {
try {
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, desKey);
return Base64.encode(cipher.doFinal(strToEncrypt.getBytes()));
} catch (NoSuchAlgorithmException | NoSuchPaddingException |
IllegalBlockSizeException | BadPaddingException |
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("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, desKey);
return new String(cipher.doFinal(Base64.decode(strToDecrypt)));
} catch (NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException
| InvalidKeyException | NoSuchPaddingException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
如果对此有任何困惑或疑问。请告诉我。
【问题讨论】:
-
那么现在的代码有什么问题呢?有像 BadPaddingException 这样的异常吗?
-
@ArtjomB。我将其更改为 DESede,但如何从字符串为 DESede 生成密钥?另外,我正在寻找如何使用 2 个密钥的组合解密?
-
另外,您似乎正在执行三重三重 DES。这是想要的吗?
-
请你编辑你的标题来描述你的问题,而不是你的目标。
-
@Duncan 老实说,我对密码学的实现不太了解,我想用纯字符串生成两个密钥,并将它们用于加密/解密。
标签: java encryption cryptography des