-
Notifications
You must be signed in to change notification settings - Fork 0
/
encrypt.go
56 lines (49 loc) · 1.07 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
package main
import (
"bytes"
"errors"
)
const (
NOPADDING = iota
PKCS5PADDING
)
//PKCS5补位
func PKCS5Padding(text []byte, blockSize int) []byte {
padding := blockSize - len(text)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(text, padtext...)
}
//去除PKCS5补位
func PKCS5Unpadding(text []byte) []byte {
length := len(text)
padtext := int(text[length-1])
return text[:(length - padtext)]
}
//补位方法
func Padding(text []byte, padding int) ([]byte, error) {
switch padding {
case NOPADDING:
if len(text)%8 != 0 {
return nil, errors.New("text length invalid")
}
case PKCS5PADDING:
return PKCS5Padding(text, 8), nil
default:
return nil, errors.New("padding type error")
}
return text, nil
}
//去除补位方法
func UnPadding(text []byte, padding int) ([]byte, error) {
switch padding {
case NOPADDING:
if len(text)%8 != 0 {
return nil, errors.New("text length invalid")
}
case PKCS5PADDING:
return PKCS5Unpadding(text), nil
default:
return nil, errors.New("padding type error.")
}
return text, nil
}