package net.sourceforge.jsurveyor;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Encoder;

/**
 * Singleton class that handles the encryption of passwords.
 * 
 * @version 1.0
 * @author Claus Methmann Christensen
 * @author Anders Spliid Hansen
 * @author Esben Iversen Hansen
 * @author Lars H Jensen
 * @author Marcus Overheu
 * @author Thomas Ramdal
 * @author Peter Thomsen
 */
public final class PasswordService {
	
	// singleton
	private static PasswordService instance;

	/**
	 * Encrypts the String passed as argument using SHA encryption.
	 * @pre none
	 * @param plaintext String
	 * @return String
	 */
	public synchronized String encrypt(String plaintext)
		 {
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("SHA");
		} catch (NoSuchAlgorithmException e) {
		
		}
		try {
			md.update(plaintext.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
	
		}

		byte raw[] = md.digest(); 
		String hash = (new BASE64Encoder()).encode(raw); 
		return hash;
	} // end encrypt
	
	/**
	 * Method that returns a singleton instance of this class. If the class
	 * was already instantiated, this instantiation is returned.
	 * @pre none
	 * @return instance PasswordService
	 */
	public static synchronized PasswordService getInstance() 
	{
		if (instance == null) {
			instance = new PasswordService();
		}
		return instance;
	} // end getInstance
} // end class