douzuo5504 2017-02-01 10:38
浏览 745

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

I've searched over the internet but with no results, There is any pattern (to be implemented in regex) to detect RSA private or public keys ?

(not included strings such as ---- Public RSA key-- or "ssh rsa")

I'm stuck after create base64 regex

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

Thanks

  • 写回答

1条回答 默认 最新

  • douyao1856 2017-02-02 09:35
    关注

    Get pem formatted block

    If your document contains not only PEM formatted block than Decode function from encoding/pem package will be helpful:

    Decode will find the next PEM formatted block (certificate, private key etc) in the input. It returns that block and the remainder of the input. If no PEM data is found, p is nil and the whole of the input is returned in rest.

    Parse key and check for rsa conformity

    Go contains package named crypto to do such things like parsing keys and certifies. For purpose of parsing public keys provided function ParsePKIXPublicKey:

    Supported key types include RSA, DSA, and ECDSA. Unknown key types result in an error.

    On success, pub will be of type *rsa.PublicKey, *dsa.PublicKey, or *ecdsa.PublicKey.

    On return you obtain concrete type which is easy to assert with type switch (idiomatic way to determine type of variable):

    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.")
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题