如何使用 JavaScript 从 base64 编码解码文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8284529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:55:38  来源:igfitidea点击:

How to decode a file from base64 encoding with JavaScript

javascriptfilebase64

提问by Madara's Ghost

My company has a very strict intranet for work related, the net has a single doorway to allow files in and out. The doorway's security does not allow special kinds of files (*.txt, *.doc etc only), and even in those specific kinds of files, it searches for patterns that approve that the file is really that kind. (You can't simply disguise a *.zip file as a *.doc file.)

我公司有一个非常严格的工作相关的内网,该网络有一个允许文件进出的入口。门口的安全性不允许特殊类型的文件(仅*.txt、*.doc 等),即使在那些特定类型的文件中,它也会搜索批准该文件确实是那种类型的模式。(您不能简单地将 *.zip 文件伪装成 *.doc 文件。)

As a security project, I was told to find a way to bypass this system, and insert a single C language .exe file that says 'Hello World'.

作为一个安全项目,我被告知要找到一种绕过这个系统的方法,并插入一个 C 语言 .exe 文件,上面写着'Hello World'.

What I thought was to change the extension to .txt, and base64 encode it so that it would be more acceptable for the system. The problem is, how to decode it once it's in. It's very easy on the outside, PHP or any other decent language can do it for me. However, in there, the only real language I have access to is JavaScript (on IE6 and maybe, MAYBE, on IE8).

我的想法是将扩展名更改为 .txt,并对其进行 base64 编码,以便系统更能接受它。问题是,一旦它进入,如何对其进行解码。在外面很容易,PHP 或任何其他体面的语言都可以为我完成。然而,在那里,我可以访问的唯一真正的语言是 JavaScript(在 IE6 上,也许,在 IE8 上)。

So the question is as follows, can I use JavaScript to read a file from the file system, decode it, and write it back? or at least display the result for me?

那么问题来了,我可以用JavaScript从文件系统中读取文件,解码,写回吗?或者至少为我显示结果?

Note that I don't ask for decoding/encoding a message, this one is easy, I look to decode encode a file.

请注意,我不要求对消息进行解码/编码,这个很简单,我希望对文件进行 decode 编码。

Thanks.

谢谢。

采纳答案by loscuropresagio

JSONmight be the answer you are looking for. It can actually do the trick.

JSON可能是您正在寻找的答案。它实际上可以做到这一点。

  1. Encode your txt file in JSON format. It is very likely for it to pass your company's doorway security

    var myJsonData = { "text" : "SGVsbG8sIHdvcmxkIQ==" };  // <-- base64 for "Hello, world!"
    
  2. Import your txt file using plain html script syntax

    <script src="hello.txt" type="text/javascript"> </script>
    
  3. That's it! Now you can access a JSON object using the Syntax:

    alert(myJsonData.text);
    
  4. To complete your job, get thissimple Javascript base64 decoder.

  5. You're done. Here's the (very simple) code I've used:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
      <meta http-equiv="content-type" content="text/html; charset=windows-1250">
      <meta name="generator" content="PSPad editor, www.pspad.com">
      <title></title>
    
      <script src="base64utils.js" type="text/javascript"> </script>
      <script src="hello.txt" type="text/javascript"> </script>
    
      <script type="text/javascript">
        function helloFunction() {
        document.getElementById("hello").innerHTML = decode64(myJsonData.text);
        }
      </script>
    
      </head>
      <body onload="helloFunction();">
        <p id="hello"></p>
      </body>
    </html>
    
  1. 以 JSON 格式对您的 txt 文件进行编码。极有可能通过贵公司的门口安检

    var myJsonData = { "text" : "SGVsbG8sIHdvcmxkIQ==" };  // <-- base64 for "Hello, world!"
    
  2. 使用纯 html 脚本语法导入您的 txt 文件

    <script src="hello.txt" type="text/javascript"> </script>
    
  3. 而已!现在您可以使用以下语法访问 JSON 对象:

    alert(myJsonData.text);
    
  4. 要完成您的工作,请获取这个简单的 Javascript base64 解码器。

  5. 你完成了。这是我使用的(非常简单的)代码:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
      <meta http-equiv="content-type" content="text/html; charset=windows-1250">
      <meta name="generator" content="PSPad editor, www.pspad.com">
      <title></title>
    
      <script src="base64utils.js" type="text/javascript"> </script>
      <script src="hello.txt" type="text/javascript"> </script>
    
      <script type="text/javascript">
        function helloFunction() {
        document.getElementById("hello").innerHTML = decode64(myJsonData.text);
        }
      </script>
    
      </head>
      <body onload="helloFunction();">
        <p id="hello"></p>
      </body>
    </html>
    

回答by Jeff

Using only javascript (i.e. no plugins like AIR etc), browsers don't allow access to the file system. Not only is it not possible to write a file to the disk, it's not possible to even read it - browsers are very strict on that sort of thing, thank goodness.

仅使用 javascript(即没有 AIR 等插件),浏览器不允许访问文件系统。不仅无法将文件写入磁盘,甚至无法读取它 - 浏览器对这类事情非常严格,谢天谢地。

回答by Tracker1

You cannot do this with straight JS in the browser, security context and the DOM do not allow filesystem access.

你不能在浏览器中使用直接的 JS 来做到这一点,安全上下文和 DOM 不允许文件系统访问。

You cannot do this with current versions of flash, older versions (pre 7 IIRC) had some security flaws that allowed filesystem access.

您无法使用当前版本的闪存执行此操作,旧版本(7 IIRC 之前的版本)存在一些允许文件系统访问的安全漏洞。

You could do this with a custom plugin, and possibly a signed Java applet, or COM (ActiveX component, IE only).

您可以使用自定义插件完成此操作,也可以使用签名的 Java 小程序或 COM(ActiveX 组件,仅限 IE)。

I would suggest working with IT regarding your intranet to open up the context/permissions needed in this case as that may be the shortest path to what you are wanting here. Alternative, you could create a command-line utility to easily encrypt/decrypt given files signed by a common key.

我建议就您的 Intranet 与 IT 部门合作,以打开这种情况下所需的上下文/权限,因为这可能是您在这里想要的最短路径。或者,您可以创建一个命令行实用程序来轻松加密/解密由公共密钥签名的给定文件。

回答by Ari Lotter

It all depends on how you can get the file in. If you have the base-64 encoded exe as a .txt, you could easily use Flash! I'm not quite sure how you would implement this, but you can load a file into flash and as3 using flex.

这完全取决于您如何获取文件。如果您将 base-64 编码的 exe 作为 .txt,您可以轻松使用 Flash!我不太确定您将如何实现这一点,但是您可以使用 flex 将文件加载到 flash 和 as3 中。

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

    <mx:Script>
        <![CDATA[
            import flash.net.FileReference;
            import flash.net.FileFilter;

            import flash.events.IOErrorEvent;
            import flash.events.Event;

            import flash.utils.ByteArray;

            //FileReference Class well will use to load data
            private var fr:FileReference;

            //File types which we want the user to open
            private static const FILE_TYPES:Array = [new FileFilter("Text File", "*.txt;*.text")];

            //called when the user clicks the load file button
            private function onLoadFileClick():void
            {
                //create the FileReference instance
                fr = new FileReference();

                //listen for when they select a file
                fr.addEventListener(Event.SELECT, onFileSelect);

                //listen for when then cancel out of the browse dialog
                fr.addEventListener(Event.CANCEL,onCancel);

                //open a native browse dialog that filters for text files
                fr.browse(FILE_TYPES);
            }

            /************ Browse Event Handlers **************/

            //called when the user selects a file from the browse dialog
            private function onFileSelect(e:Event):void
            {
                //listen for when the file has loaded
                fr.addEventListener(Event.COMPLETE, onLoadComplete);

                //listen for any errors reading the file
                fr.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);

                //load the content of the file
                fr.load();
            }

            //called when the user cancels out of the browser dialog
            private function onCancel(e:Event):void
            {
                trace("File Browse Canceled");
                fr = null;
            }

            /************ Select Event Handlers **************/

            //called when the file has completed loading
            private function onLoadComplete(e:Event):void
            {
                //get the data from the file as a ByteArray
                var data:ByteArray = fr.data;

                //read the bytes of the file as a string and put it in the
                //textarea
                outputField.text = data.readUTFBytes(data.bytesAvailable);

                //clean up the FileReference instance

                fr = null;
            }

            //called if an error occurs while loading the file contents
            private function onLoadError(e:IOErrorEvent):void
            {
                trace("Error loading file : " + e.text);
            }

        ]]>
    </mx:Script>

    <mx:Button label="Load Text File" right="10" bottom="10" click="onLoadFileClick()"/>
    <mx:TextArea right="10" left="10" top="10" bottom="40" id="outputField"/>

</mx:Application>

To decode it, look into http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/utils/Base64Decoder.html

要对其进行解码,请查看http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/utils/Base64Decoder.html

回答by PointedEars

If the security system scans for patterns in files, it is very unlikely that it will overlook a base64-encoded file or base64-encoded contents in files. E-mail attachments are base64-encoded, and if the system is any good it will scan for potentially harmful e-mail attachments even if they are named .txt. The base64-encoded start of an EXE fileis almost certainly recognized by it. So ISTM you are asking the wrong question.

如果安全系统扫描文件中的模式,它不太可能忽略 base64 编码的文件或文件中的 base64 编码的内容。电子邮件附件是 base64 编码的,如果系统很好,它会扫描潜在有害的电子邮件附件,即使它们被命名为 .txt。EXE 文件的 base64 编码开头几乎肯定会被它识别。所以ISTM你问错了问题。