[英]How to encrypt a value imported from a JSON file using SOPS (Secrets OPerationS) and Go?
我有一个 JSON 文件,如下所示。
秘密.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 如何使用 Go 工作。 我不会在生产中打印出这样的秘密值。
编辑:
我认为问题在于 Encrypt 函数的参数。 根据文档,它应该使用 []byte key 和 Cipher 参数,但我不知道我是否正确设置了 []byte 密钥或密码来自哪里。 它来自加密/密码包吗?
编辑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)
}
让我们看看sops.Tree.Encrypt
的函数声明(您的代码中的一个错字) 。 通过代码,我们应该在这些步骤中做。
sops.Tree
实例。Cipher
进行加密。请以这种方式尝试自己。
下面代码demo,以AES为Cipher,sop只能用源码接口加密总树。
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.