Merge pull request #564 from trheyi/main

Add support for parsing public keys from certificates
This commit is contained in:
Max 2024-01-24 23:01:05 +08:00 committed by GitHub
commit f006ec554c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -147,10 +147,31 @@ func parsePrivateKey(privateKeyStr string) (*rsa.PrivateKey, error) {
func parsePublicKey(publicKeyStr string) (*rsa.PublicKey, error) {
publicKeyStr = strings.TrimSpace(publicKeyStr)
if !strings.HasPrefix(publicKeyStr, "-----BEGIN RSA PUBLIC KEY-----") {
if !strings.HasPrefix(publicKeyStr, "-----BEGIN RSA PUBLIC KEY-----") && !strings.HasPrefix(publicKeyStr, "-----BEGIN CERTIFICATE-----") {
publicKeyStr = fmt.Sprintf("-----BEGIN RSA PUBLIC KEY-----\n%s\n-----END RSA PUBLIC KEY-----\n", publicKeyStr)
}
// if it is a certificate, get the public key from the certificate
if strings.HasPrefix(publicKeyStr, "-----BEGIN CERTIFICATE-----") {
block, _ := pem.Decode([]byte(publicKeyStr))
if block == nil {
return nil, fmt.Errorf("cannot decode PEM block")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
pub, ok := cert.PublicKey.(*rsa.PublicKey)
if !ok {
return nil, errors.New("public key error")
}
return pub, nil
}
block, _ := pem.Decode([]byte(publicKeyStr))
if block == nil {
return nil, fmt.Errorf("cannot decode PEM block")