Delphi Clinic C++Builder Gate Training & Consultancy Delphi Notes Weblog Dr.Bob's Webshop
Hubert Klein Ikkink (aka Mr.Haki) - Communications Officer
 Mr.Haki's JBuilder Jar #34
See Also: JBuilder Papers

Encryption (ñIÂ훉ñ’Epîš:ç«)
When we are developing applications or applets, we sometimes want the user to give a password for security reasons. Then we need to be able to store this password somewhere in a safe way: we must encrypt the password. Once it is encrypted no one can decrypt the password, so we want to be using a one-way encryption.

In the java.security we can find the MessageDigest class. We can use this class to encrypt for example Strings. We can use MD5 and SHA encryption with this class. The following piece of code shows how to use this class:

  String encrypt = "Encrypt me!";
  MessageDigest digest = null;
  try {
    /*
     * Create a instance of the MessageDigest class.
     * We will be using SHA-1 as encryption algorithm.
     */
    digest = MessageDigest.getInstance("SHA-1");
  } catch (NoSuchAlgorithmException nsex) {
    /* do nothing, only print debug info */
    nsex.printStackTrace();
  }

  /*
   * Reset MessageDigest object
   */
  digest.reset();

  /*
   * Convert String to array of bytes
   */
  byte[] b = encrypt.getBytes();

  /*
   * And "feed" this array of bytes to the MessageDigest object
   */
  digest.update(b);

  /*
   * Get the resulting bytes after the encryption process
   */
  byte[] digestedBytes = digest.digest();
Because we are using one-way encryption, we must encrypt another String using the same algorithm and compare both values to see if they are match.


This webpage © 1997-2009 by Bob Swart (aka Dr.Bob - www.drbob42.com). All Rights Reserved.