- read

Attention, Web Developers! You must learn about Subresource Integrity (SRI)

Athanasios Emmanouilidis 39

Attention, Web Developers! You must learn about Subresource Integrity (SRI)

Athanasios Emmanouilidis
Level Up Coding
Published in
3 min read4 hours ago

--

Photo by FLY:D on Unsplash

As a Web developer you almost always utilize external resources in the websites you create: you link to jQuery, Bootstrap, React or whatever other library, most times from a reputable CDN (Content Delivery Network). What you probably overlook however is that you are not validating the fact that the external resource you are linking to has not been altered by malicious actors. Remember, that resource you are linking to is external and outside your control. CDNs can be hacked, just like any other machine on the Internet. You do not want to wake up one morning and find out that X CDN has been hacked and instead of the original jQuery library, your website was using a hacked jQuery library that impacted your visitors in very bad and malicious ways.

But how can you be sure that this will not happen? Here is where Subresource Integrity (SRI) comes to help. Subresource Integrity (SRI) is a method that helps you validate a third party resource by hashing its contents. By hashing the contents of a resource, we get back a hash. If we change the contents of the resource and we apply hashing again, we get a different hash. This is the way to understand that a resource has been tampered. And that’s what the browsers do in order to keep you safe from malicious scripts.

At the time of writing, 94.35% of all browsers support SRI. But how can you implemented it as a Web Developer in your website? Let’s see.

Step 1:
We need to know the SRI hash of the resource we want to link to.Most CDNs nowdays provide this hash for us. If the hash is not provided, we can calculate it with a free online website called SRI Hash Generator.

For our example lets say we want to link to the jQuery library version 3.7.1 at cdnjs (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js).
Fortunately, cdnjs provides the SRI hash of the library which is the following:

sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==

Step 2:
Now that we know the SRI hash of the resource we want to link to, lets see how we can link to it inside our HTML webpage.