CoreJava_Encrypt-Decrypt

  • Using BASE 64

import org.apache.commons.codec.binary.Base64;


import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


public class EncryptDecrypt {
    static String key = "VANSILmangalXBB7LDUGNQ=="; // 24 chars

    public static SecretKey getSecretKey(String key) {
        byte[] decodedKey = Base64.decodeBase64(key);
        SecretKey secretKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
        return secretKey;
    }

    public static String encryptAES(String plainText, String key)
            throws Exception {
        SecretKey secretKey = getSecretKey(key);
        byte[] plainTextByte = plainText.getBytes();
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedByte = cipher.doFinal(plainTextByte);
        String encryptedText = Base64.encodeBase64String(encryptedByte);
        return encryptedText;
    }

    public static String decryptAES(String encryptedText, String key)
            throws Exception {
        SecretKey secretKey = getSecretKey(key);
        byte[] encryptedTextByte = Base64.decodeBase64(encryptedText);
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
        String decryptedText = new String(decryptedByte);
        return decryptedText;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(sampleData);

        String encryptMsg = encryptAES(sampleData, key);
        System.out.println(encryptMsg);

        String decryptMsg = decryptAES(encryptMsg, key);
        System.out.println(decryptMsg);

        System.out.println("After decrypt, sample and decrypt msg must be equal ?? "+sampleData.equalsIgnoreCase(decryptMsg));

    }

    static String sampleData = "Hello friends";

}

Output:
Hello friends
UyTO3kyEjo+okLSoi+tm+Q==
Hello friends
After decrypt, sample and decrypt msg must be equal ?? true

  • Using Hash String

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashString {

    public static final String ALGO_SHA_256 = "SHA-256";
    public static final String ALGO_SHA_1 = "SHA-1";
    public static final String ALGO_MD5 = "MD5";
    public static final String ALGO_DEFAULT = "SHA-256";

    public static String getMd5HashString(String password) {
        String hashString;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(StandardCharsets.UTF_8.encode(password));
            hashString = String.format("%032x", new BigInteger(1, md5.digest()));
        } catch (NoSuchAlgorithmException e) {
            hashString = String.valueOf(password.hashCode());
        }
        return hashString;
    }

    public static String getMd5HashString2(String password) {
        byte[] hashBytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            hashBytes = md.digest(password.getBytes());
        } catch (NoSuchAlgorithmException e) {
            e.getMessage();
        }
        StringBuilder hashedString = new StringBuilder();
        for (int i = 0; i < hashBytes.length; ++i) {
            String hex = Integer.toHexString(hashBytes[i]);
            if (hex.length() == 1) {
                hashedString.append(0);
                hashedString.append(hex.charAt(hex.length() - 1));
            } else {
                hashedString.append(hex.substring(hex.length() - 2));
            }
        }
        return hashedString.toString();
    }

    public static String generateHashString(String algo, String data) throws NoSuchAlgorithmException {
        if (data.isEmpty()) {
            return null;
        } else {
            MessageDigest messageDigest = MessageDigest.getInstance(algo);
            byte[] result = messageDigest.digest(data.getBytes());
            StringBuffer stringBuffer = new StringBuffer();
            byte[] var5 = result;
            int var6 = result.length;
            for (int var7 = 0; var7 < var6; ++var7) {
                byte bytes = var5[var7];
                stringBuffer.append(String.format("%02x", bytes & 255));
            }
            return stringBuffer.toString();
        }
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String md5HashString = getMd5HashString("mangal@123");
        String md5HashString2 = getMd5HashString2("mangal@123");

        // can be used any ALGO
        String hashMsg = generateHashString(ALGO_SHA_256, "mangal@123");

        System.out.println(md5HashString);
        System.out.println(md5HashString2);
        System.out.println(hashMsg);
    }
}

Output:
05eafeb211bbf7925eeba00fc8e44f15
05eafeb211bbf7925eeba00fc8e44f15
a0e85e4e1b48ef45e28ba049f3490c3a73f9f33dce6ec256d413ae5c777d4c2d