簡體   English   中英

如何使用 SOPS(Secrets OPerationS)和 Go 加密從 JSON 文件導入的值?

[英]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的函數聲明(您的代碼中的一個錯字) 通過代碼,我們應該在這些步驟中做。

  1. 使用 json 文件構造一個sops.Tree實例。
  2. 使用特定的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM