mirror of
https://gitee.com/dromara/mayfly-go
synced 2026-05-05 02:25:21 +08:00
refactor: rsa存储方式调整等
This commit is contained in:
@@ -13,6 +13,8 @@ import (
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"mayfly-go/pkg/cache"
|
||||
"mayfly-go/pkg/logx"
|
||||
"os"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -128,37 +130,68 @@ func DefaultRsaDecrypt(data string, useBase64 bool) (string, error) {
|
||||
return string(val), nil
|
||||
}
|
||||
|
||||
const publicKeyK = "mayfly:public-key"
|
||||
const privateKeyK = "mayfly:private-key"
|
||||
const (
|
||||
// 公钥文件路径
|
||||
publicKeyFile = "./mayfly_rsa.pub"
|
||||
// 私钥文件路径
|
||||
privateKeyFile = "./mayfly_rsa"
|
||||
|
||||
publicKeyK = "mayfly:public-key"
|
||||
privateKeyK = "mayfly:private-key"
|
||||
)
|
||||
|
||||
// 获取系统的RSA公钥
|
||||
func GetRsaPublicKey() (string, error) {
|
||||
publicKey := cache.GetStr(publicKeyK)
|
||||
if publicKey != "" {
|
||||
return publicKey, nil
|
||||
}
|
||||
privateKey, publicKey, err := GenerateRSAKey(1024)
|
||||
content, err := os.ReadFile(publicKeyFile)
|
||||
if err != nil {
|
||||
return "", err
|
||||
publicKey := cache.GetStr(publicKeyK)
|
||||
if publicKey != "" {
|
||||
return publicKey, nil
|
||||
}
|
||||
_, pubKey, err := GenerateAndSaveRSAKey()
|
||||
return pubKey, err
|
||||
}
|
||||
cache.SetStr(publicKeyK, publicKey, -1)
|
||||
cache.SetStr(privateKeyK, privateKey, -1)
|
||||
return publicKey, nil
|
||||
|
||||
return string(content), nil
|
||||
}
|
||||
|
||||
// 获取系统私钥
|
||||
func GetRsaPrivateKey() (string, error) {
|
||||
privateKey := cache.GetStr(privateKeyK)
|
||||
if privateKey != "" {
|
||||
return privateKey, nil
|
||||
content, err := os.ReadFile(privateKeyFile)
|
||||
if err != nil {
|
||||
privateKey := cache.GetStr(privateKeyK)
|
||||
if privateKey != "" {
|
||||
return privateKey, nil
|
||||
}
|
||||
privateKey, _, err := GenerateAndSaveRSAKey()
|
||||
return privateKey, err
|
||||
}
|
||||
|
||||
return string(content), nil
|
||||
}
|
||||
|
||||
// 生成并保存rsa key,优先保存于磁盘,若磁盘保存失败,则保存至缓存
|
||||
//
|
||||
// 依次返回 privateKey, publicKey, error
|
||||
func GenerateAndSaveRSAKey() (string, string, error) {
|
||||
privateKey, publicKey, err := GenerateRSAKey(1024)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", "", err
|
||||
}
|
||||
cache.SetStr(publicKeyK, publicKey, -1)
|
||||
cache.SetStr(privateKeyK, privateKey, -1)
|
||||
return privateKey, nil
|
||||
|
||||
err = os.WriteFile(privateKeyFile, []byte(privateKey), 0644)
|
||||
if err != nil {
|
||||
logx.ErrorTrace("RSA私钥写入磁盘文件失败, 使用缓存存储该私钥", err)
|
||||
cache.SetStr(privateKeyK, privateKey, -1)
|
||||
}
|
||||
|
||||
err = os.WriteFile(publicKeyFile, []byte(publicKey), 0644)
|
||||
if err != nil {
|
||||
logx.ErrorTrace("RSA公钥写入磁盘文件失败, 使用缓存存储该公钥", err)
|
||||
cache.SetStr(publicKeyK, publicKey, -1)
|
||||
}
|
||||
|
||||
return privateKey, publicKey, nil
|
||||
}
|
||||
|
||||
// AesEncrypt 加密
|
||||
|
||||
Reference in New Issue
Block a user