Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/471.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在Nodejs中加密,并使用webcryptoapi在客户端上解密_Javascript_Node.js_Encryption_Cryptography_Webcrypto Api - Fatal编程技术网

Javascript 在Nodejs中加密,并使用webcryptoapi在客户端上解密

Javascript 在Nodejs中加密,并使用webcryptoapi在客户端上解密,javascript,node.js,encryption,cryptography,webcrypto-api,Javascript,Node.js,Encryption,Cryptography,Webcrypto Api,我正在尝试创建以下流: 在客户端上创建密钥对 将公钥发送到服务器(nodejs) 使用WebCryptoAPI polyfill加密服务器上的字符串 将加密数据发送回客户端进行解密 我正在(很长一段时间)为数据类型而挣扎 下面是代码,首先生成密钥(客户端): 然后要导出: // function to export the generate publicKey const exportPublicKey = (publicKey) => { crypto.exportKey('jw

我正在尝试创建以下流:

  • 在客户端上创建密钥对
  • 将公钥发送到服务器(nodejs)
  • 使用WebCryptoAPI polyfill加密服务器上的字符串
  • 将加密数据发送回客户端进行解密
  • 我正在(很长一段时间)为数据类型而挣扎

    下面是代码,首先生成密钥(客户端):

    然后要导出:

    // function to export the generate publicKey
    const exportPublicKey = (publicKey) => {
        crypto.exportKey('jwk', publicKey)
            .then((keydata) => {
                fetch('/key2', {
                    method : 'POST',
                    mode : 'cors',
                    body : JSON.stringify(keydata),
                    headers : new Headers({
                        'Content-Type' : 'application/json'
                    })
                }).then(res => res.json())
                .catch(err => console.error(err))
                .then(res => console.log(res));
                console.log(keydata);
            })
            .catch((err) => {
                console.log(err);
        });
    };
    
    保存密钥:

    app.post('/key2', (req, res) => {
        webcrypto.subtle.importKey(
            'jwk', req.body, 
            {
                name : 'RSA-OAEP',
                hash : {name : 'SHA-256'},
            },
            false,
            ['encrypt']
        ).then((publicKey) => {
            keyStorage.setItem('alicePubKey', publicKey);
            if(publicKey == keyStorage.getItem('alicePubKey'));
            res.json({ 'success' : 'key received and saved' });
            console.log('saved key from client: ' + publicKey);
            return; 
        })
        .catch((err) => {
            console.error(err);
        });
    });
    
    在服务器上加密:

    app.get('/challenge', (req, res) => {
        let challengeFromServer = null;
        let key = keyStorage.getItem('alicePubKey');
        let buf = new Buffer.from('decryptthis!');
    
        webcrypto.subtle.encrypt(
            {
                name : 'RSA-OAEP'
            }, key, buf
        )
        .then((encrypted) => {
            console.log('challenge created: ' + encrypted);
            res.json({'challenge' : new Uint8Array(encrypted) })
        })
        .catch((err) => {
            console.error(err);
        })
    
    获取加密数据并解密-不工作:)

    以下几行是我认为的问题

    console.log(ArrayBuffer.isView(data.challenge)) // false
    console.log(new ArrayBuffer(data.challenge)) // empty
    
    小更新:

        res.json(
            {'challenge' : encrypted , // {} empty
            'uint' : new Uint8Array(encrypted), // {0: 162, 1: 252, 2: 113, 3: 38, .......
            'stringify' : JSON.stringify(encrypted), //  "{}" empty
            'toString' : encrypted.toString() // "[object ArrayBuffer]"
        });
    

    考虑看一看为您处理交换问题的更高级别的库;例如js jose或PKIjs。

    已解决

    问题在于数据类型

    如果任何人有此问题,解决方法是确保您在服务器上发送密文作为缓冲区,my express应用程序:

    res.write(new Buffer(encrypted), 'binary')
    res.end(null, 'binary')
    
    在客户端接收并解码,如下所示:

    const decryptedReadable = new TextDecoder().decode(decrypted)
    

    愉快的编码。

    要加密和解密,您需要在两个部分之间拥有一个共享密钥对称密钥工作得很好@AbdeslemCharifWhy不仅使用HTTPS,它还提供了完整的e2e加密。@zaph这是一个更大的身份验证项目的一部分
    res.write(new Buffer(encrypted), 'binary')
    res.end(null, 'binary')
    
    const decryptedReadable = new TextDecoder().decode(decrypted)