devxlogo

Encryption Classes

Encryption Classes

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

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

The java.securitypackage contains the MessageDigest class, which can be used to performone-way encryption. MessageDigests cannot be directly instantiated andare 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 programdemonstrates how to do this. It prints out the MD5 digest of each ofits 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]));      }}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist