Interview Questions

Java - Encryption Decryption Example

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class JavaEncryptionDecryption {

    private static String KEY = "ABCD1234";

    public static byte[] encrypt(String textData) throws Exception {
        String algo = "DES";
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo);
        byte[] encBytes = KEY.getBytes("UTF8");
        DESKeySpec keySpecEncrypt = new DESKeySpec(encBytes);

        SecretKey keyEncrypt = keyFactory.generateSecret(keySpecEncrypt);

        Cipher cipherEncrypt = Cipher.getInstance(algo);
        cipherEncrypt.init(Cipher.ENCRYPT_MODE, keyEncrypt);

        byte[] encryptedBytes = cipherEncrypt.doFinal(textData.getBytes());
        return encryptedBytes;
    }

    public static String decrypt(byte[] encrypted) throws Exception {
        String algo = "DES";
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo);
        byte[] encBytes = KEY.getBytes("UTF8");
        DESKeySpec keySpecEncrypt = new DESKeySpec(encBytes);

        SecretKey keyEncrypt = keyFactory.generateSecret(keySpecEncrypt);

        Cipher cipherEncrypt = Cipher.getInstance(algo);

        cipherEncrypt.init(Cipher.DECRYPT_MODE, keyEncrypt);
        byte[] decryptedBytes = cipherEncrypt.doFinal(encrypted);
        return new String(decryptedBytes);
    }

    public static void main(String[] args) throws Exception {

        byte[] encryptText = encrypt("Hello@14$");
        System.out.println("Encrypted Text = " + encryptText);

        String decryptText = decrypt(encryptText);
        System.out.println("Decrypted Text = " + decryptText);

    }
}

Output:

Encrypted Text = [B@aa9835
Decrypted Text = Hello@14$