/
padding.go
37 lines (31 loc) · 912 Bytes
/
padding.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
package xaes
import (
"bytes"
"crypto/aes"
)
type Padinger interface {
Pading([]byte) []byte
UnPading([]byte) []byte
}
type PKCS7Pading struct{}
func (p *PKCS7Pading) Pading(plaintext []byte) []byte {
blockSize := aes.BlockSize
padding := blockSize - len(plaintext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(plaintext, padtext...)
}
func (p *PKCS7Pading) UnPading(plaintext []byte) []byte {
length := len(plaintext)
unpadding := int(plaintext[length-1])
return plaintext[:(length - unpadding)]
}
type ZeroPading struct{}
func (p *ZeroPading) Pading(plaintext []byte) []byte {
blockSize := aes.BlockSize
padding := blockSize - len(plaintext)%blockSize
padtext := bytes.Repeat([]byte{byte(0)}, padding)
return append(plaintext, padtext...)
}
func (p *ZeroPading) UnPading(plaintext []byte) []byte {
return bytes.TrimRight(plaintext, string([]byte{0}))
}