我有一个JSON文件如下所示。
secret.json:
{
"secret": "strongPassword"
}我想打印出密钥“机密”的加密值。
到目前为止,我已经尝试了如下。
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是如何工作的。我不会在生产中打印出这样的秘密价值。
编辑:
我认为问题在于加密函数的参数。根据文档,应该使用[]字节键和密码参数,但我不知道是否设置了正确的[]字节键,或者该密码来自何处。是密码包里的吗?
编辑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)
}发布于 2019-05-16 10:56:02
让我们看看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)
}https://stackoverflow.com/questions/56166471
复制相似问题