工作,学习,生活,这里将会有一些记录. 备用域名:http://meisw.wdlinux.cn 注册 | 登陆

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, error) {
block, _ := 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
}
 
--------
https://blog.csdn.net/yue7603835/article/details/73433617

« 上一篇 | 下一篇 »

Trackbacks

点击获得Trackback地址,Encode: UTF-8

发表评论

评论内容 (必填):