I have a JSON file as follows.
secret.json:
{
"secret": "strongPassword"
}
I want to print out an encrypted value of the key "secret".
I've so far tried as follows.
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)
}
As you might have guessed, I'm pretty new to Go and the code above doesn't work.
How can I improve the code to print out the encrypted value?
Please note that I'm writing code like this only to see how SOPS works using Go. I don't print out secret value like this in production.
Edit:
I think the problem is the arguments for the Encrypt function. According to the documentation, it should take []byte key and Cipher arguments, but I don't know either if I'm setting the []byte key correct or where that Cipher comes from. Is it from crypto/cipher package?
Edit 2:
Thank you @HolaYang for the great answer.
I tried to make your answer work with the external JSON file as follows, but it gave me an error message saying 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)
}