如何使用 SOPS(Secrets OPerationS)和 Go 加密从 JSON 文件导入的值?

我有一个 JSON 文件,如下所示。


秘密.json:


{

    "secret": "strongPassword"

}

我想打印出密钥“secret”的加密值。


到目前为止,我已经尝试过如下。


package main


import (

    "encoding/json"

    "fmt"

    "io/ioutil"


    "go.mozilla.org/sops"

)


type secretValue struct {

    Value string `json:"secret"`

}


func main() {

    file, _ := ioutil.ReadFile("secret.json")

    getSecretValue := secretValue{}

    _ = json.Unmarshal([]byte(file), &getSecretValue)

    encryptedValue, err := sops.Tree.Encrypt([]byte(getSecretValue.Value), file)

    if err != nil {

        panic(err)

    }

    fmt.Println(encryptedValue)

}

您可能已经猜到了,我是 Go 的新手,上面的代码不起作用。


如何改进代码以打印出加密值?


请注意,我编写这样的代码只是为了了解 SOPS 如何使用 Go 工作。我不会在生产中打印出这样的秘密值。


紫衣仙女
浏览 61回答 1
1回答

叮当猫咪

sops.Tree.Encrypt 让我们看看(a typo here in your code)的函数声明。通过代码,我们应该分这几步去做。sops.Tree使用 json 文件构造一个实例。使用特定Cipher的加密。请以这种方式尝试自己。下面代码demo,用AES作为Cipher,sops只能用源码接口加密total tree。package mainimport (    "fmt"    "go.mozilla.org/sops"    "go.mozilla.org/sops/aes"    "go.mozilla.org/sops/stores/json")func main() {    /*    fileContent := []byte(`{    "secret": "strongPassword"    }`)    */    fileContent, _ := ioutil.ReadFile("xxx.json")    encryptKey := []byte("0123456789012345") // length 16    branches, _ := (&json.Store{}).LoadPlainFile(fileContent)    tree := sops.Tree{Branches: branches}    r, err := tree.Encrypt(encryptKey, aes.NewCipher())    if err != nil {        panic(err)    }    fmt.Println(r)}
打开App,查看更多内容
随时随地看视频慕课网APP