2017-05-08 2182
简介:
package tools
import (
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/pem"
"errors"
)
co...
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 }
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
开发者社区 >
安全
>
文章