zhangzengfei
2021-11-08 cd769ea498c08d5742b444fe6451b4c22899a317
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package licence
 
import (
    "bytes"
    "crypto/aes"
    "crypto/cipher"
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "strings"
)
 
var ivspec = []byte("0000000000000000")
 
func GetMd5String(s string, upper bool, half bool) string {
    h := md5.New()
    h.Write([]byte(s))
    result := hex.EncodeToString(h.Sum(nil))
    if upper == true {
        result = strings.ToUpper(result)
    }
    if half == true {
        result = result[8:24]
    }
    return result
}
 
func AESEncodeStr(src []byte, key string) string {
    block, err := aes.NewCipher([]byte(key))
    if err != nil {
        fmt.Println("key error1", err)
    }
    if src == nil {
        fmt.Println("plain content empty")
    }
    ecb := cipher.NewCBCEncrypter(block, ivspec)
    content := PKCS5Padding(src, block.BlockSize())
    crypted := make([]byte, len(content))
    ecb.CryptBlocks(crypted, content)
 
    return hex.EncodeToString(crypted)
}
 
func AESDecodeStr(crypt, key string) []byte {
    crypted, err := hex.DecodeString(strings.ToLower(crypt))
    if err != nil || len(crypted) == 0 {
        return nil
    }
 
    block, err := aes.NewCipher([]byte(key))
    if err != nil {
        return nil
    }
 
    decrypted := make([]byte, len(crypted))
    bs := block.BlockSize()
    if len(crypted)%bs != 0 {
        return nil
    }
 
    ecb := cipher.NewCBCDecrypter(block, ivspec)
    ecb.CryptBlocks(decrypted, crypted)
 
    return PKCS5Trimming(decrypted)
}
 
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}
 
func PKCS5Trimming(encrypt []byte) []byte {
    length := len(encrypt)
    number := int(encrypt[length-1])
    if number >= length {
        return nil
    }
    return encrypt[:length-number]
}