sample_chain/order/token/handler.go

113 lines
2.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package token
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
pb "schain/proto"
"golang.org/x/net/context"
)
// 用于注册grpc服务
type RequestServer struct {
pb.UnimplementedPingServer
}
var key string = "0123456789abcdef"
func (s *RequestServer) Login(ctx context.Context, in *pb.LoginRequest) (*pb.LoginReply, error) {
//实现aes解密
// 解密字符串
de_name, err := decrypt(in.Username, key)
if err != nil {
panic("Decryption error")
}
de_password, err := decrypt(in.Password, key)
if err != nil {
panic("Decryption error")
}
fmt.Println("Loginrequest: ", de_name)
if de_name == "Wuxinyu" && de_password == "123456" {
tokenString := CreateToken(in.Username)
return &pb.LoginReply{Status: "200", Token: tokenString}, nil
} else {
return &pb.LoginReply{Status: "403", Token: ""}, nil
}
}
// SayHello 生成对 Ping 请求的响应
func (s *RequestServer) SayHello(ctx context.Context, in *pb.PingMessage) (*pb.PingMessage, error) {
//生成响应消息
msg := "bar"
// 从上下文中检查用户认证信息
userName := CheckAuth(ctx)
//将用户名添加到消息中
msg += " " + userName
return &pb.PingMessage{Greeting: msg}, nil
}
func encrypt(plainText string, key string) (string, error) {
keyBytes := []byte(key)
block, err := aes.NewCipher(keyBytes)
if err != nil {
return "", err
}
// 创建一个加密器
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
// 创建一个随机的 nonce长度必须与加密块大小相同
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
// 使用 nonce 加密数据
ciphertext := gcm.Seal(nonce, nonce, []byte(plainText), nil)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
func decrypt(ciphertext string, key string) (string, error) {
decodedCiphertext, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
return "", err
}
block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}
// 创建一个解密器
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
// 从密文中提取 nonce
nonceSize := gcm.NonceSize()
if len(decodedCiphertext) < nonceSize {
return "", fmt.Errorf("ciphertext too short")
}
nonce := decodedCiphertext[:nonceSize]
ciphertextBytes := decodedCiphertext[nonceSize:]
// 解密数据
plaintext, err := gcm.Open(nil, nonce, ciphertextBytes, nil)
if err != nil {
return "", err
}
return string(plaintext), nil
}