Search code examples
javaencryptiondes

init of a Cipher object in Java


When encrypting data in java as following:

    SecureRandom sr = new SecureRandom();  
    DESKeySpec dks = new DESKeySpec(rawKeyData);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
    SecretKey key = keyFactory.generateSecret(dks);  
    Cipher cipher = Cipher.getInstance("DES");  
    cipher.init(Cipher.ENCRYPT_MODE, key, sr);  
    // why the sr is necessary to init a Cipher object?
    byte data[] = str.getBytes();  
    byte[] encryptedData = cipher.doFinal(data);

Why the a SecureRandom object sr is necessary to init a Cipher object? As for the decryption side there is also need an SecureRandom object which is not the same as the one generated in the encryption size. Is theseSecureRandom objects just for parity digit?


Solution

  • The SecureRandom object is optional. If you don't select one, Java will use a default source of randomness. See the documentation of this method to understand how one is selected.

    The Cipher Javadocs explains the purpose of this argument:

    If this cipher (including its underlying feedback or padding scheme) requires any random bytes (e.g., for parameter generation), it will get them from random.

    So, in your particular case, you are probably not making use of this item at all. Nothing in your DES usage will require random data (since you appear to be using ECB mode). If you were using CBC-mode, then I assume the IV would be randomly generated from the SecureRandom object.