【发布时间】:2012-10-18 14:30:18
【问题描述】:
我在互联网上搜索了 Java 的 Triple Des 算法实现。
我找到了很多解决方案并选择了一个(对我来说文档更好的那个)。 我测试并工作正常。
然后,我搜索了 Java 的 AES 算法实现。并找到了一个好的。与 Triple Des 算法的实现非常相似,但并不完全相同。
所以我想,如果我使用 AES 算法实现但将 Cipher 实例参数从“AES”更改为“DESede”,会附加什么? 我进行了更改,测试了代码并且工作正常。但是,它返回的字符串与我之前的 Triple Des 算法实现中返回的字符串不同。
所以,正如标题所说,我如何知道我是否使用了正确版本的 Triple Des 算法实现?
这是第一个实现:
public String encrypt(SecretKey key, String stringIn){
String outString = "";
if (stringIn.isEmpty() || stringIn.toUpperCase().equals("NULL")){
return "";
}
try {
if (key == null)
key = this.key;
InputStream in = new ByteArrayInputStream(stringIn.getBytes("UTF-8"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
// Create and initialize the encryption engine
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, key);
// Create a special output stream to do the work for us
CipherOutputStream cos = new CipherOutputStream(out, cipher);
// Read from the input and write to the encrypting output stream
byte[] buffer = new byte[2048];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
cos.write(buffer, 0, bytesRead);
}
cos.close();
// For extra security, don't leave any plaintext hanging around memory.
java.util.Arrays.fill(buffer, (byte) 0);
outString = out.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
return outString;
}
}
这是第二个:
public String encrypt(SecretKey key, String stringIn){
String outString = "";
if (stringIn.isEmpty() || stringIn.toUpperCase().equals("NULL")){
return "";
}
try {
if (key == null)
key = this.key;
Cipher ecipher = Cipher.getInstance("DESede");
ecipher.init(Cipher.ENCRYPT_MODE, key);
byte[] bytes = stringIn.getBytes("UTF8");
byte[] encVal = ecipher.doFinal(bytes);
outString = new sun.misc.BASE64Encoder().encode(encVal);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
return outString;
}
}
这是测试用例:
String In: 6985475896580019
String Returned when I Encripted with First code: Kœ¼i …€‡ä«‘]<žéù âpU
String Returned when I Encripted with Second code: w1ujopasjH6ccFKgUtOgansFNBtxbWe8YwDhso2pZN8=
对不起,我的英语不好。
感谢您的帮助
【问题讨论】:
-
那么,你是否也用这两个字符串测试了解密?我有一种预感,第一个代码会失败......
-
是的,两者都可以正常工作并返回相同的原始字符串
-
如果你想要相同的输出,你可以使用相同的密文字节编码。在第一个中,您使用 ByteArrayOutputStream 的 toString() 方法,这没有任何意义。在第二个中,您使用 base64 编码,这确实有意义。其他提示:永远不要使用默认值,例如
Cipher.getInstance("DESede")使用默认模式和默认填充。始终明确指定两者。总是。 -
@GregS 好的,很棒的信息。你能推荐我一些模式和填充吗?另外,您认为使用选项 2 是个好主意吗?谢谢
标签: java encryption tripledes