001 /*
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements. See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership. The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License. You may obtain a copy of the License at
010 *
011 * http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing,
014 * software distributed under the License is distributed on an
015 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
016 * KIND, either express or implied. See the License for the
017 * specific language governing permissions and limitations
018 * under the License.
019 *
020 */
021 package org.apache.qpid.management.common.sasl;
022
023 import java.io.IOException;
024 import java.io.UnsupportedEncodingException;
025 import java.security.MessageDigest;
026 import java.security.NoSuchAlgorithmException;
027
028 import javax.security.auth.callback.Callback;
029 import javax.security.auth.callback.CallbackHandler;
030 import javax.security.auth.callback.NameCallback;
031 import javax.security.auth.callback.PasswordCallback;
032 import javax.security.auth.callback.UnsupportedCallbackException;
033
034
035 public class UsernameHashedPasswordCallbackHandler implements CallbackHandler
036 {
037 private String user;
038 private char[] pwchars;
039
040 public UsernameHashedPasswordCallbackHandler(String user, String password) throws Exception
041 {
042 this.user = user;
043 this.pwchars = getHash(password);
044 }
045
046 public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
047 {
048 for (int i = 0; i < callbacks.length; i++)
049 {
050 if (callbacks[i] instanceof NameCallback)
051 {
052 NameCallback ncb = (NameCallback) callbacks[i];
053 ncb.setName(user);
054 }
055 else if (callbacks[i] instanceof PasswordCallback)
056 {
057 PasswordCallback pcb = (PasswordCallback) callbacks[i];
058 pcb.setPassword(pwchars);
059 }
060 else
061 {
062 throw new UnsupportedCallbackException(callbacks[i]);
063 }
064 }
065 }
066
067
068 private void clearPassword()
069 {
070 if (pwchars != null)
071 {
072 for (int i = 0 ; i < pwchars.length ; i++)
073 {
074 pwchars[i] = 0;
075 }
076 pwchars = null;
077 }
078 }
079
080 protected void finalize()
081 {
082 clearPassword();
083 }
084
085 public static char[] getHash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException
086 {
087 byte[] data = text.getBytes("utf-8");
088
089 MessageDigest md = MessageDigest.getInstance("MD5");
090
091 for (byte b : data)
092 {
093 md.update(b);
094 }
095
096 byte[] digest = md.digest();
097
098 char[] hash = new char[digest.length ];
099
100 int index = 0;
101 for (byte b : digest)
102 {
103 hash[index++] = (char) b;
104 }
105
106 return hash;
107 }
108 }
|