js中的web加密
Posted 叶家伟的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js中的web加密相关的知识,希望对你有一定的参考价值。
js中的web加密
window.crypto.subtle只会在安全模式下有用,也就是https环境下
创建摘要(硬解)
var i = new TextEncoder(‘utf-8‘).encode("Hello World!"); crypto.subtle.digest(‘SHA-256‘, i).then(function(digest) { var view = new DataView(digest); var str = ‘‘; for(var i = 0; i < view.byteLength; i++) { var b = view.getUint8(i); str += ‘0123456789abcdef‘[(b & 0xf0) >> 4]; str += ‘0123456789abcdef‘[(b & 0x0f)]; } console.log(str); // 7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069 var arr = new Uint8Array(digest); console.log(arr); }).catch(function(err) { console.log(err); })
创建摘要(软解)
const text = ‘Hello World!‘; const encoder = new TextEncoder(); const data = encoder.encode(text); window.crypto.subtle.digest(‘SHA-256‘, data).then(digestValue => { const byteArray = new Uint8Array(digestValue); const hexCodes = [...byteArray].map(value => { const hexCode = value.toString(16); const paddedHexCode = hexCode.padStart(2, ‘0‘); return paddedHexCode; }); console.log(hexCodes.join(‘‘)); });
加密随机数
var arr = new Uint8Array(5); crypto.getRandomValues(arr);
创建PEM格式的RSA-OAEP私钥
function arrayBufferToBase64(arrayBuffer) { var byteArray = new Uint8Array(arrayBuffer); var byteString = ""; for(var i = 0; i < byteArray.byteLength; i++) { byteString += String.fromCharCode(byteArray[i]); } var b64 = window.btoa(byteString); return b64 } function addNewLines(str) { var finalString = ‘‘; while(str.length > 0) { finalString += str.substring(0, 64) + ‘ ‘; str = str.substring(64); } return finalString; } function toPem(privateKey) { var b64 = addNewLines(arrayBufferToBase64(privateKey)); var pem = "-----BEGIN PRIVATE KEY----- " + b64 + "-----END PRIVATE KEY-----" return pem; } window.crypto.subtle.generateKey( { name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), hash: {name: "SHA-256"} }, true, ["encrypt", "decrypt"] ).then(function(keyPair){ window.crypto.subtle.exportKey("pkcs8", keyPair.privateKey).then(function(exportedPrivateKey){ var pem = toPem(exportedPrivateKey); console.log(pem); }).catch(function(err){ console.log(err); }) }) 运行上面代码 -----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDVh3Q1faf2SSsF M8yVqSCTgSSdEpbRepE2mzG03mq2CUpu+yGJo2U+JyqVJVorcFRBcu5fLNtXrizp cMu5AsYSJ60HXi4us3UlIIDJm+lLVCYzD3C8bttGUglbTDo3JY1xrQ+1SVCjop33 NSBgmSl48q0zLKz9r9g7hk+cRPQ5xiDn9pP7N3tIC+dVJg+wlT79XJ4bkHQo/wA7 aNKb27MJ0pKKZXDl2iDjKxryVATunzBHbmoQ0je3iQwS2Eup9UHH/STO0Gzn81jr 0fpqtZsRSfpzBwgqKgckDQkW5TB9Bn9mhM/lnYU3PBlnea3ohLaxGc+RQy2IC4oA 3dCnHOjFAgMBAAECggEAZG6umQ4+NxgZFPxVKLuA6AAhIYQBzguRS5bZXVIT7QUX rnWOQ7fHweEYJUiJTc8qwhH1zmxBys7Qrwfvulh0o0toFgQVQsADxG+yQ6GCrHyq 7u8/PlIB7uRdJEUJSLDwA1y7+6+9LwootIKXdPf1Sr8R+fT0dOoFkZHN1hmUqasL ch95JLkCJZ8ELZU2IJ5H8R4qDDRiUI1/zaGAFO1DCbGNRWpqTs/MVMTp7wMh3oN0 ZYFGgmibWv8WALxpsSX+mT9JkPHn7ljlXNVWfi+J1qy8h6YcQW4nArcDPpomPIpN 9y3UfsHOHSE39d5AGEWhw2syk+PxSaKnqbW6nrGeDQKBgQD8RIPt9x5n/hnJpCaE 5o46qUrlYkIJk49t73Bqhr2k1StbaUFu9qF9G+PP/hsJRPJEWXyKvVfb6BNZsgbP gPMbBmsXwnobd+XWqChx6HJE09obF1GSQjXov/t4nFzdNxTrXzhMjbyTw4N72CyX 1+QFZAn9GRXiben9W05XmSa5wwKBgQDYsDaVvJ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H3m0IPgdnsBVUw7Svl4fH1/N U62GN/XBPZjY+Wfl+jPxMVhcUU9LXH1bqepbETuFAoGAQiHF8bPTSqPcCQ0AvQzG h5RK/K1LkoATXkxgJY+Te7jws6Ru/U6mFD7KDeUw3GeuSiMYZY/9eUnOq0WKfNg4 fg4S7vqYvzyISdMj77CyHhQPcnZ6KqtdBS2D3NPqf/aG9OjfftRDXe0kZP0v0YNF DU2EjlbkOZPIVrZZ0THSUIo= -----END PRIVATE KEY-----` function removeLines(str) { return str.replace(" ", ""); } function base64ToArrayBuffer(b64) { var byteString = window.atob(b64); var byteArray = new Uint8Array(byteString.length); for(var i = 0; i < byteString.length; i++) { byteArray[i] = byteString.charCodeAt(i); } return byteArray; } function pemToArrayBuffer(pem) { var b64Lines = removeLines(pem); var b64Prefix = b64Lines.replace("-----BEGIN PRIVATE KEY-----", ‘‘); console.log(b64Prefix) var b64Final = b64Prefix.replace("-----END PRIVATE KEY-----", ‘‘); return base64ToArrayBuffer(b64Final); } window.crypto.subtle.importKey( "pkcs8", pemToArrayBuffer(pkey), {name: "RSA-OAEP", hash: {name: "SHA-256"}}, true, [‘decrypt‘] ).then(function(importedPrivateKey){ console.log(importedPrivateKey); }).catch(function(err){ console.log(err); })
以上是关于js中的web加密的主要内容,如果未能解决你的问题,请参考以下文章