certvalidate.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package certvalidate
  2. import (
  3. "crypto/x509"
  4. "encoding/pem"
  5. "io"
  6. "mime/multipart"
  7. "strings"
  8. )
  9. func isValidTLSFile(file multipart.File) bool {
  10. // Read the contents of the uploaded file
  11. contents, err := io.ReadAll(file)
  12. if err != nil {
  13. // Handle the error
  14. return false
  15. }
  16. // Parse the contents of the file as a PEM-encoded certificate or key
  17. block, _ := pem.Decode(contents)
  18. if block == nil {
  19. // The file is not a valid PEM-encoded certificate or key
  20. return false
  21. }
  22. // Parse the certificate or key
  23. if strings.Contains(block.Type, "CERTIFICATE") {
  24. // The file contains a certificate
  25. cert, err := x509.ParseCertificate(block.Bytes)
  26. if err != nil {
  27. // Handle the error
  28. return false
  29. }
  30. // Check if the certificate is a valid TLS/SSL certificate
  31. return cert.IsCA == false && cert.KeyUsage&x509.KeyUsageDigitalSignature != 0 && cert.KeyUsage&x509.KeyUsageKeyEncipherment != 0
  32. } else if strings.Contains(block.Type, "PRIVATE KEY") {
  33. // The file contains a private key
  34. _, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  35. if err != nil {
  36. // Handle the error
  37. return false
  38. }
  39. return true
  40. } else {
  41. return false
  42. }
  43. }