正则表达式,用于检测私有和公共RSA密钥

时间:2017-02-01 10:38:57

标签: regex go

我在互联网上搜索但没有结果, 是否有任何模式(在regex中实现)来检测RSA私钥或公钥?

(不包括---- Public RSA key--或“ssh rsa”等字符串)

创建base64正则表达式后我被卡住了

var re = regexp.MustCompile(`(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3})=`)

由于

1 个答案:

答案 0 :(得分:0)

获取pem格式化块

如果您的文档不仅包含PEM格式的块,而且包含来自encoding/pem包的Decode函数将有帮助:

  

解码将在输入中找到下一个PEM格式化的块(证书,私钥等)。它返回该块和输入的其余部分。如果没有找到PEM数据,则p为nil,并且整个输入将在休息时返回。

解析密钥并检查rsa符合性

Go包含名为crypto的包,用于执行解析密钥和证明等操作。为了解析提供函数ParsePKIXPublicKey的公钥:

  

支持的密钥类型包括RSA,DSA和ECDSA。未知的密钥类型会导致错误。

     

成功时,pub的类型为* rsa.PublicKey,* dsa.PublicKey或* ecdsa.PublicKey。

返回时,您将获得具有类型切换容易断言的具体类型(用于确定变量类型的惯用方法):

Example

// There is a key
const pubPEM = `MIICIjANBgkqhkiG9...`

// Ignore the rest of document
block, _ := pem.Decode([]byte(pubPEM))
if block == nil {
    log.Fatal("The document doesn't contain PEM blocks.")
}

pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
    log.Fatal("The block is not a DER encoded public key.")
}

switch pub := pub.(type) {
case *rsa.PublicKey:
    fmt.Println("pub is of type RSA:", pub)
default:
    log.Fatal("The key is not RSA encripted.")
}