Search code examples
base64gatlingpassword-encryption

How to encode the password in Gatling?


I have a requirement in my project to encode the password being sent in the login request. What is the best way to do it?


Solution

  • You can store the credentials in a file as key-value pair. Read the file in vector and then decode the value. The value can be stored in a session and can be used in your Gatling request as below:

    import scala.concurrent.duration._
    import io.gatling.core.Predef._
    import io.gatling.core.structure.ChainBuilder
    import io.gatling.http.Predef._
    import io.gatling.jdbc.Predef._
    import io.gatling.jsonpath._
    import Headers._
    import scala.collection._
    import java.time.format.DateTimeFormatter
    import java.time.LocalDateTime
    import java.time.LocalDate
    
    import io.gatling.core.feeder._
    import java.util.Base64
    import java.nio.charset.StandardCharsets
    import scala.util.matching.Regex
    
    object TestClass {
    
    //Now you can use below code to read the credential file,
    
      val recordsByEnv: Map[String, Seq[Record[Any]]] =
        csv("/User/sandy/data/userdetails.csv").readRecords.groupBy { record =>
          record("env").toString
        }
      val passwordByEnv: Map[String, Seq[Any]] = recordsByEnv.mapValues { records =>
        records.map { record =>
          record("password")
        }
      }
      val password_v = (passwordByEnv.get("env_name").toString)
      val password_encoded = password_v.substring(12, (password_v.length - 2))
      val credentials = new String(Base64.getDecoder.decode(password_encoded))
      //Store the decoded value in session variable
        .exec(session => session.set("password", credentials))
        .exec(
          http("Authorization")
            .post("https://XXXX.xxxxxx.com")
            .header("Content-Type", "application/x-www-form-urlencoded")
            .formParam("password", "${password}")
            .formParam("username", "USERNAME")
        )
    //Below is user details file look like below
    //env_name,encoded_password
    
    }