KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > user > Digest


1 /*
2  * This file is part of "SnipSnap Wiki/Weblog".
3  *
4  * Copyright (c) 2002 Stephan J. Schmidt, Matthias L. Jugel
5  * All Rights Reserved.
6  *
7  * Please visit http://snipsnap.org/ for updates and contact.
8  *
9  * --LICENSE NOTICE--
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  * --LICENSE NOTICE--
24  */

25 package org.snipsnap.user;
26
27 import java.security.MessageDigest JavaDoc;
28 import java.security.NoSuchAlgorithmException JavaDoc;
29
30 /**
31  * Digest handler for encrypting passwords.
32  * @author Matthias L. Jugel
33  * @version $Id: Digest.java 951 2003-08-28 13:31:24Z leo $
34  */

35 public class Digest {
36   private static MessageDigest JavaDoc digest;
37
38   static {
39     try {
40       digest = MessageDigest.getInstance("SHA1");
41     } catch (NoSuchAlgorithmException JavaDoc e) {
42       System.err.println("UserManager: unable to load digest algorithm: " + e);
43       digest = null;
44     }
45   }
46
47   public static String JavaDoc getDigest(String JavaDoc s) {
48     if (digest != null && s != null) {
49       return digestToHexString(digest.digest(s.getBytes()));
50     }
51     return "";
52   }
53
54   /**
55    * Compare a password with an encryped password.
56    */

57   public static boolean authenticate(String JavaDoc password, String JavaDoc encrypted) {
58     return encrypted.equals(getDigest(password));
59   }
60
61   /**
62    * Make a hexadecimal character string out of a byte array digest
63    */

64   public static String JavaDoc digestToHexString(byte[] digest) {
65     byte b = 0;
66     StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
67
68     for (int i = 0; i < digest.length; ++i) {
69       b = digest[i];
70       int value = (b & 0x7F) + (b < 0 ? 128 : 0);
71       buffer.append(value < 16 ? "0" : "");
72       buffer.append(Integer.toHexString(value).toUpperCase());
73     }
74     return buffer.toString();
75   }
76 }
77
Popular Tags