L o a d i n g . . .
主打一个C++
文章详情

本地js代码RSA-OAEP加密与解密

Posted on 2022-03-25 11:25:03 by 主打一个C++

加解密方案千千万,这次玩玩RSA

RSA-OAEP(RSA Optimal Asymmetric Encryption Padding)是一种用于公钥加密的填充方案,它结合了RSA加密算法和OAEP填充机制。

其主要用途是确保在使用RSA进行加密时,能够提供更强的安全性。

OAEP填充方案通过在加密前对数据进行随机填充和哈希操作,增加了加密数据的安全性,防止了某些类型的攻击,如重放攻击和选择明文攻击。

因此,RSA-OAEP通常用于安全地传输对称密钥或者较小的数据块。

下面是测试代码通过代码:

image.png

 // 使用RSA-OAEP异步解密数据的函数
        async function decryptWithRSAOAEP(encryptedData, privateKey) {

            // 将Base64格式的私钥转换为ArrayBuffer
            const privateKeyBuffer = base64ToArrayBuffer(privateKey);

            // 导入私钥为CryptoKey对象
            const importedPrivateKey = await crypto.subtle.importKey(
                 // 导入格式,具体取决于密钥格式
                'pkcs8',
                privateKeyBuffer,
                {
                    name: 'RSA-OAEP',
                    // 模数长度,应与密钥生成时的一致
                    modulusLength: 2048,
                    // 公共指数,通常是 65537
                    publicExponent: new Uint8Array([1, 0, 1]),
                    // 哈希函数,应与加密时的一致
                    hash: 'SHA-256'
                },
                // 提取密钥材料,这里设置为true
                true,
                // 密钥用途,这里是解密
                ['decrypt'] 
            );

            // 将Base64格式的加密数据转换为ArrayBuffer
            const encryptedDataBuffer = base64ToArrayBuffer(encryptedData);

            // 使用导入的私钥解密数据
            const decryptedDataBuffer = await crypto.subtle.decrypt(
                {
                    name: 'RSA-OAEP'
                },
                importedPrivateKey,
                encryptedDataBuffer
            );

            // 将解密后的数据Buffer转换为文本并返回
            return new TextDecoder().decode(decryptedDataBuffer);
        }

        // 将Base64字符串转换为ArrayBuffer的函数
        function base64ToArrayBuffer(base64) {
            const binaryString = atob(base64);
            const len = binaryString.length;
            const bytes = new Uint8Array(len);
            for (let i = 0; i < len; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }
            return bytes.buffer;
        }

        // 生成RSA-OAEP密钥对的异步函数
        async function generateKey() {
            return await window.crypto.subtle.generateKey(
                {
                    name: "RSA-OAEP",
                    // 密钥位数
                    modulusLength: 2048, 
                    // 65537
                    publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
                    // 哈希算法
                    hash: { name: "SHA-256" } 
                },
                // 密钥是否可以被提取
                true, 
                 // 用途
                ["encrypt", "decrypt"] 
            );
        }

        // 使用公钥异步加密数据的函数
        async function encryptData(publicKey, data) {
    
            // 创建TextEncoder对象对数据进行编码
            const encoder = new TextEncoder();
            const encodedData = encoder.encode(data);

            // 使用公钥加密数据
            const encrypted = await crypto.subtle.encrypt(
                {
                    name: "RSA-OAEP"
                },
                publicKey,
                encodedData
            );

            // 返回加密后的数据Buffer
            return encrypted;
        }

        // 立即执行表达式,用于生成密钥,加密和解密数据
        (async () => {
            try {
     
                // 生成RSA-OAEP密钥对
                const keyPair = await generateKey();

     
                // 获取公钥
                const publicKey = keyPair.publicKey;

       
                // 定义要加密的文本
                const textToEncrypt = "测试数据加密与解密!";

       
                // 使用公钥加密文本
                const encryptedData = await encryptData(publicKey, textToEncrypt);

                // 将加密后的数据Buffer转换为Base64格式
                const encryptedDataBase64 = await arrayBufferToBase64(encryptedData);
                console.log("加密后的数据(Base64):", encryptedDataBase64);

 
                // 导出私钥为ArrayBuffer
                const privateKey = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey);
                const privateKeyBase64 = await arrayBufferToBase64(privateKey);

   
                // 使用私钥解密Base64格式的加密数据,并处理解密结果
                decryptWithRSAOAEP(encryptedDataBase64, privateKeyBase64)
                    .then(decryptedText => console.log('解密后的文本:', decryptedText))
                    .catch(error => console.error('解密失败:', error));

            } catch (error) {
                console.error("加密过程中发生错误:", error);
            }
        })();

        // 将ArrayBuffer转换为Base64字符串的函数
        function arrayBufferToBase64(buffer) {
            return new Promise((resolve, reject) => {
                const blob = new Blob([buffer]);
                const reader = new FileReader();
                reader.onload = () => resolve(reader.result.split(',')[1]);
                reader.onerror = () => reject(new Error('Failed to read file'));
                reader.readAsDataURL(blob);
            });
        }


*转载请注明出处:原文链接:https://cpp.vin/page/129.html

作者近期文章
提示
×
确定
数据库执行: 8次 总耗时: 0.01s
页面加载耗时: 



wechat +447752296473
wechat cpp-blog