如何将字符串形式的RSA公私钥转换为rsa.PrivateKey与rsa.PublicKey对象?
Go中字符串格式RSA密钥转PKCS8格式密钥对象的实现
私钥转换(字符串→*rsa.PrivateKey)
你的私钥字符串是Base64编码的PKCS8格式私钥,转换步骤如下:
- 对字符串做Base64解码,得到原始PKCS8私钥字节数据
- 使用
x509.ParsePKCS8PrivateKey解析字节数据,再通过类型断言转为*rsa.PrivateKey
代码示例:
import ( "crypto/rsa" "crypto/x509" "encoding/base64" "fmt" ) func parseRSAPrivateKey(privKeyStr string) (*rsa.PrivateKey, error) { // Base64解码 privKeyBytes, err := base64.StdEncoding.DecodeString(privKeyStr) if err != nil { return nil, fmt.Errorf("base64解码失败: %w", err) } // 解析PKCS8格式私钥 privKey, err := x509.ParsePKCS8PrivateKey(privKeyBytes) if err != nil { return nil, fmt.Errorf("解析PKCS8私钥失败: %w", err) } // 类型断言为RSA私钥 rsaPrivKey, ok := privKey.(*rsa.PrivateKey) if !ok { return nil, fmt.Errorf("输入的不是RSA私钥") } return rsaPrivKey, nil }
公钥转换(字符串→*rsa.PublicKey)
公钥字符串是Base64编码的PKIX格式公钥(对应PKCS8规范中的公钥格式),转换步骤:
- Base64解码字符串得到公钥字节数据
- 使用
x509.ParsePKIXPublicKey解析字节数据,类型断言转为*rsa.PublicKey
代码示例:
func parseRSAPublicKey(pubKeyStr string) (*rsa.PublicKey, error) { // Base64解码 pubKeyBytes, err := base64.StdEncoding.DecodeString(pubKeyStr) if err != nil { return nil, fmt.Errorf("base64解码失败: %w", err) } // 解析PKIX格式公钥 pubKey, err := x509.ParsePKIXPublicKey(pubKeyBytes) if err != nil { return nil, fmt.Errorf("解析PKIX公钥失败: %w", err) } // 类型断言为RSA公钥 rsaPubKey, ok := pubKey.(*rsa.PublicKey) if !ok { return nil, fmt.Errorf("输入的不是RSA公钥") } return rsaPubKey, nil }
使用示例
func main() { privateKeyStr := "MIIB.......SDNW" publicKeyStr := "MIIE........io=" privKey, err := parseRSAPrivateKey(privateKeyStr) if err != nil { panic(err) } pubKey, err := parseRSAPublicKey(publicKeyStr) if err != nil { panic(err) } // 后续可使用privKey执行解密、签名操作,pubKey执行加密、验签操作 }
注意事项:
- 若你的密钥是URL安全的Base64编码,需改用
base64.URLEncoding.DecodeString解码 - 必须保留错误处理逻辑,避免因密钥格式错误或非RSA密钥引发程序崩溃
内容的提问来源于stack exchange,提问作者belbel
相关产品推荐
相关产品推荐

