Search This Blog

Breaking

Friday, 11 June 2021

Encrypt and Decrypt username and Password in Automation

Recently, I came across a situation where we need to encrypt usernames and passwords so that they can not be hardcoded. This was my first experience to encounter this kind of situation in automation. So I read some java articles on how can we achieve it. 

I used java cipher, to do this activity. 






In java, You can create an instance for the cipher class and provide a mode that can be used for encryption.

Cipher cipher Cipher.getInstance("AES/ECB/PKCS5Padding");

Before using the cipher obect, you need to initialise it.

cipher.init(Cipher.ENCRYPT_MODEsecretKeySpec);

The first argument is for to set mode (Encrypt/decrypt) and the second argument is to

for creating the secretKeySpec.

The secret key spec you can generate by:

public static void setKey(String mykey) {

    {

        try {

            key = mykey.getBytes(UTF_8);

            sha MessageDigest.getInstance(CIPHER_ALGORITHM_SHA);

            key sha.digest(key);

            key Arrays.copyOf(key16);

            secretKeySpec new SecretKeySpec(keyAES_ALGORITHM);

        catch (NoSuchAlgorithmException e) {

            e.printStackTrace();

        catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        }

    }

}


The CIPHER_ALGORITHM_SHA is "SHA-1".

The base encoding is "UTF-8".

The ES_ALGORITHM is "AES".


When all is set, you can invoke the encrypt and decrypt with the help of doFinal method.

Base64.encodeBase64String(cipher.doFinal(StringToEncrypt.getBytes(UTF_8)));

String(cipher.doFinal(Base64.decodeBase64(encodedText)));


Let me know if anyone needs this utility. I will upload it to my GitHub repo.

No comments:

Post a Comment