douboshan1466
douboshan1466
2017-03-09 23:16

如何在Go中验证RSA密钥长度?

已采纳

I'm setting up a https server in Go using the following function.

err := http.ListenAndServeTLS(":8080", key, cert, nil)
if err != nil {
    log.Fatal("error...")
}

Where key and cert are respectively self-signed key and certificate files. My problem is that for security I need to validate they self-signed key to have a 2048 bits size (or more). How can I securely and cleanly check for this in Go?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douzhuan0309 douzhuan0309 4年前
    package main
    
    import (
        "crypto/ecdsa"
        "crypto/rsa"
        "crypto/tls"
        "log"
        "net/http"
    )
    
    func main() {
        certFile := "/tmp/cert.pem"
        keyFile := "/tmp/key.pem"
    
        cert, err := tls.LoadX509KeyPair(certFile, keyFile)
        if err != nil {
            log.Fatal(err)
        }
    
        var bitLen int
        switch privKey := cert.PrivateKey.(type) {
        case *rsa.PrivateKey:
            bitLen = privKey.N.BitLen()
        case *ecdsa.PrivateKey:
            bitLen = privKey.Curve.Params().BitSize
        default:
            log.Fatal("unsupported private key")
        }
    
        if bitLen < 2048 {
            log.Fatalf("private key length is too small (size: %d)
    ", bitLen)
        }
    
        tlsConfig := tls.Config{
            Certificates: []tls.Certificate{cert},
        }
    
        server := http.Server{
            Addr:      ":8080",
            TLSConfig: &tlsConfig,
        }
        if err := server.ListenAndServeTLS("", ""); err != nil {
            log.Fatal(err)
        }
    }
    
    点赞 评论 复制链接分享

为你推荐