Find the MD5 hash of the image uploaded using Java WebDriver

I am trying to calculate the MD5 hash of images that are loaded in Firefox webdriver using Java.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.JavascriptExecutor;


String script = "var imgElement = document.querySelector('div.mtl:nth-child(2) > div:nth-child(1) > img:nth-child(1))'; *** find a way to get the MD5 hash of this image *** ";
String url = "http://www.facebook.com";

WebDriver webDriver = new FirefoxDriver();
driver.get(url);
JavascriptExecutor js = (JavascriptExecutor) driver;
Stgin md5 = (String) js.executeScript(script);

in this code, what must replace with :

*** find a way to get the MD5 hash of this image ***

Answer №1

Utilize the fetch function with force-cache to retrieve content from cache. After that, process the arrayBuffer from the response. It is worth noting that MD5 is considered outdated and no longer supported by browsers. For more information on Crypto, visit this link. You have the option to choose between SHA-1, SHA-256, SHA-384, and SHA-512 for digesting. An example of digesting using SHA-256 is provided below.

public void getImageSHA256(){
    driver.get("https://www.blognone.com/");        
    WebElement img = driver.findElement(By.cssSelector("img"));
    String imgUrl = img.getAttribute("src").trim();
    String script = "function hex(buffer) {  var hexCodes = [];  var view = new DataView(buffer);  for (var i = 0; i < view.byteLength; i += 4) { var value = view.getUint32(i); var stringValue = value.toString(16); var padding = '00000000'; var paddedValue = (padding + stringValue).slice(-padding.length); hexCodes.push(paddedValue);  }  return hexCodes.join(\"\");}" +
    "var callback = arguments[arguments.length - 1];" + 
    "fetch(arguments[0],{cache:'force-cache'}).then((response)=> {" +
        "return response.arrayBuffer(); }).then((buffer)=>{" +
            " return crypto.subtle.digest('SHA-256', buffer); }).then((hashArray)=>{" + 
                " callback(hex(hashArray));"+
                "});";
    driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);
    Object response = ((JavascriptExecutor) driver).executeAsyncScript(script, imgUrl);
    System.out.println(response);
}

The screenshot displayed below illustrates the comparison between the SHA-256 generated by my code and the one produced by an online tool. https://i.sstatic.net/lGBsI.png

Answer №2

private void retrieveImageMD5(){
    driver.get("https://www.blognone.com/");        
    WebElement img = driver.findElement(By.cssSelector("img"));
    String imgUrl = img.getAttribute("src").trim();
    String script = "var callback = arguments[arguments.length - 1];"
                + "function _arrayBufferToBase64( buffer ) {"
                + "    var binary = '';"
                + "    var bytes = new Uint8Array( buffer );"
                + "    var len = bytes.byteLength;"
                + "    for (var i = 0; i < len; i++) {"
                + "        binary += String.fromCharCode( bytes[ i ] );"
                + "    }"
                + "    return window.btoa( binary );"
                + "}"
                + " fetch(' " + imgUrl + " ',{cache:'force-cache'})."
                + "then((response)=>{return response.arrayBuffer()})."
                + "then((response)=>{return _arrayBufferToBase64(response)})."
                + "then((response)=>{callback(response)});";
    driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);
    Object response = ((JavascriptExecutor) driver).executeAsyncScript(script, imgUrl);
            byte[] data = Base64.getDecoder().decode((String) response);
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] hash = md.digest(data);

    StringBuilder sb = new StringBuilder(2 * hash.length);
    for (byte b : hash) {
        sb.append(String.format("%02x", b & 0xff));
    }

    String digest = sb.toString();
    System.out.println("MD5 of the Image : " + digest);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating nested JSON objects using D3 - A guide

I have a problem in my REACT application where I am trying to implement Mike Bostock's Multi-Series Line Chart using D3 v4. I am reading JSON response with axios and passing it to a component using react-faux-dom, but even though the object seems corr ...

Running res.render in an asynchronous manner within an express application

My goal is to make this router respond asynchronously: var express = require('express'), router = express.Router(); router.get('/', function(req, res, next) { res.render('contact', { titleShown: true, title: & ...

Show the respective value names stored in my database for every choice available

I am facing a challenge in explaining what I need, but essentially, I want to showcase the name of the choice I selected from a list stored in the database. To provide more context, below is my select input: <select name="options[1][]" id="perso_1" cl ...

Is it possible to dynamically add attributes to XHTML tags using Javascript? For instance, adding a title attribute to an anchor tag like <a title="text">

Is it possible to modify XHTML source code through JavaScript? Can attributes be added to any XHTML tag dynamically, such as adding a title attribute to an anchor tag (<a title="text">)? ...

Leveraging the power of PhantomJS as a headless browser in Selenium with Python

I am currently utilizing Python-Selenium for running a series of tests. The objective is to log into the webpage, input the username and password, and perform additional tasks. While executing the test with the Firefox browser, everything runs smoothly. Ho ...

Trouble with Google Interactive Charts failing to load after UpdatePanel refresh

Desperately seeking assistance! I have spent countless hours researching this issue but have hit a dead end. My dilemma involves using the Google Interactive Charts API within an UpdatePanel to dynamically update data based on dropdown selection changes. H ...

What is the process for including a checkbox at the beginning of each row in a React-virtualized table?

I have been utilizing the react-virtualized library to render a Table, with an intended appearance as follows: Desired Table Layout My progress so far has led me to this representation: Current Table Display https://i.sstatic.net/6VFbp.png I have succ ...

Is getElementById in JavaScript reliable for multiple calls?

I am attempting to create a table cell that transforms into a textbox upon clicking, allowing for input to be entered and then displayed in the cell. Below is my JavaScript function: $(".cellConsigne").click(function () { var numId = this.id.substrin ...

JavaScript running out of memory during yarn build process

While working with yarn to build my project, I encountered a problem. The issue at hand is that the memory heap exceeds its allocated size, causing the build process to fail. FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - Java ...

Exploring the relationship between MongoDB and Node.js: Retrieving a document based on its _id using a UUID (GUID

As I work on creating a restAPI with node.js, I am facing an issue while querying a mongo collection. While I can successfully query using strings such as "companyname", I struggle when it comes to querying the "_id" element in the document. In my mongo d ...

Locating consecutive combinations of characters in a two-dimensional array using Java

I am on a quest to search for a specific combination of char letters within a large 2D array filled with random letters from the alphabet, ranging from 'a' to 'z'. The combination that I am seeking is quite specific - it consists of the ...

Exploring the Fusion of Strings and Arrays of Javascript Objects using jQuery and JSON

Trying to achieve a simple task, but not very proficient in jQuery so struggling to figure it out. Want to send JSON data to an ASP.NET Controller. Data includes strings and a list of objects. The code snippet would appear like this: View: $(document). ...

The Transition Division Is Malfunctioning

I've encountered an issue where I am trying to move a div by adjusting its left property, but no transition is taking place. Regardless of the changes I make to my code, the result remains the same. Below is the current state of the code. Can anyone i ...

Dynamically alter the arguments of the onClick function

Here's a scenario I'm dealing with: <button id="button1" onClick="someFunc('arg1','arg2')"> </button> I'm wondering if it's feasible to modify the parameters of the function someFunc as shown below: &l ...

Can halting an ajax function mid-process prevent it from finishing?

My objective is to convert a video using ffmpeg, which tends to take a considerable amount of time to complete. I'm considering sending an ajax request to the server for this task, but I don't want the user to have to wait until the video convers ...

When running `npm start`, if you encounter an error message that says `npm ERR`,

When attempting to run this JS project on my Mac using this JS project, I encountered an npm error after typing npm start: https://i.sstatic.net/o2UZj.png Despite searching various websites for a solution, I have already included these lines in my packag ...

Error: The directive template is unable to evaluate the given expression

I recently dove into AngularJS and hit a roadblock. Excuse the coffeescript and haml mix. # some-js-file.js.coffee app.directive "sr", -> restrict: "C" replace: true transclude: true scope: serviceRequest: "@servReq" template: "<div> ...

Tips for delivering exceptional service at the module level:

I've been working on implementing a provider for a library module that triggers my factory provider when added. However, I've encountered an issue where the provider doesn't seem to execute the console.log, indicating that it's not runn ...

Creating dynamic email content with Node.js using SendGrid templating

How can I properly format SendGrid's content using Node.js? I'm currently working on sending emails from a contact form within an application using SendGrid. I have a Google Cloud Function set up that I call via an HTTP post request. Although I ...

Refresh your HTML page automatically while keeping the scroll position and functioning with anchors

I am currently facing an issue with a web service that generates HTML and I need it to automatically refresh in the browser every 10 seconds. Initially, I used the <meta http-equiv="refresh" content="10"> method which worked successfully, maintaining ...