给出以下示例:
String f="A000000000000000";
FileInputStream fis = new FileInputStream("C:\\Users\\original.txt");
byte[] bytes = DatatypeConverter.parseHexBinary(f);
SecretKey key = new SecretKeySpec(bytes, 0, bytes.length, "DES");
String strDataToEncrypt = new String();
String strCipherText = new String();
String strDecryptedText = new String();
try{
Cipher desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE,key);
//read from file and transform to String
try{
builder = new StringBuilder();
int ch;
while((ch = fis.read()) != -1){
builder.append((char)ch);
}
}catch (IOException e){
}
byte[] byteDataToEncrypt = builder.toString().getBytes();
byte[] byteCipherText = desCipher.doFinal(byteDataToEncrypt);
strCipherText = new BASE64Encoder().encode(byteCipherText);
System.out.println(strCipherText);
每次使用相同的 key 值 i 编译时,加密的数据都是不同的,我尝试了不同的代码,但加密的数据始终相同,这里出了什么问题?
最佳答案
documentation for javax.crypto.Cipher.init部分说:
If this cipher requires any algorithm parameters that cannot be derived from the given key, the underlying cipher implementation is supposed to generate the required parameters itself (using provider-specific default or random values)
DES CBC(密码 block 链接)模式需要初始化 vector (IV)。如果您不提供(您不应该提供,因为它会打开 dictionary attacks ),则会生成一个随机的。
但是如果您希望每次加密的数据都相同,则需要使用 IvParameterSpec
指定 IV:
byte[] iv = DatatypeConverter.parseHexBinary("0000000000000000");
IvParameterSpec ips = new IvParameterSpec(iv);
desCipher.init(Cipher.ENCRYPT_MODE, key, ips);
如果您确实让它生成随机 IV,您可以使用 desCipher.getIV()
检索生成的 IV。
关于java - 使用 DES 加密数据 - JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22185728/