golang token的生成和获取


golang 加减密

token的生成和获取

// GetToken 获取token
func GetToken(appId, userId, deviceId int64, expire int64, publicKey string) (string, error) {
	info := TokenInfo{
		AppId:    appId,
		UserId:   userId,
		DeviceId: deviceId,
		Expire:   expire,
	}
	bytes, err := json.Marshal(info)
	if err != nil {
		logger.Sugar.Error(err)
		return "", err
	}

	token, err := RsaEncrypt(bytes, []byte(publicKey))
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(token), nil
}

// DecryptToken 对加密的token进行解码
func DecryptToken(token string, privateKey string) (*TokenInfo, error) {
	bytes, err := base64.StdEncoding.DecodeString(token)
	if err != nil {
		logger.Sugar.Error(err)
		return nil, err
	}
	result, err := RsaDecrypt(bytes, Str2bytes(privateKey))
	if err != nil {
		logger.Sugar.Error(err)
		return nil, err
	}

	var info TokenInfo
	err = jsoniter.Unmarshal(result, &info)
	if err != nil {
		logger.Sugar.Error(err)
		return nil, err
	}
	return &info, nil
}

加减密

// 公钥生成
//openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

// 加密
func RsaEncrypt(origData []byte, publicKey []byte) ([]byte, error) {
	//解密pem格式的公钥
	block, _ := pem.Decode(publicKey)
	if block == nil {
		return nil, errors.New("public key error")
	}
	// 解析公钥
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	// 类型断言
	pub := pubInterface.(*rsa.PublicKey)
	//加密
	return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}

// 解密
func RsaDecrypt(ciphertext []byte, privateKey []byte) ([]byte, error) {
	//解密
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	//解析PKCS1格式的私钥
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	// 解密
	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM