Skip to content

Instantly share code, notes, and snippets.

@MeyCry
Created June 6, 2024 12:40
Show Gist options
  • Save MeyCry/7a6bccbdf3860f93e95a0c9a47d2ce90 to your computer and use it in GitHub Desktop.
Save MeyCry/7a6bccbdf3860f93e95a0c9a47d2ce90 to your computer and use it in GitHub Desktop.
Sha hashing in browser
export async function doShaHashing(message: string, algorithm: 'SHA-256' | 'SHA-384' | 'SHA-512') {
// Check if the specified algorithm is supported
const supportedAlgorithms = ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512'];
if (!supportedAlgorithms.includes(algorithm.toLowerCase())) {
throw new Error(`Unsupported algorithm: ${algorithm}`);
}
// Encode the message as a Uint8Array
const encoder = new TextEncoder();
const data = encoder.encode(message);
// Hash the data using the specified algorithm
const hashBuffer = await crypto.subtle.digest(algorithm, data);
// Convert the hash buffer to a hex string
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment