Introduction to ssri
SSRI (Secure Software Resource Integrity) is a powerful Node.js library used to manage Subresource Integrity (SRI) hashes. SRI helps ensure that a webpage fetches the appropriate content by allowing browsers to verify the integrity of a fetched resource. In this comprehensive guide, we’ll explore various useful APIs provided by the `ssri` library through detailed explanations and code snippets. This post will also include a sample application demonstrating the use of these APIs.
Generating Integrity Hash
The `integrity` method allows you to generate an integrity hash from a given string or buffer.
const ssri = require('ssri'); const integrity = ssri.fromData('Hello World!'); console.log(integrity.toString());
Combining Multiple Integrity Hashes
If you need to combine multiple integrity hashes into a single hash, use the `combine` method.
const ssri = require('ssri'); const integrity1 = ssri.fromData('Hello'); const integrity2 = ssri.fromData('World'); const combinedIntegrity = ssri.parse(integrity1 + ' ' + integrity2).concat(); console.log(combinedIntegrity.toString());
Checking Resource Integrity
Use the `checkData` method to verify if data matches a given integrity hash.
const ssri = require('ssri'); const data = 'Hello World!'; const integrity = ssri.fromData(data); ssri.checkData(data, integrity.toString()) .then(() => { console.log('Data integrity is verified!'); }) .catch(err => { console.error('Data integrity verification failed:', err); });
Generating Integrity Hash with Options
You can generate an integrity hash with specific algorithms using `integrity` and the `integrity.toJson()` method.
const ssri = require('ssri'); const options = { algorithms: ['sha256', 'sha512'], strict: true }; const integrity = ssri.fromData('Hello World!', options); console.log(integrity.toJson());
Example Application Using ssri APIs
Let’s create a simple Node.js application that generates, verifies, and logs integrity hashes for user input.
const ssri = require('ssri'); const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.text()); app.post('/generate', (req, res) => { const hash = ssri.fromData(req.body); res.send(hash.toString()); }); app.post('/verify', (req, res) => { const { data, hash } = req.body; ssri.checkData(data, hash) .then(() => res.send('Verified')) .catch(() => res.status(400).send('Verification failed')); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
In this application, we use `ssri` to generate and verify integrity hashes from user-provided data, showcasing the versatility of the library in real-world scenarios.
Hash: 93add3212241e46dbc9e6bd3bc10bcc0997e52d53680dd00513cee1840cb7a26