0 day streak
javascript / expert
Snippet

Secure Integrity Validation via Web Crypto API

For high-security Angular applications, verifying data integrity client-side is crucial. The Web Crypto API provides native, performant cryptographic primitives like SHA-256 without requiring heavy external libraries.

snippet.js
javascript
1
2
3
4
5
6
async function generateChecksum(data: string): Promise<string> {
const msgUint8 = new TextEncoder().encode(data);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
angular
Breakdown
1
crypto.subtle.digest('SHA-256', ...)
Performs an asynchronous cryptographic hash operation using the browser's optimized engine.
2
new TextEncoder().encode(data)
Converts the string into a Uint8Array, which is the required format for cryptographic operations.