javascriptajaxblobmd5subresource-integrity

Sub Resource Integrity for images using javascript


I recently learned about Sub Resource Integrity which prevents the execution of altered JS and CSS. Since the current implementation lacks the support for images I tried to experiment with my own implementation.

<img data-src="http://localhost:8888/4.jpg" alt="" data-hash="" class="image">
<img data-src="http://localhost:8888/2.jpg" alt="" data-hash="" class="image">
<img data-src="http://localhost:8888/3.jpg" alt="" data-hash="" class="image">


<script src="qwest.js"></script>
<script src="md5.min.js"></script>
<script>

var images = document.getElementsByClassName("image");

     for( var i = 0, len = images.length; i < len; i++){
        popHash(images[i]);

    }

    function popHash(image) {

        qwest.get(image.dataset.src, {}, {responseType:"blob"})
        .then(function (xhr, response) {
            var src = window.URL.createObjectURL(response);
            image.src = src;
            image.dataset.hash = md5(src); 
           console.log(image.dataset.hash);


            /* code to check the equality of hashes here */
        }) 
    }


</script>

The problem is each time I am getting a different MD5 hash. Please help me to find what I am doing wrong.

I am using JavaScript-MD5 (https://github.com/blueimp/JavaScript-MD5) for getting MD5 hash and Qwest.js (https://github.com/pyrsmk/qwest) for fetching the Image


Solution

  • With Slight Changes I was able to get the correct result. I used arrayBuffer instead of blob and a sha-256 hashing. I made a tiny library for the same.

    https://github.com/ShopupStore/IntegrityChecker