简体   繁体   中英

Encrypted Data with DES - JAVA

Given the following example:

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);

the encrypted data is different everytime I compile with the same key value i , i tried different codes and the encrypted data was always the same , what's wrong here ?

The documentation for javax.crypto.Cipher.init says, in part:

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 (Cipher Block Chaining) mode requires an Initialization Vector (IV). If you do not provide one (and you should not, because it opens you up to dictionary attacks ), a random one will be generated.

But if you want the encrypted data to be the same every time, you need to specify the IV using an IvParameterSpec :

byte[] iv = DatatypeConverter.parseHexBinary("0000000000000000");
IvParameterSpec ips = new IvParameterSpec(iv);
desCipher.init(Cipher.ENCRYPT_MODE, key, ips);

If you do let it generate a random IV, you can retrieve the generated IV with desCipher.getIV() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM