How encrypt and decrypt text password example sending into database?

I spend a lot of time to find solution for encryption password and insert it into database and get it from database and decryption.  The way for it is very simple.

Create in Netbeans project.

s1q7The project named EncryptDecryptPass. Click the Finish button.

q1Right click on project node and choose New->Java Class.

q2

In Class Name write AESCrypt and from Package select dora package.

q3Click the Finish button. You see in tree of project two files: main class and AESCrypt class.

q8Into AESCrypt.java file paste this code:


 package dora;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class AESCrypt 
{
    private static final String ALGORITHM = "AES";
    private static final String KEY = "1Hbfh667adfDEJ78";
    
    public static String encrypt(String value) throws Exception
    {
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(AESCrypt.ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte [] encryptedByteValue = cipher.doFinal(value.getBytes("utf-8"));
        String encryptedValue64 = new BASE64Encoder().encode(encryptedByteValue);
        return encryptedValue64;
               
    }
    
    public static String decrypt(String value) throws Exception
    {
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(AESCrypt.ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte [] decryptedValue64 = new BASE64Decoder().decodeBuffer(value);
        byte [] decryptedByteValue = cipher.doFinal(decryptedValue64);
        String decryptedValue = new String(decryptedByteValue,"utf-8");
        return decryptedValue;
                
    }
    
    private static Key generateKey() throws Exception 
    {
        Key key = new SecretKeySpec(AESCrypt.KEY.getBytes(),AESCrypt.ALGORITHM);
        return key;
    }
}

Remember that for AES alogithm your key must have 16 chars. For DES algorithm it will be 8 chars.

q6

q4But into EncryptDecryptPass.java paste this code:


package dora;

public class EncryptDecryptPass {

    public static void main(String[] args) {
        try {
        String password = "Summer2014";
            System.out.println("plain pass="+password);
        String encryptedPassword = AESCrypt.encrypt(password);
            System.out.println("encrypted pass="+encryptedPassword);
        String decryptedPassword = AESCrypt.decrypt(encryptedPassword);    
                System.out.println("decrypted pass="+decryptedPassword);
        } catch(Exception e) { System.out.println("bug"+e.getMessage()); }
    }
    
}

q9If You run this application in Output window see:

q10