fix version 1
This commit is contained in:
@@ -2,20 +2,16 @@ package private
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
pb "bsm/full/module/base/cloud/pb"
|
||||
"git.apinb.com/bsm-sdk/core/errcode"
|
||||
"git.apinb.com/bsm-sdk/core/printer"
|
||||
"git.apinb.com/bsm-sdk/core/service"
|
||||
)
|
||||
|
||||
// 加密数据
|
||||
// 加密数据(使用服务端密钥,客户端传入的 Key 不再作为服务端密钥)
|
||||
func EncryptData(ctx context.Context, in *pb.DataRequest) (reply *pb.StatusReply, err error) {
|
||||
// parse authorization meta.
|
||||
_, err = service.ParseMetaCtx(ctx, nil)
|
||||
@@ -27,47 +23,14 @@ func EncryptData(ctx context.Context, in *pb.DataRequest) (reply *pb.StatusReply
|
||||
if strings.TrimSpace(in.Data) == "" {
|
||||
return nil, errcode.ErrInvalidArgument
|
||||
}
|
||||
if strings.TrimSpace(in.Key) == "" {
|
||||
return nil, errcode.ErrInvalidArgument
|
||||
}
|
||||
|
||||
// logic code
|
||||
// 简单的AES加密实现
|
||||
key := []byte(in.Key)
|
||||
if len(key) != 32 {
|
||||
// 如果密钥长度不是32字节,进行填充或截断
|
||||
if len(key) < 32 {
|
||||
for len(key) < 32 {
|
||||
key = append(key, 0)
|
||||
}
|
||||
} else {
|
||||
key = key[:32]
|
||||
}
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
encryptedData, err := encryptPrivateData(in.Data)
|
||||
if err != nil {
|
||||
printer.Error("Encrypt data error: %v", err)
|
||||
return nil, errcode.ErrInternal
|
||||
}
|
||||
|
||||
// 使用GCM模式进行加密
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, errcode.ErrInternal
|
||||
}
|
||||
|
||||
// 生成随机nonce
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return nil, errcode.ErrInternal
|
||||
}
|
||||
|
||||
// 加密数据
|
||||
ciphertext := gcm.Seal(nonce, nonce, []byte(in.Data), nil)
|
||||
|
||||
// 返回base64编码的加密数据
|
||||
encryptedData := base64.StdEncoding.EncodeToString(ciphertext)
|
||||
|
||||
return &pb.StatusReply{
|
||||
Details: encryptedData,
|
||||
Timeseq: time.Now().UnixMilli(),
|
||||
|
||||
Reference in New Issue
Block a user