JS基于base64编码加密解密文本和图片(修订)

JS基于base64编码加密解密文本和图片

密码学,体系太庞大了,常见的加密解密算法很多,这里仅介绍采用base64实现的加密解密的方法。

严格地说base64不是加密算法,他只是一种编码方式,是一种用64个字符来表示任意二进制数据的方法。详情可参见其它资料。

Base64编码具有不可读性,需要解码后才能阅读。算是伪加密吧。

加密解密文本

源码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS的BASE64加密/解密示例</title>
<script>
// 创建Base64对象
var Base64 = {
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    encode: function(e) {
        var t = "";
        var n, r, i, s, o, u, a;
        var f = 0;
        e = Base64._utf8_encode(e);
        while (f < e.length) {
            n = e.charCodeAt(f++);
            r = e.charCodeAt(f++);
            i = e.charCodeAt(f++);
            s = n >> 2;
            o = (n & 3) << 4 | r >> 4;
            u = (r & 15) << 2 | i >> 6;
            a = i & 63;
            if (isNaN(r)) {
                u = a = 64
            } else if (isNaN(i)) {
                a = 64
            }
            t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
        }
        return t
    },
    decode: function(e) {
        var t = "";
        var n, r, i;
        var s, o, u, a;
        var f = 0;
        e = e.replace(/[^A-Za-z0-9+/=]/g, "");
        while (f < e.length) {
            s = this._keyStr.indexOf(e.charAt(f++));
            o = this._keyStr.indexOf(e.charAt(f++));
            u = this._keyStr.indexOf(e.charAt(f++));
            a = this._keyStr.indexOf(e.charAt(f++));
            n = s << 2 | o >> 4;
            r = (o & 15) << 4 | u >> 2;
            i = (u & 3) << 6 | a;
            t = t + String.fromCharCode(n);
            if (u != 64) {
                t = t + String.fromCharCode(r)
            }
            if (a != 64) {
                t = t + String.fromCharCode(i)
            }
        }
        t = Base64._utf8_decode(t);
        return t
    },
    _utf8_encode: function(e) {
        e = e.replace(/rn/g, "n");
        var t = "";
        for (var n = 0; n < e.length; n++) {
            var r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r)
            } else if (r > 127 && r < 2048) {
                t += String.fromCharCode(r >> 6 | 192);
                t += String.fromCharCode(r & 63 | 128)
            } else {
                t += String.fromCharCode(r >> 12 | 224);
                t += String.fromCharCode(r >> 6 & 63 | 128);
                t += String.fromCharCode(r & 63 | 128)
            }
        }
        return t
    },
    _utf8_decode: function(e) {
        var t = "";
        var n = 0;
        var r = c1 = c2 = 0;
        while (n < e.length) {
            r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r);
                n++
            } else if (r > 191 && r < 224) {
                c2 = e.charCodeAt(n + 1);
                t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                n += 2
            } else {
                c2 = e.charCodeAt(n + 1);
                c3 = e.charCodeAt(n + 2);
                t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
                n += 3
            }
        }
        return t
    }
}

function Encode(){
    var str1= document.getElementById("text1").value
    document.getElementById("text1").value=Base64.encode(str1); // 使用Base64对象的encode()
}

function deEncode(){
    var str2= document.getElementById("text2").value
    document.getElementById("text2").value=Base64.decode(str2) ; //使用Base64对象的decode() 
}

</script>
</head>
<body>
<textarea id="text1" cols="60" rows="10"></textarea>
<br>
<input type="button" value="BASE64加密"  onclick="Encode()">
<br><br>
<textarea id="text2" cols="60" rows="10"></textarea>
<br>
<input type="button" value="BASE64解密" onclick="deEncode()">

</body>
</html>

保存文件名为:BASE64编码加密解密文本.html,用浏览器打开效果:

 现在,你可以试试了。 

参考https://www.yisu.com/zixun/180535.html

加密解密图片

本文例子用到jquery,若本地使用请先下载,我这以里jquery-3.5.1. js版本为例,这样用

<script src="jquery-3.5.1. js"></script>

也可以不下载,需要联网【使用CDN(全称是Content Delivery Network:内容分发网络或内容交付网络)可参见https://blog.csdn.net/cnds123/article/details/126268941】如下使用

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>

Canvas(画布) API提供了toDataURL()方法,可以把画布中的图形转换为图片。有了Data URL数据后,就可将这些数据直接填充到<img>元素里,或者直接从浏览器里下载它们。

【关于toDataURL()方法参看https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLCanvasElement/toDataURL

https://www.canvasapi.cn/HTMLCanvasElement/toDataURL

这里介绍的加密解密图片基本原理:将图片读入canvas,并使用canvas的toDataURL方法将图片base64化,在此过程中,可以设定quality值,即图片质量值,值为0.1到1之间,值越小,压缩度越高。

先看如何对图片加密并保存

源码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>加密图片并保存</title>
    </head>
<body>
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    请选定要加密的图片文件<input id="file" type="file" onchange="showPreview(this, 'pic')" capture="microphone" accept="image/*">      
    <button type="button" onclick="download()">保存加密图片</button>
    <br>        
    <img id="pic" >

    <script>
        //显示选定的图片
        function showPreview(source, imgId) {
          var file = source.files[0];
          if(window.FileReader) {
              var fr = new FileReader();
              fr.onloadend = function(e) {               
                  document.getElementById(imgId).src = e.target.result;
                  ReadFlag = e.target.result;
              }
              fr.readAsDataURL(file);
          }
        }

        var stringData;  //要保存的变量
         
        $("#file").change(function(){
            var m_this = this;
            cutImageBase64(m_this,null,900,0.7);
        })
        function cutImageBase64(m_this,id,wid,quality) {
            var file = m_this.files[0];
            var URL = window.URL || window.webkitURL;
            var blob = URL.createObjectURL(file);
            var base64;
            var img = new Image();
            img.src = blob;
            img.onload = function() {
                var that = this;
                //生成比例
                var w = that.width,
                    h = that.height;
                    //scale = w / h;
                    //w = wid || w;
                    //h = w / scale; 
                
                //生成canvas(画布)
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                $(canvas).attr({
                    width: w,
                    height: h
                });
                ctx.drawImage(that, 0, 0, w, h);
                // 生成base64
                base64 = canvas.toDataURL('image/jpeg', quality || 0.9);
                //stringData = base64;            
                //加密
                var base64_2 = base64.substring(0,26) + "a" +base64.substring(26,base64.lenght);
                console.log(base64_2);
                stringData = base64_2;
                
            };
        }

       function download(){ 
           //alert(stringData);
           if(stringData ==undefined){
                alert("先选定需要加密的图片!");
                return;
           }
           var text =  stringData;
           var blob = new Blob([text], { type: "text/plain"}); 
           var anchor = document.createElement("a"); 
           //anchor.download = "my-filename.txt"; 
           anchor.download = "加密_" + document.getElementById("file").files[0].name;
           anchor.href = window.URL.createObjectURL(blob); 
           anchor.target ="_blank"; 
           anchor.style.display = "none"; // 
           document.body.appendChild(anchor); 
           anchor.click(); 
           document.body.removeChild(anchor); //
       }

    </script>
   </body>
</html>

保存文件名为:对图片加密并保存AA.html,用浏览器打开效果:

单击“保存加密图片”将保存到浏览器默认下载位置,你可以到此找到已加密的图片,用“画图”等是打不开的——因为已加密,怎么打开?接着往下看。

再看对已加密图片文件进行解密

对由上面例子加密的图片文件进行解密,并将解密得到的图片保存到本地,源码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>对已经加密图片解密</title>
    </head>
    
    <body>
    选定已加密的图片文件<input type="file" id="file"/>
    <br>
    <textarea id="output" cols="80" rows="6" readonly="readonly"> </textarea>
    <br> 
    <button type="button" onclick="jm()">解密图片</button> 
 
    <button onclick="downloadIamge('pic')">保存已解密图片</button>
    <br>
    <img id="pic">
    <script>
        var fileName;
        document.getElementById('file').onchange =function(){
            var file = this.files[0];
            fileName=file.name
            //alert(file.name)
            var reader = new FileReader();            
            reader.onload = function(progressEvent){    
               var fileContent = this.result;    
               //alert(fileContent );   
               document.getElementById('output').value = fileContent;           
            };
            reader.readAsText(file);
        };

        function jm(){
            var base64_2 = document.getElementById("output").value;  
            if(base64_2 ==" "){
                alert("提示:请先选定要解密的加密图片文件!!!");
                return;
            }
            //解密
            var base64_3 = base64_2.substring(0,26) + base64_2.substring(27,base64_2.length);
            document.getElementById("pic").src=base64_3;
            //console.log(base64_3)
          
        }

    //将img标签中图片保存到本地
    
    function downloadIamge(selector) {
        // 通过选择器获取img元素
        var img = document.getElementById(selector)
        // 将图片的src属性作为URL地址        
        var url = img.src
        //alert(url);
        if(url ==""){
            alert("请先解密已加密的图片文件!");
            return;
        }
        var a = document.createElement('a')
        var event = new MouseEvent('click')

        a.download = "解密_"+fileName // '下载图片名称'
        a.href = url

        a.dispatchEvent(event) //根据A标签的属性来搞事情
    }

    </script>
  </body>
</html>

保存文件名为:对已加密图片文件进行解密并可保存AA.html,用浏览器打开效果:

解密后的图片可保存,单击“保存已解密图片”将保存到浏览器默认下载位置,你可以到此找到已解密的图片,可以用“画图”等 打开看了。

参考:https://www.jb51.net/article/239975.htm

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学习&实践爱好者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值