Encryptying and Decrypting Passwords using the DES algorithm

From Kb

Jump to: navigation, search

Contact Article Author | Blog of Article Author | FirstPartners.net Home | LinkedIn profile of Author


See Also

How to Encrypt and Decrypt using the DES algorithm in Java

import org.apache.xerces.impl.dv.util.Base64;
 
import java.security.GeneralSecurityException;
import java.util.Properties;
 
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
 
 
public class EncryptDecrypt {
 
	private SecretKey desKey=null;
 
	public EncryptDecrypt(String secretString){
		desKey = new SecretKeySpec(secretString.getBytes(), "DES");
	}
 
	public void setSecretString(String newSecretString){
		desKey = new SecretKeySpec(secretString.getBytes(), "DES");
	}
 
	public String encrypt(String clearText) throws GeneralSecurityException {
 
        byte[] cypherText = encrypt(clearText.getBytes());
        return "{DES}" + new String(Base64.encode(cypherText));
 
    public  String decrypt( String cypherText)throws GeneralSecurityException {
 
        byte[] clearText = null;
 
        byte[] cypherBytes = Base64.decode(cypherText.substring("{DES}".length()));
        clearText = decrypt(cypherBytes);
 
        return new String(clearText);
    }
 
 
    private byte[] doEncryption( byte[] forEncrypt)
        throws GeneralSecurityException {
 
        Cipher desCipher = Cipher.getInstance("DES");
 
        desCipher.init(Cipher.ENCRYPT_MODE, desKey);
 
        return desCipher.do(forEncrypt);
    }
 
    private  byte[] doDecryption( byte[] forDecrypt)
            throws GeneralSecurityException {
 
        Cipher desCipher = Cipher.getInstance("DES");
 
        desCipher.init(Cipher.DECRYPT_MODE, desKey);
 
        return desCipher.do(forDecrypt);
    }
 
    public boolean isStringEncrypted(String textToCheck) {
        return (textToCheck != null && (textToCheck.startsWith("{DES}")));
    }
 
}
Personal tools