-
Notifications
You must be signed in to change notification settings - Fork 0
/
Certencrypt.go
63 lines (52 loc) · 1.58 KB
/
Certencrypt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package darajaAuth
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"io"
"os"
)
type certificationError struct {
Context string
Err error
}
// Error implements the error interface for certificationError.
func (e *certificationError) Error() string {
return fmt.Sprintf("%s: %v", e.Context, e.Err)
}
func openSSlEncrypt(data, certPath string) (string, error) {
cert, err := loadCertificate(certPath)
if err != nil {
return "", &certificationError{Context: "failed to load certificate", Err: err}
}
encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, cert.PublicKey.(*rsa.PublicKey), []byte(data))
if err != nil {
return "", &certificationError{Context: "encryption failed", Err: err}
}
return base64.StdEncoding.EncodeToString(encrypted), nil
}
// loadCertificate loads and parses the X.509 certificate.
func loadCertificate(certPath string) (*x509.Certificate, error) {
certFile, err := os.Open(certPath)
if err != nil {
return nil, &certificationError{Context: "failed to open certificate file", Err: err}
}
defer certFile.Close()
certBytes, err := io.ReadAll(certFile)
if err != nil {
return nil, &certificationError{Context: "failed to read certificate file", Err: err}
}
block, _ := pem.Decode(certBytes)
if block == nil {
return nil, &certificationError{Context: "failed to parse certificate PEM", Err: errors.New("no PEM block found")}
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, &certificationError{Context: "failed to parse certificate", Err: err}
}
return cert, nil
}