html做校园网站,拖拽式网站建设哪家专业,wordpress 小工具插件下载地址,上海设计展2021室内设计deriveKey 方法的完整示例#xff0c;演示如何使用 HMAC 作为密钥派生函数#xff08;KDF#xff09;来从一个给定的秘密#xff08;如密码#xff09;派生出一个新的 AES 加密密钥。
//创建一个函数来生成随机盐function getRandomSalt(length){let arraynew Uint8Array…deriveKey 方法的完整示例演示如何使用 HMAC 作为密钥派生函数KDF来从一个给定的秘密如密码派生出一个新的 AES 加密密钥。
//创建一个函数来生成随机盐function getRandomSalt(length){let arraynew Uint8Array(length);window.crypto.getRandomValues(array);return array;}//生成随机数字function randomFloat(){const fooArraynew Uint32Array(1);const maxUint320xFFFFFFFF;return crypto.getRandomValues(fooArray)[0];}//生成随机密码导入密钥当中function getKeyMaterial(){//const passwordwindow.prompt(请输入你的密码);//就是为加密时用密码//这里不用输入密码我们采用随机生成的数字这样可以增加破解难度提升安全性const passwordrandomFloat();const encnew TextEncoder();return window.crypto.subtle.importKey(raw,enc.encode(password),PBKDF2,false,[deriveBits,deriveKey]);}
//创建一个函数来派生密钥async function deriveAeskey(salt,info,keyLength){//生成已有密钥//不能直接用new Textcoder().encoder(password)这样来生成密码必须用这个函数的importKey导入密钥才行const passwordBufferawait getKeyMaterial();const derivedKeyawait crypto.subtle.deriveKey({name:PBKDF2,salt:salt,iterations:10000,hash:SHA-256},passwordBuffer,{name:AES-GCM,length:keyLength},true,[encrypt,decrypt]);return derivedKey;}//使用派生的密钥进行加密async function encryptData(derivedKey,dataToEncrypt){const encodernew TextEncoder();const dataBufferencoder.encode(dataToEncrypt);const ivwindow.crypto.getRandomValues(new Uint8Array(12));const encryptionawait crypto.subtle.encrypt({name:AES-GCM,iv:iv},derivedKey,dataBuffer);return {ciphertext:encryption,iv:Array.from(iv)}}//使用派生的密钥进行解密async function decryptData(derivedKey,ciphertext,iv){const decryptedawait crypto.subtle.decrypt({name:AES-GCM,iv:new Uint8Array(iv)},derivedKey,ciphertext);const decodernew TextDecoder();return decoder.decode(decrypted);}//最后把他们综合到一起进行加密和解密以及做加密后内容的演式(async function(){const saltgetRandomSalt(16);const infonew Uint8Array();const keyLength256;try{//派生的密钥const derivedKeyawait deriveAeskey(salt,info,keyLength);//需要加密的数据const dataToEncryptthis is data;const {ciphertext,iv}await encryptData(derivedKey,dataToEncrypt);//这里是演式你加密后的数据样式console.log(String.fromCharCode(...new Uint8Array(ciphertext)));//解密数据const decryptedDataawait decryptData(derivedKey,ciphertext,iv);console.log(解密数据,decryptedData);}catch(error){console.log(加解密时发生错误,error);}})();