【发布时间】:2017-02-11 09:37:36
【问题描述】:
我正在尝试学习和测试 java 1.6 加密/解密 API。我想知道我做错了什么以及我在知识方面缺少什么。
在下面的代码中,我创建了两个密码:一个用于加密,另一个用于解密。当我使用这些密码时,我用不同的 SecretKey 初始化它们,但我仍然能够得到相同的值。这是为什么呢?
String algorithm = "DES";
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
byte[] encBytes = "12345678".getBytes("UTF8");
byte[] decBytes = "56781234".getBytes("UTF8");
DESKeySpec keySpecEncrypt = new DESKeySpec(encBytes);
DESKeySpec keySpecDecrypt = new DESKeySpec(decBytes);
SecretKey keyEncrypt = keyFactory.generateSecret(keySpecEncrypt);
SecretKey keyDecrypt = keyFactory.generateSecret(keySpecDecrypt);
Cipher cipherEncrypt = Cipher.getInstance(algorithm);
Cipher cipherDecrypt = Cipher.getInstance(algorithm);
String input = "john doe";
cipherEncrypt.init(Cipher.ENCRYPT_MODE, keyEncrypt);
byte[] inputBytes = cipherEncrypt.doFinal(input.getBytes());
System.out.println("inputBytes: " + new String(inputBytes));
cipherDecrypt.init(Cipher.DECRYPT_MODE, keyDecrypt);
byte[] outputBytes = cipherDecrypt.doFinal(inputBytes);
System.out.println("outputBytes: " + new String(outputBytes));
【问题讨论】:
-
这里也有一个非常好的 RSA 加密教程:javamex.com/tutorials/cryptography/rsa_encryption.shtml
标签: java encryption