1

我正在尝试使用静态 RSA 公钥来加密会话生成的 AES 密钥,然后用于加密密码,并且随机生成的 AES 会话密钥输入 RSA 加密密码有以下错误消息:

TypeError: Failed to execute 'encrypt' on 'SubtleCrypto': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'

我尝试将随机生成的 AES 密钥数据(通过导出)转换为 Uint8Array 缓冲区,然后再将其转换为 ArrayBuffer 以在 RSA 加密代码中使用,但不知何故它不起作用。

在@pedrofb 的帮助下设法转换数组缓冲区字段后,我尝试将所有结果拉到一个统一字段中,以便集中存储处理后的输出,这会产生不一致的输出。

这是修改后的源代码,它修复了失败的执行,但产生了另一个问题,即在 HTML“输入”字段中没有一致的输出值。HTML 输入字段仅显示在所有操作中收集的部分数据。我正在尝试使用“隐藏”字段作为一种收集器来收集所有已处理的结果,但是当我将处理后的结果转移到非隐藏字段时,它只显示为部分。

<html>
    <body>
        <script>
            var secBuff = null;         
            function encryptPassword(rsaPublicKeyModulusHex, password) {
                var enc = new TextEncoder();
                var iv = window.crypto.getRandomValues(new Uint8Array(16));
                document.getElementById("a").value = buff2hex(iv);
                var b64UrlPEM = h2b64("30820122300d06092a864886f70d01010105000382010f003082010a0282010100" + rsaPublicKeyModulusHex + "0203010001", true);
                var binaryDerStr = window.atob(b64UrlPEM);
                var binDERData = str2ab(binaryDerStr);

                // Generate session AES key and encrypt password/pin
                window.crypto.subtle.generateKey(
                    {
                        name: "AES-CBC",
                        length: 256,
                    },
                    true,
                    ["encrypt", "decrypt"]
                )
                .then(function(key){

                    // Export AES Session Key bytes
                    window.crypto.subtle.exportKey("raw", key)
                    .then(function(data){
                        // Convert AES Session secret key to buffer object
                        secBuff = typedArrayToBuffer(new Uint8Array(data));

                        // Import RSA Public Modulus
                        window.crypto.subtle.importKey(
                            "spki",
                            binDERData,
                            {
                                name: "RSA-OAEP",
                                hash: "SHA-256"
                            },
                            false,
                            ["encrypt"]
                        )
                        .then(function(publicKey){

                            // Encrypt AES session key with public key
                            window.crypto.subtle.encrypt(
                                {
                                    name: "RSA-OAEP"
                                },
                                publicKey, // from above imported RSA Public Key
                                secBuff    // ArrayBuffer of session secret key
                            )
                            .then(function(encrypted){
                                var pre = document.getElementById("a").value;
                                document.getElementById("a").value = pre + buff2hex(new Uint8Array(encrypted));
                            })
                            .catch(function(err){
                                console.error(err);
                            });

                        })
                        .catch(function(err){
                            console.error(err);
                        });
                    })
                    .catch(function(err){
                        console.error(err);
                    });

                    // Encrypt plaintext from somewhere
                    window.crypto.subtle.encrypt(
                        {
                            name: "AES-CBC",
                            iv
                        },
                        key,
                        enc.encode(password)
                    )
                    .then(function(encrypted){
                        var pre = document.getElementById("a").value;
                        document.getElementById("a").value = pre + buff2hex(new Uint8Array(encrypted));
                    })
                    .catch(function(err){
                        console.error(err);
                    });
                })
                .catch(function(err){
                    console.error(err);
                });
            }

            function h2b64(hex, url) {
                var output = btoa(hex.match(/\w{2}/g).map(function(a) {
                    return String.fromCharCode(parseInt(a, 16));
                }).join(""));
                if (url) {
                    output = output.replace(/=/g,"");
                }
                return output;
            }

            function str2ab(str) {
                const buf = new ArrayBuffer(str.length);
                const bufView = new Uint8Array(buf);
                for (let i = 0, strLen = str.length; i < strLen; i++) {
                    bufView[i] = str.charCodeAt(i);
                }
                return buf;
            }

            function typedArrayToBuffer(array) {        
                return array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset);
            }

            function buff2hex(buffer) {
                return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
            }
        </script>
        <input type="hidden" id="a">
        </input>
        <textarea rows="4" cols="50" id="b">
        </textarea>
        <script>
            var blob = encryptPassword('b1cea3fd81bdd475315fda596dee95bd4b54d2954b936fee143689cc7936d5400eecf201b18f016ce307b43d4eeb6e7794c74731d907a37517e055850984db5d3f065902e190e469f004d1ed0ceb7696db98026053aa0323b24657c8351bd09510c54b174fb11c0f8ea0c59bdda93597a2176281b7b12c43fd29330cba45ce9ce533ef62450d21222938e4dfdf08a18a38ebb58ea9809a7ba4f129e3df8f2adb65870c906b8a5d89d4d6a8bf4e54c604c0f43ad92403ce1fa1ac7cac1070dc28072cb90d19ee48c0664225bf9fb24af47924a7b3a15f183a3c330999ed3d9d318efcbbd2fd586a1edd232f9f4cef01db79ae1f00bfc705bf5e3e621ad081a3a5', 'abc');
            document.getElementById("b").value = document.getElementById("a").value;
        </script>
    </body>
</html>

以下是存档出现问题的原始源代码:

<html>
    <body onload="encryptPassword('b1cea3fd81bdd475315fda596dee95bd4b54d2954b936fee143689cc7936d5400eecf201b18f016ce307b43d4eeb6e7794c74731d907a37517e055850984db5d3f065902e190e469f004d1ed0ceb7696db98026053aa0323b24657c8351bd09510c54b174fb11c0f8ea0c59bdda93597a2176281b7b12c43fd29330cba45ce9ce533ef62450d21222938e4dfdf08a18a38ebb58ea9809a7ba4f129e3df8f2adb65870c906b8a5d89d4d6a8bf4e54c604c0f43ad92403ce1fa1ac7cac1070dc28072cb90d19ee48c0664225bf9fb24af47924a7b3a15f183a3c330999ed3d9d318efcbbd2fd586a1edd232f9f4cef01db79ae1f00bfc705bf5e3e621ad081a3a5', 'abc')">
        <script>
            var secBuff = null;
            function encryptPassword(rsaPublicKeyModulusHex, password) {                
                var enc = new TextEncoder();
                var iv = window.crypto.getRandomValues(new Uint8Array(16));
                var b64UrlPEM = h2b64("30820122300d06092a864886f70d01010105000382010f003082010a0282010100" + rsaPublicKeyModulusHex + "0203010001", true);
                var binaryDerStr = window.atob(b64UrlPEM);
                var binDERData = str2ab(binaryDerStr);

                // Generate session AES key and encrypt password/pin
                window.crypto.subtle.generateKey(
                    {
                        name: "AES-CBC",
                        length: 256,
                    },
                    true,
                    ["encrypt", "decrypt"]
                )
                .then(function(key){

                    // Export AES Session Key bytes
                    window.crypto.subtle.exportKey("raw", key)
                    .then(function(data){
                        // Convert AES Session secret key to buffer object
                        secBuff = typedArrayToBuffer(new Uint8Array(data));
                    })
                    .catch(function(err){
                        console.error(err);
                    });

                    // Encrypt plaintext from somewhere
                    window.crypto.subtle.encrypt(
                        {
                            name: "AES-CBC",
                            iv
                        },
                        key,
                        enc.encode(password)
                    )
                    .then(function(encrypted){
                        console.log("IV: " + iv);
                        console.log("Ciphertext: " + new Uint8Array(encrypted));
                    })
                    .catch(function(err){
                        console.error(err);
                    });
                })
                .catch(function(err){
                    console.error(err);
                });

                // Import RSA Public Modulus
                window.crypto.subtle.importKey(
                    "spki",
                    binDERData,
                    {
                        name: "RSA-OAEP",
                        hash: "SHA-256"
                    },
                    false,
                    ["encrypt"]
                )
                .then(function(publicKey){

                    // Encrypt AES session key with public key
                    window.crypto.subtle.encrypt(
                        {
                            name: "RSA-OAEP"
                        },
                        publicKey, // from above imported RSA Public Key
                        secBuff    // ArrayBuffer of session secret key
                    )
                    .then(function(encrypted){
                        console.log(new Uint8Array(encrypted));
                    })
                    .catch(function(err){
                        console.error(err);
                    });

                })
                .catch(function(err){
                    console.error(err);
                });             
            }

            function h2b64(hex, url) {
                var output = btoa(hex.match(/\w{2}/g).map(function(a) {
                    return String.fromCharCode(parseInt(a, 16));
                }).join(""));
                if (url) {
                    output = output.replace(/=/g,"");
                }
                return output;
            }

            function str2ab(str) {
                const buf = new ArrayBuffer(str.length);
                const bufView = new Uint8Array(buf);
                for (let i = 0, strLen = str.length; i < strLen; i++) {
                    bufView[i] = str.charCodeAt(i);
                }
                return buf;
            }

            function typedArrayToBuffer(array) {                
                if (array.constructor === Uint8Array) {
                    console.log("Uint8Array input: " + array);
                    console.log(array.byteLength);
                } else {
                    console.log("Uint8Array input NOT detected ...");
                }               
                return array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset);
            }
        </script>
    </body>
</html>
4

1 回答 1

1

您的代码的第二部分(导入 RSA Public Modulus)与第一部分同时运行(因为 webcrypto 承诺是异步的),因此secBuff变量未初始化。

确保调用以// Import RSA Public Modulusafter开头的部分secBuff = typedArrayToBuffer (new Uint8Array (data));

// Export AES Session Key bytes
window.crypto.subtle.exportKey("raw", key)
    .then(function(data){
         // Convert AES Session secret key to buffer object
         secBuff = typedArrayToBuffer(new Uint8Array(data));
         //Call Import RSA Public Modulus here
     })
于 2019-09-23T08:14:44.360 回答