Jack N
Jack N

Reputation: 334

How to hide password within JAR file

I am trying to make a Java program that requires a password. The problem is that a Java class or JAR file can be converted back to source code, so people can see the password by converting the program back to source code. How can I fix this?

Upvotes: 1

Views: 3868

Answers (2)

WJS
WJS

Reputation: 40034

Probably the best way is to protect the password is to use a one-way hash. I would recommend investigating the Secure Hash Algorithms (SHA). These are one-way hashes (aka cryptographic checksums) that generate, for all practical purposes, a unique hash for some given text or message. Store the hash in the JAR file and the use the same algorithm to hash the entered password. Compare that hash to the stored one for verification.

The down side to this is that it is not easy (or in some cases possible) to change the password.

The odds of generating identical hashes for different inputs is infinitesimal.

Here is one way it could be done using standard Java libraries.

      MessageDigest md = MessageDigest.getInstance("SHA-256");
      String password = "Password"; // password to be "stored"
      byte[] bytes = password.getBytes();

      md.update(bytes);
      byte[] digest = md.digest();

      // store the following string in the jar file
      String storedDigest = toHex(digest);

      // validation process
      String enteredPassword = "Password";
      md.update(enteredPassword.getBytes());
      System.out.println(toHex(md.digest()).equals(storedDigest) ? "Passed"
            : "Failed");

   //Convert array of bytes to a long hex string
   public static String toHex(byte[] digest) {
      StringBuilder sb = new StringBuilder();
      for (byte b : digest) {
         sb.append(Integer.toHexString((b >> 4) & 0xF));
         sb.append(Integer.toHexString(b & 0xF));
      }
      return sb.toString();
   }

Upvotes: 0

cameron1024
cameron1024

Reputation: 10136

You can't.

Even if you encrypt the password, the code to decrypt the password will be available in, and so will not prevent someone decompiling your application.

You have some options:

  • Put your password in an environment variable (accessible with System.getProperty("variable.name"))
  • Store the password in a file (still not great, but better than sources)
  • Access the password from a server, however, you are still required to make the user enter their creds for the server, and now you're left with the same problem.
  • Make the user enter a password every time they run the application

Upvotes: 2

Related Questions