我在互联网上搜索了Java的三重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=
抱歉我的英语很差。
感谢您的帮助
答案 0 :(得分:0)
cipher.init(mode,key)
生成随机IV。这实际上是最安全的使用方式;你应该使用.getIV()
并将其与加密文本一起返回(这也是自动的; Java将其添加到cryptostream的前几个字节,这是他们解密的方式)。不同的IV会将结果更改为不同的密钥,但它不需要保密,只是为了确保相同的内容不会加密。
要强制使用IV进行比较算法,或使用未包含的已知密码进行解密,请使用cipher.init(mode,key,new IvParameterSpec(iv))