0


js实现rsa密钥的加密、解密与生成

今天想用js实现rsa的加解密的,在网上找了好久,下载啊什么的,十分麻烦,今天我也不bb的直接放代码

rsa.html

<!DOCTYPE html>
<html lang="zh-Cn">

    <head>
        <title>javascript-rsa-Example</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <!-- 导入必要js文件 -->
        <script src="jquery.js"></script>
        <script src="jsencrypt.min.js"></script>
        
    </head>
    <body> 
        <!-- 一个私钥的例子 -->
        <textarea id="privkey" rows="15" cols="65" style="display: none;">-----BEGIN RSA PRIVATE KEY-----
            MIICXgIBAAKBgQDQ/Mgm9uPiUpmUvA4l/254RMPU55Vu7FVewhd1fjn8qKhvSo7B
            sYpY11MaUuIoSsSvnJcvg8x6kZU1I1ohB4IgkXQhsVsBstr+abLKBNebr5LX5qBn
            ARlJ/ZZLrSlIi97c//86cJpmLOF94KzKI9vm98CHN32I7UxaBZs9epMDeQIDAQAB
            AoGBAIAnQqWCKGQUutEWMKbkZ92gbWYVTPFkQ0WER9ZovS5OTltQoRHtySSJhhBS
            WxTSJKJ7p8ofTDitJY4cS5yNeiFaXdA3C/E+M0KgNOhTIkaKMh1KrkOrDvff3oIp
            TT40/g9fO8QorIWp0CRWVE+qEG8gHhFLnj5ST2jxqVChQPrBAkEA9bwlzWmNsWG6
            nCn/9Hh1IRzjZAHrle2H8gtiPYKScrzsvkNNlEA1vFoUFjfMWklvRTZQbpJE05rS
            7azAKicSzQJBANm3qWfG5jhUVrZtPeWZacu8kGs0n0lQ/c285CMwVU9aUu760HkT
            siuK3WeJ31lOOVF6YbvZv60PZtQjx5Kb610CQAz9DOJ2mc6uY7atYaICW+6MIFjA
            4TrjezQH9gFaTXNTGRBVblxPqId0G2uxN1PuXbtCy62MfabRoCR/5QhVWGECQQCr
            KzdX7Mtxe/VUpZxlV/ESieStNIkK9k8kop5mgAiCQ8wyMSUYHAEXNK0PSxk7OEHe
            Ki6OpwqIgDRjEuJEBKvNAkEA7hQfSDCuDl4Cf5apfUyMH6eY1WNMexyZFcp+1njb
            VLQRL9rtbEeTCuZ/vsrA94HwlGx0CmSrinl0sA+cZg25xQ==
            -----END RSA PRIVATE KEY-----
            
        </textarea><br/>
        <!-- 一个公钥的例子 -->
        <textarea id="pubkey" rows="15" cols="65" style="display: none;">-----BEGIN PUBLIC KEY-----
            MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQ/Mgm9uPiUpmUvA4l/254RMPU
            55Vu7FVewhd1fjn8qKhvSo7BsYpY11MaUuIoSsSvnJcvg8x6kZU1I1ohB4IgkXQh
            sVsBstr+abLKBNebr5LX5qBnARlJ/ZZLrSlIi97c//86cJpmLOF94KzKI9vm98CH
            N32I7UxaBZs9epMDeQIDAQAB
            -----END PUBLIC KEY-----            
        </textarea><br/>
        <label for="privateKey_out">生成的rsa私钥</label>
        <textarea id="privateKey_out" rows="15" cols="65"></textarea><br/>
        <label for="publicKey_out">生成的rsa公钥</label>
        <textarea id="publicKey_out" rows="15" cols="65"></textarea><br/>
    </body>
    <script type="text/javascript">
        //*****这里开始介绍如何生成"密钥和公钥"!!!***********
    function getRsaKeys(func){
    window.crypto.subtle.generateKey(
        {
            name: "RSA-OAEP",
            modulusLength: 2048, //可以是 1024, 2048, or 4096
            publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
            hash: {name: "SHA-512"}, //可以是 "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
        },
        true, //密钥是否可提取 (i.e. 可以在 exportKey中使用)
        ["encrypt", "decrypt"] //一定要是["encrypt", "decrypt"] 或者 ["wrapKey", "unwrapKey"]
    ).then(function(key){
        window.crypto.subtle.exportKey(
            "pkcs8", 
            key.privateKey 
        ).then(function(keydata1){
            window.crypto.subtle.exportKey(
                "spki",
                key.publicKey 
            ).then(function(keydata2){
                var privateKey = RSA2text(keydata1,1);
                var publicKey = RSA2text(keydata2);
                func(privateKey,publicKey);
            }).catch(function(err){
                console.error(err);
            });
        })
        .catch(function(err){
            console.error(err);
        });
    })
    .catch(function(err){
        console.error(err);
    });
    }
    function RSA2text(buffer,isPrivate=0) {
        var binary = '';
        var bytes = new Uint8Array(buffer);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        var base64 = window.btoa(binary);
        var text = "-----BEGIN "+(isPrivate?"PRIVATE":"PUBLIC")+" KEY-----\n";
        text += base64.replace(/[^\x00-\xff]/g,"$&\x01").replace(/.{64}\x01?/g,"$&\n");
        text += "\n-----END "+(isPrivate?"PRIVATE":"PUBLIC")+" KEY-----";
        return text;
    }
    function displayRsaKeys(privateKey,publicKey) {
        privateKey_example1=privateKey;//得到rsa密钥和私钥!
        publicKey_example1=publicKey;
        document.getElementById("privateKey_out").innerHTML = privateKey_example1;//输出
        document.getElementById("publicKey_out").innerHTML = publicKey_example1;

    }
    getRsaKeys(displayRsaKeys);
    
    //*****这里开始介绍如何加解密!!!***********
    var example_public_key=$('#pubkey').val();//注意:密钥中含有“//”字符无法直接写不然会报错,所以用了html元素
    var example_private_key=$('#privkey').val();
    var example_text="我是一个要加密的文本";
    function encrypt1(public_key,sometext){//加密:需要两个参数public_key(公钥),sometext(要加密的文本)
        var encrypt = new JSEncrypt();
        encrypt.setPublicKey(public_key);
        var encrypted = encrypt.encrypt(sometext);
        return encrypted;
    }
    function decrypt1(private_key,encrypted_text) {//解密:需要两个参数private_key(私钥),encrypted_text(密文)
        var decrypt = new JSEncrypt();
        decrypt.setPrivateKey(private_key);
        var uncrypted = decrypt.decrypt(encrypted_text);
        return uncrypted;
    }
    var tmp01=encrypt1(example_public_key,example_text);
    document.write("<br>");
    document.write(tmp01);//输出一个加密
    document.write("<br>");
    tmp02=decrypt1(example_private_key,tmp01)
    document.write(tmp02);//输出一个解密
    </script>
</html>

生成完了后,可以去在线rsa网站上检测一下,RSA在线加解密

然后还需要在同一个文件夹下放入两个js文件,用于加解密!

下载链接:

rsa.zip - 蓝奏云

备用下载链接:

百度网盘 密码1234

参考文献:

travist/jsencrypt: (github.com)


本文转载自: https://blog.csdn.net/wtxiaobaishu/article/details/128874641
版权归原作者 wtxiaobaishu 所有, 如有侵权,请联系我们删除。

“js实现rsa密钥的加密、解密与生成”的评论:

还没有评论