我有一个如下的JSON文件。
secret.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键和Cipher参数,但是我不知道是否正确设置了[] byte键或该Cipher的来源。是来自加密/密码包吗?
编辑2:
感谢@HolaYang的出色回答。
我试图按如下方法使您的答案与外部JSON文件一起使用,但是它给了我一条错误消息,内容为cannot use fileContent (type secretValue) as type []byte in argument to (&"go.mozilla.org/sops/stores/json".Store literal).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)
}
答案 0 :(得分:1)
让我们看看sops.Tree.Encrypt
(代码中的错字)的函数声明。
通过代码,我们应该在这些步骤中进行操作。
sops.Tree
实例。Cipher
进行加密。请以这种方式尝试一下。
下面的代码演示,以AES作为密码,并且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)
}