簡體   English   中英

go 中的編碼可執行文件和 javascript 中的解碼不起作用

[英]encoding executable in go and decoding in javascript is not working

我在go中對可執行文件進行編碼,並嘗試在javascript中對其進行解碼。

解碼javascript中的編碼string不會產生匹配的文件。 我能夠對"this is a test string"之類的字符串進行編碼並在javascript中對其進行解碼,並且工作正常。 但是當我使用一個可執行應用程序並做同樣的事情時,解碼后的文件比編碼前的文件大。

我究竟做錯了什么? 謝謝!

這是我正在使用的測試可執行文件。 它在 c++ 中,用g++編譯它並使用 output。

#include <iostream>
int main(void) {

    char test1[] = "hello";

    std::cout << "test1: " << test1 << std::endl;

    char test2[] = "world";

    std::cout << "test2: " << test2 << std::endl;

    char test3[] = "foobar";

    std::cout << "test3: " << test3 << std::endl;

    return 0;
}

這是我用來將文件轉換為bytesgo應用程序。

package main

import (
    "fmt"
    "github.com/atotto/clipboard"
    "io/ioutil"
)

func main() {
    bytes, err := ioutil.ReadFile("/path/to/file/a.out")
    if err != nil {
        fmt.Println(err)
    }

    enc := make([]byte, base64.RawStdEncoding.EncodedLen(len(bytes)))
    base64.RawStdEncoding.Encode(enc, bytes)

    fmt.Println("byte size: ", len(bytes))
    fmt.Println("encoded byte size: ", len(enc))

    clipboard.WriteAll(string(enc))
}

這是我嘗試解碼並將文件保存在 javascript 中的方式。

let decodedBytes = atob("put the bytes here from your clipboard from running the go app");

fs.writeFileSync(
    "/destination/to/save/file",
    decodedBytes
);

我想到了。 經過一些研究和閱讀,我發現了這個問題這篇文章 最初這個問題對我沒有幫助,但是在閱讀了那篇文章一段時間后,我嘗試了一些示例並且能夠讓其中一個工作。 我能夠讓solution 1起作用。 這是javascript我現在必須讓它工作。

保存的文件與源文件完全相同。

function b64ToUint6(nChr) {
  return nChr > 64 && nChr < 91
    ? nChr - 65
    : nChr > 96 && nChr < 123
    ? nChr - 71
    : nChr > 47 && nChr < 58
    ? nChr + 4
    : nChr === 43
    ? 62
    : nChr === 47
    ? 63
    : 0;
}

function base64DecToArr(sBase64, nBlockSize) {
  var sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""),
    nInLen = sB64Enc.length,
    nOutLen = nBlockSize
      ? Math.ceil(((nInLen * 3 + 1) >>> 2) / nBlockSize) * nBlockSize
      : (nInLen * 3 + 1) >>> 2,
    aBytes = new Uint8Array(nOutLen);

  for (
    var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0;
    nInIdx < nInLen;
    nInIdx++
  ) {
    nMod4 = nInIdx & 3;
    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << (18 - 6 * nMod4);
    if (nMod4 === 3 || nInLen - nInIdx === 1) {
      for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
        aBytes[nOutIdx] = (nUint24 >>> ((16 >>> nMod3) & 24)) & 255;
      }
      nUint24 = 0;
    }
  }

  return aBytes;
}

let decodedBytes = base64DecToArr("bytes to decode");

fs.writeFileSync(
    "/destination/to/save/file",
    decodedBytes
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM