大家好,今天本人给大家带来文章《使用 SOPS 和 Go 加密导入 JSON 文件中的值的方法》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!
我有一个 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 工作。我不会在生产中打印出这样的秘密值。
编辑:
我认为问题出在 encrypt 函数的参数上。根据文档,它应该采用 []byte key 和 cipher 参数,但我不知道我是否正确设置了 []byte key 或 cipher 来自哪里。是来自 crypto/cipher 包吗?
编辑2:
谢谢@holayang 的精彩回答。
我尝试使您的答案与外部 json 文件一起使用,如下所示,但它给了我一条错误消息,指出 cannot use filecontent (type secretvalue) as type []byte in argument to (&"go.mozilla.org/sops/stores /json".存储文字).loadplainfile。
package main
import (
hey "encoding/json"
"fmt"
"io/ioutil"
"go.mozilla.org/sops"
"go.mozilla.org/sops/aes"
"go.mozilla.org/sops/stores/json"
)
type secretValue struct {
Value string `json:"secret"`
}
func main() {
// fileContent := []byte(`{
// "secret": "strongPassword"
// }`)
file, _ := ioutil.ReadFile("secret.json")
fileContent := secretValue{}
//_ = json.Unmarshal([]byte(file), &fileContent)
_ = hey.Unmarshal([]byte(file), &fileContent)
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)
}解决方案
让我们看看 sops.tree.encrypt 的函数声明(代码中的拼写错误)。
通过代码,我们应该执行以下步骤。
- 使用 json 文件构建
sops.tree实例。 - 使用特定的
cipher进行加密。
请尝试一下这种方式。
下面的代码演示,使用aes作为cipher,sops只能用源码接口加密全树。
package main
import (
"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)
}本篇关于《使用 SOPS 和 Go 加密导入 JSON 文件中的值的方法》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
