代码拉取完成,页面将自动刷新
package utils
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"os"
"path/filepath"
)
const (
privateKeyFile = "rsa_private_key.pem"
publicKeyFile = "rsa_public_key.pem"
)
func Encrypt(data string) (string, error) {
key, err := loadPublicKey(publicKeyFile)
if err != nil {
return "", err
}
res, err := EncryptWithPublicKey([]byte(data), key)
if err != nil {
return "", err
}
return res, nil
}
func Decrypt(res string) (string, error) {
key, err := loadPrivateKey(privateKeyFile)
if err != nil {
return "", err
}
data, err := DecryptWithPrivateKey(res, key)
if err != nil {
return "", err
}
return string(data), nil
}
func loadPEMFromFile(filename string) ([]byte, error) {
certPath := filepath.Join("/etc/chameleon/certs", filename)
data, err := os.ReadFile(certPath)
if err != nil {
return nil, fmt.Errorf("unable to read file %s, %w", filename, err)
}
return data, nil
}
func loadPrivateKey(filename string) (*rsa.PrivateKey, error) {
data, err := loadPEMFromFile(filename)
if err != nil {
return nil, err
}
block, _ := pem.Decode(data)
if block == nil || block.Type != "RSA PRIVATE KEY" {
return nil, errors.New("invalid private key PEM file")
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("unable to parse private key, %w", err)
}
return privateKey, nil
}
func loadPublicKey(filename string) (*rsa.PublicKey, error) {
data, err := loadPEMFromFile(filename)
if err != nil {
return nil, err
}
block, _ := pem.Decode(data)
if block == nil || block.Type != "PUBLIC KEY" {
return nil, errors.New("invalid public key PEM file")
}
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("unable to parse public key, %w", err)
}
publicKey, ok := publicKeyInterface.(*rsa.PublicKey)
if !ok {
return nil, errors.New("invalid public key type")
}
return publicKey, nil
}
func EncryptWithPublicKey(data []byte, publicKey *rsa.PublicKey) (res string, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("invalid raw text")
}
}()
encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, data)
if err != nil {
return "", fmt.Errorf("unable to encrypt data, %w", err)
}
return base64.StdEncoding.EncodeToString(encryptedData), nil
}
func DecryptWithPrivateKey(encrypted string, privateKey *rsa.PrivateKey) (res []byte, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("invalid raw text")
}
}()
encryptedData, err := base64.StdEncoding.DecodeString(encrypted)
if err != nil {
return nil, err
}
decryptedData, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, encryptedData)
if err != nil {
return nil, fmt.Errorf("unable to decrypt data, %w", err)
}
return decryptedData, nil
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。