如何在Go中从字符串中读取证书?

huangapple go评论62阅读模式
英文:

How to read a certificate from a string in Go?

问题

我正在编写一些代码,需要从环境变量中获取证书内容,并将其附加到证书池中。

如果通过环境变量传递证书的文件路径,它可以正常工作:

filename := os.Getenv("CACERT")
b, err := os.ReadFile(filename)
if err != nil {
	return nil, errors.Errorf("无法读取根证书")
}
if ok := pool.AppendCertsFromPEM(b); !ok {
	return nil, errors.Errorf("无法解析来自 %q 的根证书", filename)
}

但是,如果直接传递证书的实际内容,AppendCertsFromPem 就会抛出错误:

cert := os.Getenv("CACERT")
if ok := pool.AppendCertsFromPEM([]byte(cert)); !ok {
	return nil, errors.Errorf("无法解析根证书")
}

这是环境变量 CACERT 中的字符串内容:

-----BEGIN CERTIFICATE-----

**证书哈希值在这里**

-----END CERTIFICATE-----
英文:

I'm writing some code that needs to grab certificate content from an environment variable and append it to a certpool.

If I pass the file path of the certificate through the env variable it works fine:

filename := os.Getenv("CACERT")
b, err := os.ReadFile(filename)
if err != nil {
	return nil, errors.Errorf("unable to read root certificate")
}
if ok := pool.AppendCertsFromPEM(b); !ok {
	return nil, errors.Errorf("cannot parse root certificate from %q", filename)
}

But if I pass the actual contents of the certificate, AppendCertsFromPem throws an error:

cert := os.Getenv("CACERT")
if ok := pool.AppendCertsFromPEM([]byte(cert)); !ok {
	return nil, errors.Errorf("cannot parse root certificate")
}

This is the string inside the env variable CACERT:

-----BEGIN CERTIFICATE-----

**certificate hash here**

-----END CERTIFICATE-----

答案1

得分: 0

我不认为这是与golang相关的问题。这取决于你如何设置环境变量。你可能设置了错误格式的内容(可能缺少换行符或其他原因)。

我的偏好是使用base64对字符串进行编码,包括换行符和其他特殊字符,在使用时进行解码。

英文:

I don't think that it is a problem related to golang. It depends on how you set your environment variables. You may be set content with wrong format(newline missed or something else).

My preference is to encode string with newline and other special characters to base64 and decode it when used.

huangapple
  • 本文由 发表于 2023年6月15日 06:59:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76478082.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定