You may use this program to encrypt your passwords and then store those in database so that they are secure. First we call al the classes which we want to import.
Listing 1: Importing classes
import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.Cipher; import sun.misc.BASE64Encoder;
Here:
Now, We will make the class along with the main method:
Listing 2: Class declaration along with Main method
public class AesEncrDec
{
public static void main(String args[])
{
new AesEncrDec().encrypt();
}
Here,
Now we will make the encrypt method containing the logic,
Listing 3: Making the keygenerator and making key
void encrypt()
{
try
{
String plainData="hello",cipherText,decryptedText;
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
Here:
Now we will perform the encryption part:
Listing 4: Performing the encryption
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE,secretKey);
byte[] byteDataToEncrypt = plainData.getBytes();
byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
cipherText = new BASE64Encoder().encode(byteCipherText);
Here:
Now we will perform the decryption part:
Listing 5: Performing the decryption
aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters());
byte[] byteDecryptedText = aesCipher.doFinal(byteCipherText);
decryptedText = new String(byteDecryptedText);
System.out.println("\n Plain Data : "+plainData+" \n Cipher Data : "+cipherText+" \n Decrypted Data : "+decryptedText);
}
catch(Exception e)
{
}
}
}
Here:
Full Source Code:
Listing 6: Full Source code
package article13;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import sun.misc.BASE64Encoder;
public class AesEncrDec
{
public static void main(String args[])
{
new AesEncrDec().encrypt();
}
void encrypt()
{
try
{
String plainData="hello",cipherText,decryptedText;
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE,secretKey);
byte[] byteDataToEncrypt = plainData.getBytes();
byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
cipherText = new BASE64Encoder().encode(byteCipherText);
aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters());
byte[] byteDecryptedText = aesCipher.doFinal(byteCipherText);
decryptedText = new String(byteDecryptedText);
System.out.println("\n Plain Data : "+plainData+" \n Cipher Data : "+cipherText+" \n Decrypted Data : "+decryptedText);
}
catch(Exception e)
{
}
}
}
Output:
Plain Data : hello Cipher Data : VD7EhOL4+n+h9mK+Gsj7/A== Decrypted Data : hello






See the prices for this post in Mr.Bool Credits System below: