i

Selenium Step By Step Guide

How to Encode password in WebDriver

Selenium automation needs login and Signup related test cases where credential information might get exposed to the unwanted people group. This situation becomes a security concern for an Automation tester to take care of at the highest priority.

We can import the Base64 class for using encodeBase64 and decodeBase64 methods to encode and decode the password, which needs to be secured while doing login on any web page under test.  We need to import “org.apche.commons.codec.binary.Base64” into our package to use the Base64 class. This class provides two essential and useful methods:

  1. encodeBase64()
  2. decodeBase64()

Both the methods receive parameter as a byte array and return the byte array as well. Steps involved to encode a password sting:

  1. Use the encodeBase64() method of the Base64 class to encode the password string by passing the password string into the parameter of the encodeBase64() method.
  2. Use decodeBase64() method to decode the encoded byte array by passing the byte array as a parameter into the decodeBase64() method.
  3. Once decoded byte array is generated, we can convert it into the String object and use it as our original password on the target web page.

Let us see the detailed sample code below:

package SeleniumTest.SeleniumTest;

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

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import org.openqa.selenium.remote.DesiredCapabilities;

public class EncodedPwd

{

    public static void main( String[] args )

    {

        System.setProperty("webdriver.chrome.driver",driverPath);

        ChromeOptions options=new ChromeOptions();

        options.addArguments("start-maximized");

        DesiredCapabilities dc=new DesiredCapabilities();

        dc.setCapability(ChromeOptions.CAPABILITY, options);

        WebDriver driver=new ChromeDriver(dc);

        driver.get("https://facebook.com");

        WebElement eleUser=driver.findElement(By.xpath("//*[@id='email']"));

        WebElement elePwd=driver.findElement(By.xpath("//*[@id='pass']"));

        String strUsername="abc";

        String strPassword="abcdef";// This String value can be called from a secure source into our project.

        byte [] encodedBytes=Base64.encodeBase64(strPassword.getBytes());

        byte [] decodedBytes=Base64.decodeBase64(encodedBytes);

        eleUser.sendKeys(strUsername);

        String decodedPwdString=new String(decodedBytes);

        elePwd.sendKeys(decodedPwdString);

        System.out.println(decodedPwd);

       driver.findElement(By.xpath("//*[@value='Log In']")).click();

    } 

}