我想使用 PBE 加密我的数据。到目前为止,我已经编写了以下代码:
moteurCryptage = Cipher.getInstance("PBEWithMD5AndDES");
PBEKeySpec spécifClé=new PBEKeySpec(mdp.toCharArray());
SecretKeyFactory usineàClefs=SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey clé=null;
try {
clé = usineàClefs.generateSecret(spécifClé);
} catch (InvalidKeySpecException ex) {
Logger.getLogger(DiskUtilView.class.getName()).log(Level.SEVERE, null, ex);
}
moteurCryptage.init(Cipher.ENCRYPT_MODE,clé);
byte[] paramètresEncodage;
try {
paramètresEncodage=moteurCryptage.getParameters().getEncoded();
} catch (IOException ex) {
paramètresEncodage=null;
}
destination=moteurCryptage.update(source1.getBytes());
destination=moteurCryptage.doFinal(source2.getBytes());
moteurCryptage.init(Cipher.DECRYPT_MODE,clé,paramètresEncodage);
source=new String(moteurCryptage.doFinal(destination));
加密似乎有效(我没有收到任何错误,无论是在编译还是执行期间),但用于解密的Cipher
对象的初始化不接受javax.crypto。 SecretKey
类(编译错误)。相反,它要求 java.security.key
。
我能做什么?
预先感谢您花时间帮助我。
最佳答案
问题出在线路上
moteurCryptage.init(Cipher.DECRYPT_MODE, cle, parametresEncodage);
应该是
moteurCryptage.init(Cipher.DECRYPT_MODE, cle, moteurCryptage.getParameters());
此外,正如您所指出的,它不适用于某些字符串(仅适用于那些非常短的字符串)。问题是,当您调用 update()
时,它会将一些数据保存到生成的 byte[]
中。当您对同一个变量调用 doFinal()
时,它会覆盖数据并且它们将永远丢失。 doFinal()
方法不会再次执行所有加密操作,它只执行剩余部分!
这意味着,你
- 在处理源字符串之前必须连接它们
- 或者您必须在
update()
之后保留destination
,为doFinal()
创建destination2
,然后两者都以相同的方式解密 -update()
destination
和doFinal()
destination2
- 或者您可以创建
destination
和destination2
,将它们(例如 here's how )连接到单个completeDestination
数组中并解密doFinal()
就可以了。
如果您想查看上述所有内容的代码,只需说一句话即可。
关于java - 密码学 : using Password Based Encryption (PBE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9928409/