golang实现md5、RSA、base64 加密解密

前端之家收集整理的这篇文章主要介绍了golang实现md5、RSA、base64 加密解密前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package tools

import (
	"crypto/md5"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/hex"
	"encoding/pem"
	"errors"
)

const (
	base64Table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
)

var coder = base64.NewEncoding(base64Table)

func Base64Encode(src []byte) []byte {
	return []byte(coder.EncodeToString(src))
}

func Base64Decode(src []byte) ([]byte,error) {
	return coder.DecodeString(string(src))
}

func RSAEncrypt(origData []byte,publicKey string) ([]byte,error) {
	block,_ := pem.Decode([]byte(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 string) ([]byte,_ := pem.Decode([]byte(privateKey))
	if block == nil {
		return nil,errors.New("private key error!")
	}
	priv,err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil,err
	}
	return rsa.DecryptPKCS1v15(rand.Reader,priv,ciphertext)
}

func Md5Encrypt(data string) string {
	md5Ctx := md5.New()                            //md5 init
	md5Ctx.Write([]byte(data))                     //md5 updata
	cipherStr := md5Ctx.Sum(nil)                   //md5 final
	encryptedData := hex.EncodeToString(cipherStr) //hex_digest
	return encryptedData
}

猜你在找的Go相关文章