forked from whiym/fish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cbc.go
89 lines (72 loc) · 2.13 KB
/
cbc.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
86
87
88
89
package fish
import (
"bytes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"strings"
"golang.org/x/crypto/blowfish"
)
type cbc struct {
iv []byte
decrypter cipher.BlockMode
encrypter cipher.BlockMode
}
func newCBC(blow *blowfish.Cipher) *cbc {
// mircryption uses a zero'd initialization vector
iv := make([]byte, blowfish.BlockSize)
return &cbc{
iv: iv,
decrypter: cipher.NewCBCDecrypter(blow, iv),
encrypter: cipher.NewCBCEncrypter(blow, iv),
}
}
// CBC message prefixes.
const (
CBCPrefixOK = "+OK *"
CBCPrefixMCPS = "mcps *"
)
func (cbc *cbc) encrypt(msg string) (string, error) {
padded := pad([]byte(msg), blowfish.BlockSize)
// mircryption prepends 8 bytes of random data to the message
random := make([]byte, blowfish.BlockSize)
_, err := rand.Read(random)
if err != nil {
return "", err
}
padded = append(random, padded...)
encrypted := make([]byte, len(padded))
cbc.encrypter.CryptBlocks(encrypted, padded)
encoded := make([]byte, base64.StdEncoding.EncodedLen(len(encrypted)))
base64.StdEncoding.Encode(encoded, encrypted)
return CBCPrefixOK + string(encoded), nil
}
func (cbc *cbc) decrypt(msg string) (string, error) {
trimmed, ok := cbc.trim(msg)
if !ok {
return msg, nil
}
decoded := make([]byte, base64.StdEncoding.DecodedLen(len(trimmed)))
_, err := base64.StdEncoding.Decode(decoded, []byte(trimmed))
if err != nil {
return "", err
}
decoded = bytes.TrimRight(decoded, "\x00")
// Calculate the number of padding bytes needed to match the blocksize and apply
padding := (blowfish.BlockSize - (len(decoded) % blowfish.BlockSize)) % blowfish.BlockSize
decoded = append(decoded, make([]byte, padding)...)
decrypted := make([]byte, len(decoded))
cbc.decrypter.CryptBlocks(decrypted, decoded)
decrypted = bytes.TrimRight(decrypted, "\x00")
return string(decrypted[blowfish.BlockSize:]), nil
}
func (cbc *cbc) trim(src string) (string, bool) {
switch {
case strings.HasPrefix(src, CBCPrefixOK):
return strings.TrimPrefix(src, CBCPrefixOK), true
case strings.HasPrefix(src, CBCPrefixMCPS):
return strings.TrimPrefix(src, CBCPrefixMCPS), true
default:
return src, false
}
}