-
Notifications
You must be signed in to change notification settings - Fork 2
/
pkcs7.go
85 lines (66 loc) · 1.72 KB
/
pkcs7.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package cryptopals
import "fmt"
func padPKCS7ToBlockSize(data []byte, blockSize int) ([]byte, error) {
length := len(data)
if length%blockSize == 0 {
padding := make([]byte, blockSize)
for i := 0; i < blockSize; i++ {
padding[i] = byte(blockSize)
}
return append(data, padding...), nil
}
diff := blockSize - length%blockSize
padding := make([]byte, diff)
for i := 0; i < diff; i++ {
padding[i] = byte(diff)
}
return append(data, padding...), nil
}
func unpadPKCS7(data []byte) ([]byte, error) {
length := len(data)
// Assume that the last byte was a padding byte
paddingByte := data[length-1]
count := byte(0)
if paddingByte == 0 {
return nil, fmt.Errorf("invalid zero padding byte: %d", paddingByte)
}
if paddingByte > 16 {
return nil, fmt.Errorf("invalid padding byte: %d", paddingByte)
}
for i := length - 1; i >= 0; i-- {
if data[i] == paddingByte {
count++
if count > paddingByte {
return nil, fmt.Errorf("invalid padding byte: %d, count: %d", paddingByte, count)
}
} else {
if count == paddingByte {
return data[:i+1], nil
}
return nil, fmt.Errorf("invalid padding byte: %d, count: %d", paddingByte, count)
}
}
return data, nil
}
func padPKCS7(plainTextStr string, length int) (string, error) {
plainText := []byte(plainTextStr)
if length > 256 {
return "", fmt.Errorf("cannot pad length > 256")
}
if length == 0 {
return plainTextStr, nil
}
textLength := len(plainText)
diff := length - textLength
if diff < 0 {
return "", fmt.Errorf("plainText longer than length")
}
if diff == 0 {
return plainTextStr, nil
}
padding := make([]byte, diff)
for i := 0; i < diff; i++ {
padding[i] = byte(diff)
}
return string(append(plainText, padding...)), nil
}