The crypto
object in JavaScript provides cryptographic functionalities that can be used to generate secure random numbers, create hashes, encrypt and decrypt data. It is available in modern Web APIs and Node.js environments.
Generating Secure Random Numbers
To generate cryptographically secure random numbers, we can use the crypto.getRandomValues()
method:
const array = new Uint8Array(10);
crypto.getRandomValues(array);
console.log(array);
This method fills a typed array with secure random numbers.
Creating a Hash
We can use the crypto.subtle.digest
API to create a hash, such as SHA-256:
async function generateHash(message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
return hashHex;
}
generateHash("Hello, world!").then(console.log);
This code converts a string into an SHA-256 hash.
Encryption and Decryption
With the crypto.subtle
API, we can encrypt and decrypt data using AES-GCM:
async function encryptData(key, data) {
const encoder = new TextEncoder();
const encodedData = encoder.encode(data);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv: iv },
key,
encodedData
);
return { encrypted, iv };
}
async function decryptData(key, encrypted, iv) {
const decrypted = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: iv },
key,
encrypted
);
return new TextDecoder().decode(decrypted);
}
This implementation uses AES-GCM, a secure and modern algorithm for symmetric encryption.
Conclusion
The crypto
object in JavaScript provides powerful tools for application security, enabling secure random number generation, hash creation, and the implementation of modern encryption techniques.