Question

when i reviewed the code, i saw someone use the strategy about the key generation, the first part of IV are always the same, and the second half is different based on the machine ID (it may be hard for others to get the ID). Then it is used to generate the encryption key, like following example:

         public static final String constant = "1234";

         String key = constant + (machine ID);


         SecretKeySpec sks = new SecretKeySpec(key.getBytes(), "DES");

         String result = sks.toString();

Is it a kind of hard coded password? I am not sure whether it is secure? If not, is it high risky?

Thank you very much.

Was it helpful?

Solution

This is insecure because you are using a non-random key, and you're also using an insecure encryption algorithm (DES). You need to use a secure random generation function/class like SecureRandom, and you need to pick a secure algorithm like AES or TwoFish

Here's an example from JavaDigest showing proper use of class SecureRandom:

package random;

import java.security.SecureRandom;

/**
 * A Simple Example to generate secure random numbers using
 * java.security.SecureRandom class.
 * 
 */
public class SecureRandomGenerator {
  public static void main(String[] args) {

    // Get the instance of SecureRandom class with specified PRNG algorithm
    SecureRandom secureRandom = new SecureRandom();

    // You can use the getInstance() of the Secure Random class to create an object of SecureRandam
    // where you would need to specify the algorithm name.
    // SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");

    // Display the algorithm name
    System.out.println("Used algorithm: " + secureRandom.getAlgorithm());

    // You also specify the algorithm provider in the getInstance() method
    // SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");

    // Display the Provider
    System.out.println("Provider: " + secureRandom.getProvider());

    // A call to the setSeed() method will seed the SecureRandom object.
    // If a call is not made to setSeed(),
    // The first call to nextBytes method will force the SecureRandom object to seed itself.

    // Get 10 random numbers
    System.out.println("Random Integers generated using SecureRandom");
    for (int i = 0; i < 10; i++) {
      System.out.println(secureRandom.nextInt());
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top