На английском языке «sha256 javascript» означает генерацию хеша SHA-256 с использованием JavaScript. Вот несколько способов сделать это:
Метод 1: использование Web Crypto API
async function sha256(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;
}
const message = 'Hello, world!';
sha256(message)
.then(hash => console.log(hash))
.catch(error => console.error(error));
Метод 2. Использование библиотеки JavaScript (например, CryptoJS)
const message = 'Hello, world!';
const hash = CryptoJS.SHA256(message).toString();
console.log(hash);
Метод 3. Использование встроенного API SubtleCrypto (поддерживается в современных браузерах)
async function sha256(message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hashBuffer = await window.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;
}
const message = 'Hello, world!';
sha256(message)
.then(hash => console.log(hash))
.catch(error => console.error(error));