码迷,mamicode.com
首页 > Web开发 > 详细

js中的web加密

时间:2019-02-06 22:25:44      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:star   mod   base64   rsa   int   crypto   return   xid   array   

js中的web加密

window.crypto.subtle只会在安全模式下有用,也就是https环境下

  1. 创建摘要(硬解)

    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);
    })
  2. 创建摘要(软解)

    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(‘‘));
    });
  3. 加密随机数

    var arr = new Uint8Array(5);
    crypto.getRandomValues(arr);
  4. 创建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) + ‘\n‘;
            str = str.substring(64);
        }
        return finalString;
    }
    
    function toPem(privateKey) {
        var b64 = addNewLines(arrayBufferToBase64(privateKey));
        var pem = "-----BEGIN PRIVATE KEY-----\n" + 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+QFZAn9GRXiben9W05XmSa5wwKBgQDYsDaVvJdR5yYU6pkcgDnr7NZ9RAMPraVz
        dZvbzvIwZcOE1tBhCFODbQsPObWkLFFinaWiAUZOIIur858UJxWSCZVqgHg6bk9n
        F7+Hw+4T/VnrurqNY1H4IY/5bFPqArXrat5b49CGfj/C2Se/WUG5p8bt/cY4HLbg
        0HgGd7ki1wKBgQDEDKtLIKXsw7lez8dvuY4HYNHn+ri/oIHzOgXvg8+WbmRHokFL
        7zgJdsdROXXhekedfr4fRI8nQ/Dl4EkSsnA8LHzF9knXVxK0A/OKss87VjlGnJS0
        SeiDfc/9J+ezs776PQIP3IcVfviMIrBlQU7gMaLho8EyO6GBWJhF06wY6QKBgChv
        yd/rj7mDD0I7/VKqQyTZz7UUqhWU7Bk9y1YbqmqJsxDpHX3eFeeiw7uVo2X9tzpV
        /QDciAgwXqA6GGekW4wjKbT0QHt29m5gqidl0tn8H3m0IPgdnsBVUw7Svl4fH1/N
        U62GN/XBPZjY+Wfl+jPxMVhcUU9LXH1bqepbETuFAoGAQiHF8bPTSqPcCQ0AvQzG
        h5RK/K1LkoATXkxgJY+Te7jws6Ru/U6mFD7KDeUw3GeuSiMYZY/9eUnOq0WKfNg4
        fg4S7vqYvzyISdMj77CyHhQPcnZ6KqtdBS2D3NPqf/aG9OjfftRDXe0kZP0v0YNF
        DU2EjlbkOZPIVrZZ0THSUIo=
        -----END PRIVATE KEY-----
  5. 使用上面创建的私钥

    var pkey = 
    `-----BEGIN PRIVATE KEY-----
    MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDVh3Q1faf2SSsF
    M8yVqSCTgSSdEpbRepE2mz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HYNHn+ri/oIHzOgXvg8+WbmRHokFL
    7zgJdsdROXXhekedfr4fRI8nQ/Dl4EkSsnA8LHzF9knXVxK0A/OKss87VjlGnJS0
    SeiDfc/9J+ezs776PQIP3IcVfviMIrBlQU7gMaLho8EyO6GBWJhF06wY6QKBgChv
    yd/rj7mDD0I7/VKqQyTZz7UUqhWU7Bk9y1YbqmqJsxDpHX3eFeeiw7uVo2X9tzpV
    /QDciAgwXqA6GGekW4wjKbT0QHt29m5gqidl0tn8H3m0IPgdnsBVUw7Svl4fH1/N
    U62GN/XBPZjY+Wfl+jPxMVhcUU9LXH1bqepbETuFAoGAQiHF8bPTSqPcCQ0AvQzG
    h5RK/K1LkoATXkxgJY+Te7jws6Ru/U6mFD7KDeUw3GeuSiMYZY/9eUnOq0WKfNg4
    fg4S7vqYvzyISdMj77CyHhQPcnZ6KqtdBS2D3NPqf/aG9OjfftRDXe0kZP0v0YNF
    DU2EjlbkOZPIVrZZ0THSUIo=
    -----END PRIVATE KEY-----`
    
    function removeLines(str) {
        return str.replace("\n", "");
    }
    
    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加密

标签:star   mod   base64   rsa   int   crypto   return   xid   array   

原文地址:https://www.cnblogs.com/ye-hcj/p/10354164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!