golang官方不支持ecb模式,因业务需要自编一段ecb
复制代码
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
67package myAes import ( "bytes" "crypto/aes" "crypto/md5" "encoding/hex" "fmt" "strings" ) func padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } func secretKeySpec(skey []byte) (key string) { //key转换 has := md5.Sum(skey) sky := fmt.Sprintf("%X", has) return strings.ToUpper(sky) } func AesEncrypt(origData []byte, skey []byte) (string, error) { // aes 加密 skeySpec := secretKeySpec(skey) /**AES 加密**/ //key只能是 16 24 32长度 block, err := aes.NewCipher([]byte(skeySpec)) if err != nil { return "", err } //padding origData = padding(origData, block.BlockSize()) //存储每次加密的数据 //分组分块加密 buffer := bytes.NewBufferString("") tmpData := make([]byte, block.BlockSize()) //存储每次加密的数据 for index := 0; index < len(origData); index += block.BlockSize() { block.Encrypt(tmpData, origData[index:index+block.BlockSize()]) buffer.Write(tmpData) } return strings.ToUpper(hex.EncodeToString(buffer.Bytes())), nil } func AesDecrypt(text string, skey []byte) (string, error) { // aes解密 skeySpec := secretKeySpec(skey) block, err := aes.NewCipher([]byte(skeySpec)) if err != nil { return "", err } src, _ := hex.DecodeString(text) /**AES 解密**/ buffer := bytes.NewBufferString("") tmpData := make([]byte, block.BlockSize()) for index := 0; index < len(src); index += block.BlockSize() { block.Decrypt(tmpData, src[index:index+block.BlockSize()]) buffer.Write(tmpData) } // 去掉末尾非打印控制字符 var deByte []byte for i := len(buffer.Bytes()); i > 0; i-- { if buffer.Bytes()[i-1] >= 32 { deByte = buffer.Bytes()[:i] break } } return strings.TrimSpace(string(deByte)), nil }
最后
以上就是不安台灯最近收集整理的关于golang aes加密ecb模式的全部内容,更多相关golang内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复