add:完善控制中心授权信息部分内容提取 待完善接口相关信息

This commit is contained in:
samwaf
2024-07-08 16:38:21 +08:00
parent d69f59ff2c
commit fb89dcf27c
20 changed files with 704 additions and 64 deletions
+2 -1
View File
@@ -8,4 +8,5 @@
/data/local_log.db-shm
/data/local_log.db-wal
/data/local_stats.db-shm
/data/local_stats.db-wal
/data/local_stats.db-wal
registration_data.bin
+40
View File
@@ -73,3 +73,43 @@ func (w *CenterApi) GetListApi(c *gin.Context) {
response.FailWithMessage("解析失败", c)
}
}
/*
*
TODO 获取授权信息
*/
func (w *CenterApi) GetRegInfoApi(c *gin.Context) {
var req request.CenterClientSearchReq
err := c.ShouldBindJSON(&req)
if err == nil {
beans, total, _ := CenterService.GetListApi(req)
response.OkWithDetailed(response.PageResult{
List: beans,
Total: total,
PageIndex: req.PageIndex,
PageSize: req.PageSize,
}, "获取成功", c)
} else {
response.FailWithMessage("解析失败", c)
}
}
/*
*
TODO 设置授权信息,此时用户上传注册信息注册文件,并保存在当前目录下
*/
func (w *CenterApi) SetRegInfoApi(c *gin.Context) {
var req request.CenterClientSearchReq
err := c.ShouldBindJSON(&req)
if err == nil {
beans, total, _ := CenterService.GetListApi(req)
response.OkWithDetailed(response.PageResult{
List: beans,
Total: total,
PageIndex: req.PageIndex,
PageSize: req.PageSize,
}, "获取成功", c)
} else {
response.FailWithMessage("解析失败", c)
}
}
+14
View File
@@ -0,0 +1,14 @@
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAs1/PB/2s9tsFKkDKQPfY
JcLGVY+GqRCCixOe+Nj7r8hbC4KmdP3HlRjhhp2rz200QWP8mhX3hIzOltfu3/ln
bPAAROH+sZaPM5EcFo0OiXA4pynWniUAreS5GW+oOaUE+4ZPfxB8MX8io/2oAZ33
zFyj+sXwiyg96OaxppRVzMDYuodaE3YyUDVqMBDpHhR+gkln6xh/fAb2jvw7CiKn
VO/ntsohj5h9OfdtAd1rkZ6S45P49ILgcj3fBDrAhGkkXrFS7koV1fqPKaE9EjuH
lARTJdG6XqjwI8p6HKPOIUW0Scg55YsxV0cS0ZC1dCCnwe6sQnNT8Rd5e7kREhzY
nkkoius8+veptOfwDBfnAglrO/FgAttRN3RK21bEjDCMaYMMuVKLpj4OemNYIxnB
XB+aPT3q8FBIsbzqmdmyxf47HW7i4yE6W3P6Cergchl3vv9ofJboyGHsMVjSCQXh
St2kzg0YcszwUibYVREFpl6CRymlaYfhHHMD/bK138p6br+N63q3m9KEa7M9MJZd
9xWzCwrHOdmzFinrvuYwsBgb+0QWuoKECaDBgFmF4+peoag6TBAZQ+9q2jVW4dsu
dYXMkkmxawGOtynnIi1kkYCYkQLGyQDN3yg6o6X0WlEEOvC1zJg5aRPpA644DZKF
vaNfDS6mkM78J4Dlu2yJ8mMCAwEAAQ==
-----END PUBLIC KEY-----
+6 -2
View File
@@ -122,8 +122,12 @@ var (
/**
中心管控部分
*/
GWAF_CENTER_ENABLE string = "false" //中心管控激活状态
GWAF_CENTER_URL string = "http://127.0.0.1:26666" //中心管控默认URL
GWAF_CENTER_ENABLE string = "false" //中心管控激活状态
GWAF_CENTER_URL string = "http://127.0.0.1:26666" //中心管控默认URL
GWAF_REG_INFO model.RegistrationInfo //当前注册信息
GWAF_REG_VERSION = "v1" //注册信息版本
GWAF_REG_KEY = []byte("5F!vion$k@a7QZ&)") //注册信息加密密钥
GWAF_REG_PUBLIC_KEY string = "" //注册信息加密公钥
)
func GetCurrentVersionInt() int {
+40 -17
View File
@@ -23,29 +23,52 @@ export function getBaseUrl(){
export function getOnlineUrl(){
return "https://doc.samwaf.com"
}
//解密数据
export function AesDecrypt( text ){
let key = CryptoJS.enc.Utf8.parse("7E@u*has$d*@s5YX");
let decryptedData = CryptoJS.AES.decrypt(text, key, {
iv: key,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return decryptedData.toString(CryptoJS.enc.Utf8);
// 生成随机的IV
function generateRandomIV() {
return CryptoJS.lib.WordArray.random(16);
}
//加密数据
export function AesEncrypt( text ){
let key = CryptoJS.enc.Utf8.parse("7E@u*has$d*@s5YX");
let encryptedData = CryptoJS.AES.encrypt(text, key, {
iv: key, // 使用相同的 IV 和密钥
// 解密数据
export function AesDecrypt(encryptedText: string) {
const key = CryptoJS.enc.Utf8.parse("7E@u*has$d*@s5YX");
// 分离加密数据和IV
const encryptedDataWithIV = CryptoJS.enc.Base64.parse(encryptedText);
const iv = CryptoJS.lib.WordArray.create(
encryptedDataWithIV.words.slice(0, 4)
); // IV为前16字节
const encryptedData = CryptoJS.lib.WordArray.create(
encryptedDataWithIV.words.slice(4)
); // 剩余为加密数据
const decrypted = CryptoJS.AES.decrypt(
{ ciphertext: encryptedData },
key,
{
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
}
);
return decrypted.toString(CryptoJS.enc.Utf8);
}
// 加密数据
export function AesEncrypt( plainText: string) {
const key = CryptoJS.enc.Utf8.parse("7E@u*has$d*@s5YX");
const iv = generateRandomIV();
const encrypted = CryptoJS.AES.encrypt(plainText, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
padding: CryptoJS.pad.Pkcs7,
});
return encryptedData.toString();
// 将IV和加密数据一起编码为Base64字符串
const encryptedDataWithIV = iv.concat(encrypted.ciphertext);
return CryptoJS.enc.Base64.stringify(encryptedDataWithIV);
}
/**
* 判断是否是对象
+26
View File
@@ -15,6 +15,7 @@ import (
"SamWaf/wafdb"
"SamWaf/wafenginecore"
"SamWaf/wafmangeweb"
"SamWaf/wafreg"
"SamWaf/wafsafeclear"
"SamWaf/wafsnowflake"
"SamWaf/waftask"
@@ -46,6 +47,10 @@ var Ip2regionBytes []byte // 当前目录,解析为[]byte类型
//go:embed exedata/ldpconfig.yml
var ldpConfig string //隐私防护ldp
//go:embed exedata/public_key.pem
var publicKey string //公钥key
// wafSystenService 实现了 service.Service 接口
type wafSystenService struct{}
@@ -96,6 +101,7 @@ func (m *wafSystenService) run() {
global.GCACHE_IP_CBUFF = Ip2regionBytes
global.GWAF_DLP_CONFIG = ldpConfig
global.GWAF_REG_PUBLIC_KEY = publicKey
/*// 启动一个 goroutine 来处理信号
go func() {
@@ -279,6 +285,26 @@ func (m *wafSystenService) run() {
}
/*withEncrypt, err :=wafreg.GenClientMachineInfoWithEncrypt()
if err != nil {
fmt.Println("获取机器码失败")
} else {
fmt.Println("机器码: ", withEncrypt)
}*/
//加载授权信息
verifyResult, info, err := wafreg.VerifyServerReg()
if verifyResult {
global.GWAF_REG_INFO = info
zlog.Debug("授权信息 调试信息", info)
expiryDay, isExpiry := wafreg.CheckExpiry(info.ExpiryDate)
if isExpiry {
zlog.Info("授权信息已经过期")
} else {
zlog.Info("授权信息还剩余:" + strconv.Itoa(expiryDay) + "天")
}
} else {
zlog.Info("授权信息无效", err)
}
// 上传客户端信息到中心节点
globalobj.GWAF_RUNTIME_OBJ_WAF_CRON.Every(1).Minutes().Do(func() {
go waftask.TaskClientToCenter()
+2 -3
View File
@@ -4,7 +4,6 @@ import (
"SamWaf/service/waf_service"
"SamWaf/utils/zlog"
"bytes"
"fmt"
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
@@ -18,12 +17,12 @@ var (
// 中心管控 鉴权中间件
func CenterApi() gin.HandlerFunc {
return func(c *gin.Context) {
for key, values := range c.Request.Header {
/*for key, values := range c.Request.Header {
fmt.Printf("Header key: %s\n", key)
for _, value := range values {
fmt.Printf(" Value: %s\n", value)
}
}
}*/
remoteWafUserId := c.Request.Header.Get("Remote-Waf-User-Id") //tencent@usercode
if remoteWafUserId != "" {
+2 -4
View File
@@ -4,7 +4,6 @@ import (
"SamWaf/global"
"SamWaf/wafsec"
"bytes"
"encoding/base64"
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
@@ -31,12 +30,11 @@ func SecApi() gin.HandlerFunc {
if c.Request.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
// Modify the bodyBytes if necessary
// ...
base64Bytes, _ := base64.StdEncoding.DecodeString(string(bodyBytes))
deBytes := wafsec.AesDecrypt(base64Bytes, global.GWAF_COMMUNICATION_KEY)
decryptBytes, _ := wafsec.AesDecrypt(string(bodyBytes), global.GWAF_COMMUNICATION_KEY)
//fmt.Println("Raw body解密:", string(deBytes))
// Store the modified body back in the request
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(deBytes))
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(decryptBytes))
}
c.Next()
}
+2 -1
View File
@@ -22,10 +22,11 @@ const (
func Result(code int, data interface{}, msg string, c *gin.Context) {
result, _ := json.Marshal(data) //将数据转换为json
encryptStr, _ := wafsec.AesEncrypt(result, global.GWAF_COMMUNICATION_KEY)
// 开始时间
c.JSON(http.StatusOK, Response{
code,
wafsec.AesEncrypt(result, global.GWAF_COMMUNICATION_KEY),
encryptStr,
msg,
})
}
+28
View File
@@ -0,0 +1,28 @@
package model
import "time"
/*
*
注册信息
*/
type RegistrationInfo struct {
Version string `json:"version"`
Username string `json:"username"`
MemberType string `json:"member_type"`
MachineID string `json:"machine_id"`
ExpiryDate time.Time `json:"expiry_date"`
}
/*
*
机器信息
*/
type MachineInfo struct {
Version string `json:"version"`
MachineID string `json:"machine_id"`
ClientServerName string `json:"client_server_name"` // 客户端-自定义名称
ClientTenantId string `json:"client_tenant_id"` // 客户端-租户ID
ClientUserCode string `json:"client_user_code"` // 客户端-用户码
OtherFeature string `json:"other_feature"` // 预留其他特征
}
+6 -4
View File
@@ -125,11 +125,11 @@ func ProcessDequeEngine() {
MessageDateTime: time.Now().Format("2006-01-02 15:04:05"),
MessageUnReadStatus: true,
})
encryptStr, _ := wafsec.AesEncrypt(msgBody, global.GWAF_COMMUNICATION_KEY)
//写入ws数据
msgBytes, err := json.Marshal(model.MsgPacket{
MsgCode: "200",
MsgDataPacket: wafsec.AesEncrypt(msgBody, global.GWAF_COMMUNICATION_KEY),
MsgDataPacket: encryptStr,
MsgCmdType: "Info",
})
err = ws.WriteMessage(1, msgBytes)
@@ -159,10 +159,11 @@ func ProcessDequeEngine() {
MessageDateTime: time.Now().Format("2006-01-02 15:04:05"),
MessageUnReadStatus: true,
})
encryptStr, _ := wafsec.AesEncrypt(msgBody, global.GWAF_COMMUNICATION_KEY)
//写入ws数据
msgBytes, err := json.Marshal(model.MsgPacket{
MsgCode: "200",
MsgDataPacket: wafsec.AesEncrypt(msgBody, global.GWAF_COMMUNICATION_KEY),
MsgDataPacket: encryptStr,
MsgCmdType: "Info",
})
err = ws.WriteMessage(1, msgBytes)
@@ -188,10 +189,11 @@ func ProcessDequeEngine() {
MessageDateTime: time.Now().Format("2006-01-02 15:04:05"),
MessageUnReadStatus: true,
})
encryptStr, _ := wafsec.AesEncrypt(msgBody, global.GWAF_COMMUNICATION_KEY)
//写入ws数据
msgBytes, err := json.Marshal(model.MsgPacket{
MsgCode: "200",
MsgDataPacket: wafsec.AesEncrypt(msgBody, global.GWAF_COMMUNICATION_KEY),
MsgDataPacket: encryptStr,
MsgCmdType: "Info",
})
err = ws.WriteMessage(1, msgBytes)
+147
View File
@@ -0,0 +1,147 @@
package wafreg
import (
"SamWaf/global"
"SamWaf/model"
"SamWaf/wafsec"
"bytes"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"time"
)
/*
*
生成客户端机器信息
*/
func genClientMachineInfo() model.MachineInfo {
machineInfo := model.MachineInfo{
Version: "v1",
ClientServerName: global.GWAF_CUSTOM_SERVER_NAME,
ClientTenantId: global.GWAF_TENANT_ID,
ClientUserCode: global.GWAF_USER_CODE,
OtherFeature: "",
}
//需要加签得字段
needSignStr := machineInfo.ClientServerName + machineInfo.ClientTenantId + machineInfo.ClientUserCode
machineInfo.MachineID = fmt.Sprintf("%x", sha256.Sum256([]byte(needSignStr)))
return machineInfo
}
/*
*
生成客户端机器码加密信息
*/
func GenClientMachineInfoWithEncrypt() (string, error) {
cryptoUtil := &wafsec.CryptoUtil{}
publicKey := []byte(global.GWAF_REG_PUBLIC_KEY)
machineInfo, err := json.Marshal(genClientMachineInfo())
if err != nil {
return "转换json异常", err
}
rsaEncrypt, err := cryptoUtil.RsaEncrypt(machineInfo, publicKey)
if err != nil {
return "信息加密异常", err
}
encodeToString := base64.StdEncoding.EncodeToString(rsaEncrypt)
return encodeToString, nil
}
/*
*
校验注册服务信息
*/
func VerifyServerReg() (bool, model.RegistrationInfo, error) {
//根据用户传来得数据信息
cryptoUtil := &wafsec.CryptoUtil{}
publicKey := []byte(global.GWAF_REG_PUBLIC_KEY)
// 假设读取当前机器的机器码
currentMachineInfo := genClientMachineInfo()
// 从文件中读取二进制数据
binData, err := ioutil.ReadFile("./registration_data.bin")
if err != nil {
return false, model.RegistrationInfo{}, errors.New("验签失败-加载注册信息")
}
buffer := bytes.NewBuffer(binData)
// 读取注册信息长度
var dataLen int32
err = binary.Read(buffer, binary.LittleEndian, &dataLen)
if err != nil {
return false, model.RegistrationInfo{}, errors.New("验签失败-读取注册信息长度失败")
}
// 读取注册信息
data := make([]byte, dataLen)
_, err = buffer.Read(data)
if err != nil {
return false, model.RegistrationInfo{}, errors.New("验签失败-读取注册信息失败")
}
// 读取签名长度
var sigLen int32
err = binary.Read(buffer, binary.LittleEndian, &sigLen)
if err != nil {
return false, model.RegistrationInfo{}, errors.New("验签失败-读取签名长度失败")
}
// 读取签名
signature := make([]byte, sigLen)
_, err = buffer.Read(signature)
if err != nil {
return false, model.RegistrationInfo{}, errors.New("验签失败-读取签名失败")
}
// 客户端验证签名
signWithSha256Result := cryptoUtil.RsaVerySignWithSha256(data, signature, publicKey)
if !signWithSha256Result {
return false, model.RegistrationInfo{}, errors.New("验签失败")
} else {
decrypt, err := wafsec.AesDecrypt(string(data), global.GWAF_REG_KEY)
data = decrypt
// 解析数据
var regInfo model.RegistrationInfo
err = json.Unmarshal(data, &regInfo)
if err != nil {
return false, model.RegistrationInfo{}, errors.New("验签成功-转换json失败")
}
// 验证机器码
if regInfo.MachineID != currentMachineInfo.MachineID {
return false, model.RegistrationInfo{}, errors.New("验签成功-机器码不正确")
} else {
return true, regInfo, nil
}
}
}
// CheckExpiry 计算给定日期与当前日期的天数差,并返回是否到期
func CheckExpiry(date time.Time) (int, bool) {
// 获取当前日期
now := time.Now()
// 将当前时间和给定时间都转为零点,以比较日期
now = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
date = time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, date.Location())
// 计算日期差
duration := date.Sub(now)
// 计算天数差
days := int(duration.Hours() / 24)
// 判断是否到期
expired := days < 0
return days, expired
}
+53 -26
View File
@@ -4,41 +4,68 @@ import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"io"
)
// AesEncrypt data为明文 key为密钥
func AesEncrypt(data, key []byte) string {
block, err := aes.NewCipher(key)
if err != nil {
return ""
}
blockSize := block.BlockSize()
// PKCS7Padding applies PKCS7 padding.
func PKCS7Padding(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
text := bytes.Repeat([]byte{byte(padding)}, padding)
data = append(data, text...)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypt := make([]byte, len(data))
blockMode.CryptBlocks(crypt, data)
return base64.StdEncoding.EncodeToString(crypt)
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}
// AesDecrypt 使用AES解密算法对数据进行解密
func AesDecrypt(data, key []byte) []byte {
// PKCS7UnPadding removes PKCS7 padding.
func PKCS7UnPadding(data []byte) ([]byte, error) {
length := len(data)
if length == 0 {
return nil, errors.New("invalid padding size")
}
padding := int(data[length-1])
if padding > length {
return nil, errors.New("invalid padding size")
}
return data[:length-padding], nil
}
// AesEncrypt encrypts data using AES algorithm with the given key.
func AesEncrypt(data, key []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil
return "", err
}
blockSize := block.BlockSize()
if len(data) < blockSize {
return nil
data = PKCS7Padding(data, blockSize)
crypt := make([]byte, blockSize+len(data))
iv := crypt[:blockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
iv := key[:blockSize] // 选择密钥的前blockSize字节作为IV
blockMode := cipher.NewCBCDecrypter(block, iv)
decryptedData := make([]byte, len(data))
blockMode.CryptBlocks(decryptedData, data)
// 去除填充
padding := int(decryptedData[len(decryptedData)-1])
return decryptedData[:len(decryptedData)-padding]
blockMode := cipher.NewCBCEncrypter(block, iv)
blockMode.CryptBlocks(crypt[blockSize:], data)
return base64.StdEncoding.EncodeToString(crypt), nil
}
// AesDecrypt decrypts data using AES algorithm with the given key.
func AesDecrypt(data string, key []byte) ([]byte, error) {
crypt, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
if len(crypt) < blockSize {
return nil, errors.New("ciphertext too short")
}
iv := crypt[:blockSize]
crypt = crypt[blockSize:]
blockMode := cipher.NewCBCDecrypter(block, iv)
decrypted := make([]byte, len(crypt))
blockMode.CryptBlocks(decrypted, crypt)
return PKCS7UnPadding(decrypted)
}
+10
View File
@@ -0,0 +1,10 @@
package wafsec
import "testing"
func TestGenPublicPrivate(t *testing.T) {
GenPublicPrivate()
}
func TestEncryptInfo(t *testing.T) {
EncryptInfo("asaasdfsdfsdf")
}
+178
View File
@@ -0,0 +1,178 @@
package wafsec
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"os"
)
type CryptoUtil struct {
}
// 生成密钥对
func (r *CryptoUtil) CreateKeys(bits int) (prvkey, pubkey []byte) {
// 生成私钥文件
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
panic(err)
}
derStream := x509.MarshalPKCS1PrivateKey(privateKey)
block := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: derStream,
}
prvkey = pem.EncodeToMemory(block)
publicKey := &privateKey.PublicKey
derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
panic(err)
}
block = &pem.Block{
Type: "PUBLIC KEY",
Bytes: derPkix,
}
pubkey = pem.EncodeToMemory(block)
return
}
// 公钥加密
func (r *CryptoUtil) RsaEncrypt(data, keyBytes []byte) ([]byte, error) {
//解密pem格式的公钥
block, _ := pem.Decode(keyBytes)
if block == nil {
panic(errors.New("public key error"))
}
// 解析公钥
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
panic(err)
}
// 类型断言
pub := pubInterface.(*rsa.PublicKey)
partLen := pub.N.BitLen()/8 - 11
chunks := split([]byte(data), partLen)
buffer := bytes.NewBufferString("")
//加密
for _, chunk := range chunks {
bytes, err := rsa.EncryptPKCS1v15(rand.Reader, pub, chunk)
if err != nil {
return nil, err
}
buffer.Write(bytes)
}
//加密
ciphertext := buffer.Bytes()
return ciphertext, nil
}
// 私钥解密
func (r *CryptoUtil) RsaDecrypt(ciphertext, keyBytes []byte) ([]byte, error) {
//获取私钥
block, _ := pem.Decode(keyBytes)
if block == nil {
panic(errors.New("private key error!"))
}
//解析PKCS1格式的私钥
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
partLen := priv.N.BitLen() / 8
chunks := split([]byte(ciphertext), partLen)
// 解密
buffer := bytes.NewBufferString("")
for _, chunk := range chunks {
decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, priv, chunk)
if err != nil {
return nil, err
}
buffer.Write(decrypted)
}
return buffer.Bytes(), nil
}
// 签名
func (r *CryptoUtil) RsaSignWithSha256(data []byte, keyBytes []byte) ([]byte, error) {
h := sha256.New()
h.Write(data)
hashed := h.Sum(nil)
block, _ := pem.Decode(keyBytes)
if block == nil {
return nil, errors.New(fmt.Sprintf("private key error: "))
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, errors.New(fmt.Sprintf("ParsePKCS8PrivateKey: %s\n", err))
}
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed)
if err != nil {
return nil, errors.New(fmt.Sprintf("Error from signing: %s\n", err))
}
return signature, nil
}
// 验证
func (r *CryptoUtil) RsaVerySignWithSha256(data, signData, keyBytes []byte) bool {
block, _ := pem.Decode(keyBytes)
if block == nil {
panic(errors.New("public key error"))
}
pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
panic(err)
}
hashed := sha256.Sum256(data)
err = rsa.VerifyPKCS1v15(pubKey.(*rsa.PublicKey), crypto.SHA256, hashed[:], signData)
if err != nil {
panic(err)
}
return true
}
func split(buf []byte, lim int) [][]byte {
var chunk []byte
chunks := make([][]byte, 0, len(buf)/lim+1)
for len(buf) >= lim {
chunk, buf = buf[:lim], buf[lim:]
chunks = append(chunks, chunk)
}
if len(buf) > 0 {
chunks = append(chunks, buf[:len(buf)])
}
return chunks
}
func (r *CryptoUtil) File2Bytes(filename string) ([]byte, error) {
// File
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
// FileInfo:
stats, err := file.Stat()
if err != nil {
return nil, err
}
// []byte
data := make([]byte, stats.Size())
count, err := file.Read(data)
if err != nil {
return nil, err
}
fmt.Printf("read file %s len: %d \n", filename, count)
return data, nil
}
+31
View File
@@ -0,0 +1,31 @@
package wafsec
import (
"fmt"
"io/ioutil"
"testing"
)
func TestCryptoUtil_CreateKeys(t *testing.T) {
//生成密钥对
crsa := CryptoUtil{}
//rsa 密钥文件产生
fmt.Println("-------------------------------获取RSA公私钥-----------------------------------------")
prvKey, pubKey := crsa.CreateKeys(4096)
fmt.Println(string(prvKey))
fmt.Println(string(pubKey))
// 保存私钥和公钥到文件
err := ioutil.WriteFile("private_key.pem", prvKey, 0600)
if err != nil {
panic(err)
}
err = ioutil.WriteFile("public_key.pem", pubKey, 0600)
if err != nil {
panic(err)
}
pubKey, _ = crsa.File2Bytes("public_key.pem")
prvKey, _ = crsa.File2Bytes("private_key.pem")
}
+111
View File
@@ -0,0 +1,111 @@
package wafsec
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"io/ioutil"
)
func GenPublicPrivate() {
// 生成密钥对
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(err)
}
publicKey := &privateKey.PublicKey
// 将私钥转换为PEM格式
privateKeyPEM := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}
privateKeyPEMBytes := pem.EncodeToMemory(privateKeyPEM)
// 将公钥转换为PEM格式
publicKeyPEM := &pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: x509.MarshalPKCS1PublicKey(publicKey),
}
publicKeyPEMBytes := pem.EncodeToMemory(publicKeyPEM)
// 将PEM格式的密钥转换为Base64编码
privateKeyBase64 := base64.StdEncoding.EncodeToString(privateKeyPEMBytes)
publicKeyBase64 := base64.StdEncoding.EncodeToString(publicKeyPEMBytes)
// 保存私钥和公钥到文件
err = ioutil.WriteFile("private_key.pem", privateKeyPEMBytes, 0600)
if err != nil {
panic(err)
}
err = ioutil.WriteFile("public_key.pem", publicKeyPEMBytes, 0600)
if err != nil {
panic(err)
}
// 打印Base64编码的私钥和公钥
fmt.Println("Base64 Encoded Private Key:")
fmt.Println(privateKeyBase64)
fmt.Println("Base64 Encoded Public Key:")
fmt.Println(publicKeyBase64)
}
func EncryptInfo(str string) {
// 从文件中读取私钥和公钥
privateKeyPEMBytes, err := ioutil.ReadFile("private_key.pem")
if err != nil {
panic(err)
}
publicKeyPEMBytes, err := ioutil.ReadFile("public_key.pem")
if err != nil {
panic(err)
}
// 将Base64编码的私钥和公钥解码回PEM格式
privateKeyPEM, _ := pem.Decode(privateKeyPEMBytes)
publicKeyPEM, _ := pem.Decode(publicKeyPEMBytes)
// 从PEM格式恢复私钥和公钥
privateKey, err := x509.ParsePKCS1PrivateKey(privateKeyPEM.Bytes)
if err != nil {
panic(err)
}
publicKey, err := x509.ParsePKCS1PublicKey(publicKeyPEM.Bytes)
if err != nil {
panic(err)
}
// 打印恢复的私钥和公钥
fmt.Println("Restored Private Key:")
fmt.Println(privateKey)
fmt.Println("Restored Public Key:")
fmt.Println(publicKey)
// 使用公钥加密消息
message := []byte(str)
encryptedBytes, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, message, nil)
if err != nil {
panic(err)
}
fmt.Println("Encrypted message:", encryptedBytes)
// The first argument is an optional random data generator (the rand.Reader we used before)
// we can set this value as nil
// The OEAPOptions in the end signify that we encrypted the data using OEAP, and that we used
// SHA256 to hash the input.
decryptedBytes, err := privateKey.Decrypt(nil, encryptedBytes, &rsa.OAEPOptions{Hash: crypto.SHA256})
if err != nil {
panic(err)
}
// We get back the original information in the form of bytes, which we
// the cast to a string and print
fmt.Println("decrypted message: ", string(decryptedBytes))
}
+2 -3
View File
@@ -1,19 +1,18 @@
package wafsec
import (
"fmt"
"testing"
)
func TestWafSec_EncryptDES3(t *testing.T) {
wafsec := WafSec{}
/*wafsec := WafSec{}
key := "nilihaile"
plaintext := "https://asdf.com"
ciphertext := wafsec.Encrypt(key, plaintext)
decrypted := wafsec.Decrypt(key, ciphertext)
fmt.Println("Original:", plaintext)
fmt.Println("Encrypted:", ciphertext)
fmt.Println("Decrypted:", decrypted)
fmt.Println("Decrypted:", decrypted)*/
}
func TestWafSec_DecryptDES3(t *testing.T) {
+2 -2
View File
@@ -462,12 +462,12 @@ func TaskDelayInfo() {
MessageDateTime: time.Now().Format("2006-01-02 15:04:05"),
MessageUnReadStatus: true,
})
encryptStr, _ := wafsec.AesEncrypt(msgBody, global.GWAF_COMMUNICATION_KEY)
//写入ws数据
msgBytes, err := json.Marshal(
model.MsgPacket{
MsgCode: "200",
MsgDataPacket: wafsec.AesEncrypt(msgBody, global.GWAF_COMMUNICATION_KEY),
MsgDataPacket: encryptStr,
MsgCmdType: cmdType,
})
err = ws.WriteMessage(1, msgBytes)
+2 -1
View File
@@ -51,7 +51,8 @@ func TaskClientToCenter() {
return
}
//加密
encryptContent := wafsec.AesEncrypt(jsonData, global.GWAF_COMMUNICATION_KEY)
encryptStr, _ := wafsec.AesEncrypt(jsonData, global.GWAF_COMMUNICATION_KEY)
encryptContent := encryptStr
zlog.Debug("注册加密前" + string(jsonData))
zlog.Debug("注册加后" + encryptContent)
// 创建请求URL