Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Security
Expertise: Beginner
Aug 10, 1999

Encryption Classes

Question:
Are there any standard classes for performing one-way encryption of strings (e.g., passwords) in Java, similar to crypt() on Unix systems?

Answer:
The Java core APIs do not include an implementation of the DES encryption used by the Unix crypt() function. However, one-way encryption functionality, in the form of message digests, such as MD5, is provided. In fact, MD5 is the standard password encryption algorithm on some of the free BSD distributions and the option of using MD5 is available on most Linux distributions.

The java.security package contains the MessageDigest class, which can be used to perform one-way encryption. MessageDigests cannot be directly instantiated and are instead created by calling the getInstance() factory method. Encryption is performed by passing as an argument to the digest() method the raw bytes of a string. The accompanying program demonstrates how to do this. It prints out the MD5 digest of each of its arguments on a separate line.

import java.security.*;

/**
 * Prints to standard output the MD5 digest of its arguments, each on
 * a separate line.
 */
public class MD5Digest {
  private MessageDigest __md5;
  private StringBuffer __digestBuffer;

  public MD5Digest() throws NoSuchAlgorithmException {
    __md5 = MessageDigest.getInstance("MD5");
    __digestBuffer = new StringBuffer();
  }

  public String md5crypt(String password) {
    int index;
    byte[] digest;

    __digestBuffer.setLength(0);
    digest = __md5.digest(password.getBytes());

    for(index = 0; index < digest.length; ++index)
      __digestBuffer.append(Integer.toHexString(digest[index] & 0xff));

    return __digestBuffer.toString();
  }

  public static final void main(String[] args) {
    MD5Digest md5;
    int argc;

    if(args.length < 1) {
      System.err.println("Usage: MD5Digest [password] ...");
      return;
    }

    try {
      md5 = new MD5Digest();
    } catch(NoSuchAlgorithmException e) {
      e.printStackTrace();
      return;
    }

    for(argc = 0; argc < args.length; ++argc)
      System.out.println(md5.md5crypt(args[argc]));
    
  }
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date