WebCrypto 执行问题,由于数据类型错误而失败,并在统一字段中编译所有处理结果

WebCrypto execution problem with failure due to data type error and compiling all processed results in a unified field

我正在尝试使用静态 RSA Public 密钥来加密会话生成的 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 的帮助下设法转换 Array Buffer 字段后,我试图将所有结果拉入一个统一的字段,以便集中存储已处理的输出,但输出不一致。

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

<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>

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

确保在 secBuff = typedArrayToBuffer (new Uint8Array (data));

之后调用以 // Import RSA Public Modulus 开头的部分
// 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
     })