-
Notifications
You must be signed in to change notification settings - Fork 17
/
encrypt.go
64 lines (55 loc) · 1.52 KB
/
encrypt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//ActivedRouter
//Author:usher.yue
//Amail:usher.yue@gmail.com
//TencentQQ:4223665
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
}