helper.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package cert
  2. import (
  3. "crypto/x509"
  4. "encoding/pem"
  5. "os"
  6. )
  7. func IsCertificate(pemStr string) bool {
  8. block, _ := pem.Decode([]byte(pemStr))
  9. if block == nil {
  10. return false
  11. }
  12. _, err := x509.ParseCertificate(block.Bytes)
  13. return err == nil
  14. }
  15. func IsPrivateKey(pemStr string) bool {
  16. block, _ := pem.Decode([]byte(pemStr))
  17. if block == nil {
  18. return false
  19. }
  20. _, errRSA := x509.ParsePKCS1PrivateKey(block.Bytes)
  21. if errRSA == nil {
  22. return true
  23. }
  24. _, errECDSA := x509.ParseECPrivateKey(block.Bytes)
  25. return errECDSA == nil
  26. }
  27. // IsCertificatePath checks if the file at the given path is a certificate or not exists.
  28. func IsCertificatePath(path string) bool {
  29. if path == "" {
  30. return false
  31. }
  32. _, err := os.Stat(path)
  33. if err != nil {
  34. if os.IsNotExist(err) {
  35. return true
  36. }
  37. return false
  38. }
  39. bytes, err := os.ReadFile(path)
  40. if err != nil {
  41. return false
  42. }
  43. return IsCertificate(string(bytes))
  44. }
  45. // IsPrivateKeyPath checks if the file at the given path is a private key or not exists.
  46. func IsPrivateKeyPath(path string) bool {
  47. if path == "" {
  48. return false
  49. }
  50. _, err := os.Stat(path)
  51. if err != nil {
  52. if os.IsNotExist(err) {
  53. return true
  54. }
  55. return false
  56. }
  57. bytes, err := os.ReadFile(path)
  58. if err != nil {
  59. return false
  60. }
  61. return IsPrivateKey(string(bytes))
  62. }