douboshan1466 2017-03-09 23:16
浏览 41
已采纳

如何在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 2017-03-10 12:13
    关注
    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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥200 求能开发抖音自动回复卡片的软件
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。