Public feed #601531

Stuff

public text v1 · immutable
Raw Edit
·published 2007-07-03 15:43 UTC
rendered paste body
  public static String md5MessageDigest (String plainText)
  {
    synchronized (md5)
    {
      // If message digest object wasn't initialized, then we're not
      // using this type of secure encoding.
      if (md5 == null) return plainText;

      // MessageDigest needs a byte[];
      byte[] plainBytes = null;

      try
      {
        plainBytes = plainText.getBytes (charSet);
      }
      catch (UnsupportedEncodingException e)
      {
        System.err.println ("MD5 Digest UnsupportedEncodingException: " + e.getMessage());
        return null;
      }

      // This should be 16 bytes.
      byte[] digestBytes = md5.digest (plainBytes);

      // We use the digest in ASCII Hex format (ASCII-encoded nibbles).  Convert.
      char[] asciiDigestBytes = new char[md5OutputLength];
      for (int i = 0; i < (md5OutputLength / 2); i++)
      {
        int outputOffset = i * 2;
        byte thisByte = digestBytes[i];
        char upperNibble = toAsciiHexNibble( (thisByte & 0xF0) >> 4 );
        char lowerNibble = toAsciiHexNibble( thisByte & 0x0F );
        asciiDigestBytes[outputOffset] = upperNibble;
        asciiDigestBytes[outputOffset + 1] = lowerNibble;
      }
      String result = new String(asciiDigestBytes);
      return result;
    }
  }