01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: *
17: */
18:
19: /* $Id: Password.java 473861 2006-11-12 03:51:14Z gregor $ */
20:
21: package org.apache.lenya.ac;
22:
23: import java.security.MessageDigest;
24:
25: /**
26: * Encrypt plain text password
27: * Example: "message digest" becomes "f96b697d7cb7938d525a2f31aaf161d0" (hexadecimal notation (32 characters))
28: */
29: public class Password {
30:
31: /**
32: * Encrypt plain text password
33: *
34: * @param plain plain text password
35: * @return encrypted password
36: */
37: public static String encrypt(String plain) {
38: return getMD5(plain);
39: }
40:
41: /**
42: * Returns the MD5 representation of a string.
43: * @param plain The plain string.
44: * @return A string.
45: */
46: public static String getMD5(String plain) {
47: MessageDigest md = null;
48: try {
49: md = MessageDigest.getInstance("MD5");
50: } catch (java.security.NoSuchAlgorithmException e) {
51: throw new RuntimeException(e);
52: }
53: return stringify(md.digest(plain.getBytes()));
54: }
55:
56: /**
57: * Converts a byte buffer to a string.
58: * @param buf The buffer.
59: * @return A string.
60: */
61: private static String stringify(byte[] buf) {
62: StringBuffer sb = new StringBuffer(2 * buf.length);
63:
64: for (int i = 0; i < buf.length; i++) {
65: int h = (buf[i] & 0xf0) >> 4;
66: int l = (buf[i] & 0x0f);
67: sb.append(new Character((char) ((h > 9) ? (('a' + h) - 10)
68: : ('0' + h))));
69: sb.append(new Character((char) ((l > 9) ? (('a' + l) - 10)
70: : ('0' + l))));
71: }
72:
73: return sb.toString();
74: }
75: }
|