go解析含passphrase的pem秘钥

背景

在编写TLS配置时需要用到需要用到一串包含passphrase的RSA秘钥,本想通过官方库的方式解析使用,但由于安全因素,官方已经禁用了DecryptPEMBlockEncryptPEMBlockIsEncryptedPEMBlock等函数,导致无法通过官方库去实现这个需求。

解决方案

最终通过pkcs8库来完成需求,代码如下:

go 复制代码
package main

import (
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"os"

	"github.com/youmark/pkcs8"
)

func main() {
	pem, err := getTlsConfig()
	if err != nil {
		panic(err)
	}
	fmt.Println("无加密的pem:", string(pem))
}

func getTlsConfig() ([]byte, error) {
	passphrase := "test123"
	keyFilePaaht := "./key"

	keyPEMByte, err := os.ReadFile(keyFilePaaht)
	if err != nil {
		err = fmt.Errorf("read %s failed! err: %s", keyFilePaaht, err)
		return nil, err
	}

	keyPEMBlock, rest := pem.Decode(keyPEMByte)
	if len(rest) > 0 {
		err := fmt.Errorf("decode key failed! rest: %s", rest)
		return nil, err
	}

	// 解析pem
	key, err := pkcs8.ParsePKCS8PrivateKey(keyPEMBlock.Bytes, []byte(passphrase))
	if err != nil {
		err = fmt.Errorf("parse PKCS8 private key err: %s", err)
		return nil, err
	}

	// 解析出其中的RSA 私钥
	keyBytes, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		err = fmt.Errorf("MarshalPKCS8PrivateKey failed! %s", err)
		return nil, err
	}
	// 编码成新的PEM 结构
	newKey := pem.EncodeToMemory(
		&pem.Block{
			Type:  "PRIVATE KEY",
			Bytes: keyBytes,
		},
	)

	return newKey, nil
}

为什么GO不支持pem的加密?

GO团队的Commit Message

crypto/x509: deprecate legacy PEM encryption

It's unfortunate that we don't implement PKCS#8 encryption (#8860)

so we can't recommend an alternative but PEM encryption is so broken

that it's worth deprecating outright.

官方库x509

Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.

GO团队认为PEM encryption的实现是不好的,不够安全的,因此官方移除了实现,并且也不推荐相关的外部实现的库。

从这个Issue的讨论可以看出社区对这个需求的渴望已经很久,但官方并没有太多关注。

参考链接

相关推荐
FAFU_kyp5 小时前
Rust 模式匹配:match 与 if let 详解
开发语言·后端·rust
爬山算法6 小时前
Hibernate(46) Hibernate的配置文件如何加载?
java·后端·hibernate
青w韵7 小时前
SpringBoot3.x 升级到 SpringBoot 4.x,JDK17升级到JDK21
java·后端·spring
vx_bisheyuange7 小时前
基于SpringBoot的经方药食服务平台
java·spring boot·后端·毕业设计
哈哈老师啊7 小时前
Springboot企业办公信息化管理系统6z1v1(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
永远是我的最爱7 小时前
基于ASP.NET的图书管理系统的设计与实现
前端·后端·sql·visual studio
钟离墨笺7 小时前
Go语言-->interfance{}赋值的陷阱
开发语言·后端·golang
+VX:Fegn08959 小时前
计算机毕业设计|基于springboot + vue校园跑腿系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
VX:Fegn08959 小时前
计算机毕业设计|基于springboot + vue在线考试系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
且去填词10 小时前
Go 内存分配器(TCMalloc):栈与堆的分配策略
开发语言·后端·面试·golang