hash SHA-256 string di browser
Januari 05, 2025
1
fungsi mengubah string teks menjadi hashing SHA-256
async function hashStringSHA256(input) {
try {
const encoder = new TextEncoder();
const data = encoder.encode(input);
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;
} catch (error) {
console.error("Error hashing string:", error.message);
return null;
};
};
versi minify
async function hashStringSHA256(r){try{let t=new TextEncoder,n=t.encode(r),e=await crypto.subtle.digest("SHA-256",n),a=Array.from(new Uint8Array(e)),i=a.map(r=>r.toString(16).padStart(2,"0")).join("");return i}catch(s){return console.error("Error hashing string:",s.message),null}}
testing
hashStringSHA256("admin12345").then((hash) => {
console.log(hash)
});
(async () => {
let hash = await hashStringSHA256("admin12345");
console.log(hash)
})();
Versi Nodejs
import {
createHash
} from 'crypto';
// String yang akan di-hash
const data = "Ini adalah string yang ingin di-hash";
// Membuat hash menggunakan algoritma SHA-256
const hash = createHash('sha256').update(data).digest('hex');
console.log("Hasil hash:", hash);