/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.fw.security;


import javax.crypto.spec.SecretKeySpec;

import gov.va.med.fw.service.ServiceException;

/**
 * Encryption service to encrypt passwords using AES Symmetric algorithm as specified in the
 * configuration. Encrypted password is prefixed with alogorithm prefix 
 * for identification of encrypted passwords
 * 
 * Uses the generic implementation in the base class for encryption
 * @author DNS   KATIKM
 *
 */
public class PasswordEncryptionServiceImpl extends EncryptionServiceImpl
        implements PasswordEncryptionService {
    
    /**
     * Craete encryption service object
     */
    public PasswordEncryptionServiceImpl() {
        super();
    }

    /**
     * Encrypt password and return encrypted password
     * If the password already encrypted return as is
     */
    public String encryptPassword(String cleartext) throws ServiceException {
        //if the the text already encrypted returned as is
        if (cleartext.startsWith(AES_PREFIX)) {
            return cleartext;
        }
 		
        String newText = cleartext;
        String encrypted = encrypt(getSkeySpec(),null,newText,null);
        return getEncryptionPrefix()+encrypted;
    }

    public String decryptPassword(String encryptedText) 
    throws ServiceException {
    	
    	if ( encryptedText.startsWith(getEncryptionPrefix()) )
    	{
    		//remove the prefix.
    		encryptedText = encryptedText.substring(getEncryptionPrefix().length());
    	}
    	
    	return decrypt(getSkeySpec(),null,encryptedText);
    }
    
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
    }    
}
