Jump to Real's How-to Main page

Encrypt a password

Message digests are secure one-way hash functions that take arbitrary-sized data and output a fixed-length hash value.
public class CryptoUtils {

  public static void main(String arg[]) {
    try {
      // quick way to do input from the keyboard, now deprecated...
      java.io.StreamTokenizer Input=new java.io.StreamTokenizer(System.in);
      //
      System.out.print("Input your secret password : ");
      Input.nextToken();
      String secret = new String(CryptoUtils.encrypt(Input.sval));
      System.out.println("the encrypted result : " + secret);
      boolean ok = true;
      String s = "";
      while (ok) {
          System.out.print("Now try to enter a password : " );
          Input.nextToken();
          s = new String(CryptoUtils.encrypt(Input.sval));
          if (secret.equals(s)){
             System.out.println("You got it!");
             ok = false;
             }
          else
             System.out.println("Wrong, try again...!");
      }
    }
    catch (Exception e){
      e.printStackTrace();
    }

  }

  public static byte[] encrypt(String x)   throws Exception
  {
     java.security.MessageDigest d =null;
     d = java.security.MessageDigest.getInstance("SHA-1");
     d.reset();
     d.update(x.getBytes());
     return  d.digest();
  }
}
The output is :
Input your secret password : howto
the encrypted result : ûóbf-m¦esd
Now try to enter a password : Howto
Wrong, try again...!
Now try to enter a password : howTo
Wrong, try again...!
Now try to enter a password : howto
You got it!

If you need to save the encrypted string into a file, you may need to transform it into a hexadecimal string because the encrypted string may contains non-printable characters.

One technique is to encode using Base64 the encrypted string.

sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String encoded=encoder.encode(secret.getBytes());
// encoded is a string with printable characters.

Or we can simply convert the byte array into an hexadecimal string:

public class StringUtils {

public static void main(String arg[]) {
   byte b[] = { 7, 42, -1, -127 }; // 7, 2A, FF, 81

   System.out.println(byteArrayToHexString(b));
   /*
      output :
      072AFF81
   */
   b = hexStringToByteArray(byteArrayToHexString(b));
   for (int i = 0; i < b.length; i++) {
     System.out.println(b[i]);
   }
   /*
   output :
   7
   42
   -1
   -127
   */
   
}

public static String byteArrayToHexString(byte[] b){
    StringBuffer sb = new StringBuffer(b.length * 2);
    for (int i = 0; i < b.length; i++){
      int v = b[i] & 0xff;
      if (v < 16) {
        sb.append('0');
      }
      sb.append(Integer.toHexString(v));
    }
    return sb.toString().toUpperCase();
}

public static byte[] hexStringToByteArray(String s) {
    byte[] b = new byte[s.length() / 2];
    for (int i = 0; i < b.length; i++){
      int index = i * 2;
      int v = Integer.parseInt(s.substring(index, index + 2), 16);
      b[i] = (byte)v;
    }
    return b;
  }
}

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]