我正在尝试获取 rsa.PublicKey 的对象,并且执行了以下步骤:
----BEGIN RSA PUBLIC KEY----
....
----END RSA PUBLIC KEY----
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
)
func main() {
key, err := ioutil.ReadFile("./new_public.pem")
if err != nil {
fmt.Println(err.Error())
}
block, _ := pem.Decode([]byte(key))
if block == nil {
fmt.Println("unable to decode publicKey to request")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
panic("failed to parse RSA encoded public key" + err.Error())
}
switch pub := pub.(type) {
case *rsa.PublicKey:
fmt.Println("pub is of type RSA:", pub)
default:
panic("error")
}
}
在此之后,当我尝试x509.ParsePKIXPublicKey(block.Bytes)
我收到错误:
panic: failed to parse RSA encoded public keyasn1:
structure error: tags don't match (16 vs {class:0 tag:2 length:129 isCompound:false})
{
optional:false
explicit:false
application:false
private:false
defaultValue:<nil> tag:<nil>
stringType:0
timeType:0
set:false
omitEmpty:false
} AlgorithmIdentifier @3
因此,我阅读了一些有关 DER 和 PEM 格式的博客和文档,它们是对证书进行编码的不同方式,基本上一种使用 base64,另一种仅使用字节。
在x509的Golang包中,x509.ParsePKIXPublicKey说:
ParsePKIXPublicKey parses a DER-encoded public key. These values are typically found in PEM blocks with "BEGIN PUBLIC KEY"
并且,在此函数的示例中使用 pem.Decode()。我对此很困惑,因为这应该使用pem.Decode
或者类似的东西der.Decode()
?
另外,两者之间的真正区别是什么x509.ParsePKCS1PublicKey()
and x509.ParsePKIXPublicKey()
?两者都做同样的工作来获取 rsa.PublicKey 吗?