首页 > 文章列表 > 如何加密 Github Action Secrets API 的存储库机密

如何加密 Github Action Secrets API 的存储库机密

478 2024-04-29
问题内容

要使用 github action secrets api 创建存储库密钥,我们必须使用钠库对密钥进行加密。 github 文档。未提供 go 的示例。有人可以帮助我编写一个函数来加密秘密吗?

我当前的实现如下:

func EncodeWithPublicKey(text string, publicKey string) (string, error) {
    // Decode the public key from base64
    publicKeyBytes, _ := base64.StdEncoding.DecodeString(publicKey)
    fmt.Printf("%xnn", publicKeyBytes)

    // Generate a key pair
    _, privateKey, _ := box.GenerateKey(rand.Reader)
    fmt.Printf("Private key: %xnn", *privateKey)

    // Convert publickey to bytes
    var publicKeyDecoded [32]byte
    copy(publicKeyDecoded[:], publicKeyBytes)

    // Encrypt the secret value
    nonce := new([24]byte)
    encrypted := box.Seal(nil, []byte(text), nonce, &publicKeyDecoded, privateKey)
    fmt.Printf("%xnn", encrypted)

    // Encode the encrypted value in base64
    encryptedBase64 := base64.StdEncoding.EncodeToString(encrypted)
    fmt.Printf("%xnnn", encryptedBase64)

    return encryptedBase64, nil
}

我正在使用 golang.org/x/crypto/nacl/box

截至当前实施,操作密钥设置不正确,因为构建过程提示我错误“找不到 apitoken”。但是,如果我使用 github 的网站设置密码,部署就会起作用。


正确答案


我不得不将 seal 更改为 sealanonymous

func EncodeWithPublicKey(text string, publicKey string) (string, error) {
    // Decode the public key from base64
    publicKeyBytes, err := base64.StdEncoding.DecodeString(publicKey)
    if err != nil {
        return "", err
    }

    // Decode the public key
    var publicKeyDecoded [32]byte
    copy(publicKeyDecoded[:], publicKeyBytes)

    // Encrypt the secret value
    encrypted, err := box.SealAnonymous(nil, []byte(text), (*[32]byte)(publicKeyBytes), rand.Reader)

    if err != nil {
        return "", err
    }
    // Encode the encrypted value in base64
    encryptedBase64 := base64.StdEncoding.EncodeToString(encrypted)

    return encryptedBase64, nil
}