github.com/pdfcpu/pdfcpu@v0.11.1/pkg/api/certificate.go (about) 1 /* 2 Copyright 2025 The pdfcpu Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package api 18 19 import ( 20 "crypto/x509" 21 "fmt" 22 "os" 23 24 "github.com/pdfcpu/pdfcpu/pkg/pdfcpu" 25 "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model" 26 ) 27 28 func LoadCertificates() (int, error) { 29 30 if model.UserCertPool != nil { 31 return 0, nil 32 } 33 34 // if log.CLIEnabled() { 35 // log.CLI.Printf("certDir: %s\n", model.CertDir) 36 // } 37 38 if err := os.MkdirAll(model.CertDir, os.ModePerm); err != nil { 39 return 0, err 40 } 41 42 rootCAs := x509.NewCertPool() 43 44 n, err := pdfcpu.LoadCertificatesToCertPool(model.CertDir, rootCAs) 45 if err != nil { 46 return 0, err 47 } 48 49 model.UserCertPool = rootCAs 50 51 return n, nil 52 } 53 54 // ImportCertificates validates and imports found certificate files to pdfcpu config dir. 55 func ImportCertificates(inFiles []string) ([]string, error) { 56 count := 0 57 overwrite := true 58 ss := []string{} 59 for _, inFile := range inFiles { 60 n, ok, err := pdfcpu.ImportCertificate(inFile, overwrite) 61 if err != nil { 62 return nil, err 63 } 64 if !ok { 65 ss = append(ss, fmt.Sprintf("%s skipped (already imported)", inFile)) 66 continue 67 } 68 ss = append(ss, fmt.Sprintf("%s: %d certificates", inFile, n)) 69 count += n 70 } 71 72 ss = append(ss, fmt.Sprintf("imported %d certificates", count)) 73 return ss, nil 74 } 75 76 func InspectCertificates(inFiles []string) ([]string, error) { 77 count := 0 78 ss := []string{} 79 80 for _, inFile := range inFiles { 81 82 certs, err := pdfcpu.LoadCertificates(inFile) 83 if err != nil { 84 return nil, err 85 } 86 87 ss = append(ss, fmt.Sprintf("%s: %d certificates\n", inFile, len(certs))) 88 89 for i, cert := range certs { 90 s, err := pdfcpu.InspectCertificate(cert) 91 if err != nil { 92 return nil, err 93 } 94 ss = append(ss, fmt.Sprintf("%d:", i+1)) 95 ss = append(ss, s) 96 count++ 97 } 98 99 } 100 101 ss = append(ss, fmt.Sprintf("inspected %d certificates", count)) 102 return ss, nil 103 }