Sunday, 21 July 2013

How to encrypt and decrypt password using AES algorithm?



Password encryption and decryption using AES algorithm


Question: - How to encrypt and decrypt password using AES algorithm?


Answer: - As AES is a Symmetric Key Algorithm, So AES algorithm describes that the secret key used for encrypting the data, the same will be used for decrypting that encrypted data.

STEPS to encrypt and decrypt the message:-


  • We can pass the secret key which is used for encryption and decryption and also pass the cryptographic algorithm in the constructor of SecretKeySpec class.

  • Then we have to create new instance of Cipher using getInstance method where we are passing the name of algorithm to transform our secret data.

  • After that we have to call init method of cipher class and then we are informing Cipher to initiate the Encryption mode and use the specified SecretKey by calling below two lines.


                    Key key = new SecretKeySpec(uniqueKeys, ALGORITHMUSEDFORENCRPTIONDECRYPTION);
                    cipher.init(Cipher.ENCRYPT_MODE, key);


  • Then to encrypt the secret data, we have to pass that data into the doFinal() of Cipher class and then we will get the our secret data as encrypted data.

  • To decrypt the encrypted data we have to call init() method of Cipher class in decrypt mode using the below java code:-
                               
cipher.init(Cipher.DECRYPT_MODE, key);
String originalData = new String(cipher.doFinal(encryptedData));


Inthe following sample example, we will use AES algorithm called AES and we are using the word "SecretUniqueKeys" as the secret key. AES algorithm can use a key of 128 bits (16 bytes * 8). We use "generateKey()" method of SecretKeySpec class to generate a secret key for AES algorithm with a specific key.


Java sample example for encryption and decryption



PasswordEncryptorDecryptor.java

packagecom.gaurav.java.security;

importjava.security.Key;

importjavax.crypto.Cipher;
importjavax.crypto.spec.SecretKeySpec;

importsun.misc.BASE64Decoder;
importsun.misc.BASE64Encoder;

public classPasswordEncryptorDecryptor {
            privatestatic final String ALGORITHMUSEDFORENCRPTIONDECRYPTION = "AES";
            privatestatic final byte[] uniqueKeys = new byte[] { 'S', 'e', 'c', 'r',
                                    'e', 't', 'U', 'n', 'i', 'q', 'u', 'e', 'K', 'e', 'y', 's' };

            privatestatic Key generateKey() throws Exception {
                        Key key = new SecretKeySpec(uniqueKeys,
                                                ALGORITHMUSEDFORENCRPTIONDECRYPTION);
                        returnkey;
            }

            /** This method is used for Password Encryption using AES algorithm */
            publicstatic String doPasswordEncryption(String plainString4Encyption)
                                    throwsException {
                        Key key = generateKey();
                        Cipher c = Cipher.getInstance(ALGORITHMUSEDFORENCRPTIONDECRYPTION);
                        c.init(Cipher.ENCRYPT_MODE, key);
                        byte[] encyptedArrayValue = c.doFinal(plainString4Encyption.getBytes());
                        String encryptedStringValue = new BASE64Encoder()
                                                .encode(encyptedArrayValue);
                        returnencryptedStringValue;
            }

            /** This method is used for Password decryption using AES algorithm */
            publicstatic String getDecryptedPassword(String encryptedString)
                                    throwsException {
                        Key key = generateKey();
                        Cipher c = Cipher.getInstance(ALGORITHMUSEDFORENCRPTIONDECRYPTION);
                        c.init(Cipher.DECRYPT_MODE, key);
                        byte[] decodedArrayValue = new BASE64Decoder()
                                                .decodeBuffer(encryptedString);
                        byte[] decyptedArrayValue = c.doFinal(decodedArrayValue);
                        String decryptedStringValue = new String(decyptedArrayValue);
                        returndecryptedStringValue;
            }

}


PasswordEncryptorDecryptorCaller.java

packagecom.gaurav.java.security;

public classPasswordEncryptorDecryptorCaller {
            publicstatic void main(String[] args) {

                        try{
                                    String passwordToEncrypt = "KumarGaurav";
                                    String encyptedPassword = PasswordEncryptorDecryptor
                                                            .doPasswordEncryption(passwordToEncrypt);
                                    String decyptedPassword = PasswordEncryptorDecryptor
                                                            .getDecryptedPassword(encyptedPassword);

                                    System.out.println("Text which is passed for Encryption  : "
                                                            + passwordToEncrypt);
                                    System.out.println("Encrypted Password Text : " + encyptedPassword);
                                    System.out.println("Decrypted Password Text : " + decyptedPassword);

                        } catch (Exception e) {
                                    System.out
                                                            .println("Error while password encryption and decryption is :-> "
                                                                                    + e.getMessage());
                        }
            }
}

Result:-

Text which is passed for Encryption  : KumarGaurav
Encrypted Password Text : 6iUeJjU7P6wVZgiZ0xkyfA==
Decrypted Password Text : KumarGaurav

No comments:

Post a Comment