我正在使用 Go 编写 CLI,我想将密码保存到保存在用户主目录中的配置文件中。
我是否应该在保存时加密密码并在将密码发送到与 CLI 交互的服务器时解密?
如果是这样,go library 中是否有一个很好的内置库来做到这一点?我想让它尽可能简单,并且不使用任何额外的外部包。我看到的所有答案都非常复杂。
应该是这样的:
func Encrypt(password string) string
func Decrypt(password string) string
有什么想法吗?
最佳答案
免责声明:核心库不提供开箱即用的此功能。 Go 的第三方库(来自 Docker)可以提供帮助。
现代操作系统提供了以安全方式存储 secret 的工具和 API。
- 苹果:钥匙串(keychain)
- Linux:特勤局
- Windows:凭据管理器 API
Git 和 Docker 使用这些工具来存储您的凭据。
David Calavera 贡献了 Docker credential helpers给Docker Engine v1.11写了一篇标题为Stop saving credential tokens in text files的文章2016 年。这篇文章描述了这个问题,一个简单的 Linux 实现,并展示了如何使用该库。
package main
import (
"github.com/docker/docker-credential-helpers/client"
"github.com/docker/docker-credential-helpers/credentials"
)
var nativeStore = client.NewShellProgramFunc("docker-credential-secretservice")
func main() {
c := &credentials.Credentials{
ServerURL: "https://api.github.com",
Username: "token",
Secret: "my-super-secret-token",
}
client.Store(nativeStore, c)
storedCreds, err := client.Get(nativeStore, "https://api.github.com")
}
Docker credential helpers 的缺点是它希望您安装它的二进制文件并需要 CGo。我专门添加了 Docker 解决方案,因为它在评论中被提及但是有类似的库:
- 99designs/keyring - 最初是 AWS 保险库库的一部分。
- zalando/go-keyring - 一个纯 Go 实现,其目标是避免 C 绑定(bind)。
关于encryption - 创建 CLI : What should I do with the password in the config file (and how)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33183692/