gpt4 book ai didi

json - 使用 json post 的 Golang 编码/解码 base64 不起作用

转载 作者:IT王子 更新时间:2023-10-29 02:22:00 25 4
gpt4 key购买 nike

我用golang搭建的客户端和服务器都是用这个函数加解密

func encrypt(text []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
b := base64.StdEncoding.EncodeToString(text)
ciphertext := make([]byte, aes.BlockSize+len(b))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
return ciphertext, nil
}

func decrypt(text []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(text) < aes.BlockSize {
return nil, errors.New("ciphertext too short")
}
iv := text[:aes.BlockSize]
text = text[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(text, text)
data, err := base64.StdEncoding.DecodeString(string(text))
if err != nil {
return nil, err
}
return data, nil
}

所以是的,我发出了一个正常的发帖请求

url := "https://"+configuration.Server+configuration.Port+"/get"

// TODO maybe bugs rest here
ciphertext, err := encrypt([]byte(*getUrl))
if err != nil {
fmt.Println("Error: " + err.Error())
}
fmt.Println(string(ciphertext))

values := map[string]interface{}{"url": *getUrl, "urlCrypted": ciphertext}
jsonValue, _ := json.Marshal(values)
jsonStr := bytes.NewBuffer(jsonValue)

req, err := http.NewRequest("POST", url, jsonStr)

服务器代码如下

requestContent := getRequestContentFromRequest(req)
url := requestContent["url"].(string)

undecryptedUrl := requestContent["urlCrypted"].(string)
decryptedurl, err := decrypt([]byte(undecryptedUrl))
if err != nil {
fmt.Println("Error: " + err.Error())
}
fmt.Println(decryptedurl)

其中getRequestContentFromRequest如下

func getRequestContentFromRequest(req *http.Request)                 
map[string]interface{} {
buf := new(bytes.Buffer)
buf.ReadFrom(req.Body)
data := buf.Bytes()
var requestContent map[string]interface{}
err := json.Unmarshal(data, &requestContent)
if err != nil {
fmt.Println(err)
}
return requestContent
}

现在来解决问题。如果我在客户端加密我的字符串并在之后直接解密,一切都很好。

但是,当我将加密的字符串发送到服务器并尝试使用与客户端完全相同的函数对其进行解密时,解密函数会抛出错误。

Error: illegal base64 data at input byte 0

我认为问题在于 JSON 的解码。

感谢您的帮助。

附言

repo 是

github.com/BelphegorPrime/goSafeClient 和 github.com/BelphegorPrime/goSafe

更新

示例 JSON

{"url":"facebook2.com","urlCrypted":"/}\ufffd\ufffd\ufffdgP\ufffdN뼞\ufffd\u0016\ufffd)\ufffd\ufffd\ufffdy\u001c\u000f\ufffd\ufffd\ufffdep\ufffd\rY\ufffd\ufffd$\ufffd\ufffd"}

更新2

我做了一个 Playground here

最佳答案

问题是你用 base64 编码了两次。第一次在 encrypt 函数中,第二次在 JSON 编码期间。 encoding/json 编码器会自动将字节 slice 转换为 base64 字符串。

解决方案是在调用decrypt之前解码base64字符串。

关于 the Go PlayGround 的示例

编辑

工作解决方案 here

关于json - 使用 json post 的 Golang 编码/解码 base64 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43942972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com