fix version 1
This commit is contained in:
@@ -2,18 +2,16 @@ package private
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"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 DecryptData(ctx context.Context, in *pb.DataRequest) (reply *pb.StatusReply, err error) {
|
||||
// parse authorization meta.
|
||||
_, err = service.ParseMetaCtx(ctx, nil)
|
||||
@@ -25,57 +23,16 @@ func DecryptData(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
|
||||
// 解码base64数据
|
||||
ciphertext, err := base64.StdEncoding.DecodeString(in.Data)
|
||||
if err != nil {
|
||||
return nil, errcode.ErrInvalidArgument
|
||||
}
|
||||
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, errcode.ErrInternal
|
||||
}
|
||||
|
||||
// 使用GCM模式进行解密
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, errcode.ErrInternal
|
||||
}
|
||||
|
||||
// 检查数据长度
|
||||
if len(ciphertext) < gcm.NonceSize() {
|
||||
return nil, errcode.ErrInvalidArgument
|
||||
}
|
||||
|
||||
// 分离nonce和密文
|
||||
nonce := ciphertext[:gcm.NonceSize()]
|
||||
ciphertext = ciphertext[gcm.NonceSize():]
|
||||
|
||||
// 解密数据
|
||||
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
|
||||
plainData, err := decryptPrivateData(in.Data)
|
||||
if err != nil {
|
||||
printer.Error("Decrypt data error: %v", err)
|
||||
return nil, errcode.ErrInvalidArgument
|
||||
}
|
||||
|
||||
return &pb.StatusReply{
|
||||
Details: string(plaintext),
|
||||
Details: plainData,
|
||||
Timeseq: time.Now().UnixMilli(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user