HTML - Integrity attribute

1 - About

integrity is an attribute of the fetch elements.

Its value is a digest that controls that the file was not altered in transit. It's a data integrity functionality.

3 - Example

If the calculation output with a sha384 was:


ZYfZnVukOuh/gRpU9uN+T9XwwRFJ9Y+0Ylk3zKvI184omb/HoOtQ0F8Iol7Nix7q

A link element for instance would be:


<link rel="stylesheet" href="stylesheet.css" integrity="sha384-ZYfZnVukOuh/gRpU9uN+T9XwwRFJ9Y+0Ylk3zKvI184omb/HoOtQ0F8Iol7Nix7q">

3.2 - Script element with javascript

For a script element


<script src="script.js" integrity="sha384-ZYfZnVukOuh/gRpU9uN+T9XwwRFJ9Y+0Ylk3zKvI184omb/HoOtQ0F8Iol7Nix7q" type="text/javascript"></script>

4 - Management

4.1 - Calculation

4.1.1 - Online


<p>Choose a file to calculate the sha256 and sha384 integrity value:</p>
<input onchange="handleFile(event, this)" type="file"> 


handleFile = function(event,element){
  let files = element.files;
  if (files.length == 0) return;
  let reader = new FileReader(); 
  // Retrieve the buffer
  reader.onload = (e) =>{
     // Get the result in bytes
     var arrayBuffer = reader.result;
     processIntegrity(arrayBuffer,'SHA-256');
     processIntegrity(arrayBuffer,'SHA-384');
     // Debug: the plaintext
     // var dec = new TextDecoder(); // always utf-8
     // var fileText = dec.decode(arrayBuffer);
     // console.log(fileText);
  }
  // Start the read process
  reader.readAsArrayBuffer(files[0]);
}

// Digest an array of bytes
processIntegrity = async function(arrayBuffer,hashAlgo){
    let algoIntegrityValue  = '';
    if (hashAlgo == 'SHA-256'){
        algoIntegrityValue = 'sha256';
    } else if (hashAlgo == 'SHA-384') {
        algoIntegrityValue = 'sha384';
    }
    const digestArrayBuffer = await crypto.subtle.digest(hashAlgo, arrayBuffer);
    const digestString = String.fromCharCode.apply(null, new Uint8Array(digestArrayBuffer));
    // btoa need a binary string
    // https://developer.mozilla.org/en-US/docs/Web/API/DOMString/Binary
    let base64Digest = window.btoa(digestString)
    console.log(algoIntegrityValue+'-'+base64Digest);
}


4.1.2 - Offline

The integrity can be calculated with the following command line.

It calculate the digest with a sha (256 or 384) and apply the base64 algorithm above.


#sha256
openssl dgst -sha256 -binary stylesheet.css | openssl base64 -A

#sha384
openssl dgst -sha384 -binary stylesheet.css | openssl base64 -A

# work also for other script
openssl dgst -sha384 -binary script.js | openssl base64 -A

where:

5 - Documentation / Reference


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap