· 7 years ago · Nov 10, 2018, 04:08 AM
1type Encoder struct {
2 Block cipher.Block
3 SecretKey string
4}
5
6func (e *Encoder) Encode(message string) (string, error) {
7 plainText := []byte(message)
8 cipherText := make([]byte, aes.BlockSize+len(plainText))
9 iv := cipherText[:aes.BlockSize]
10 if _, err := io.ReadFull(rand.Reader, iv); err != nil {
11 return "", nil
12 }
13 stream := cipher.NewCFBEncrypter(e.Block, iv)
14 stream.XORKeyStream(cipherText[aes.BlockSize:], plainText)
15 encodedMessage := base64.URLEncoding.EncodeToString(cipherText)
16 return encodedMessage, nil
17}
18
19func (e *Encoder) Decode(message string) (string, error) {
20 cipherText, err := base64.URLEncoding.DecodeString(message)
21 if err != nil {
22 return "", nil
23 }
24 if len(cipherText) < aes.BlockSize {
25 return "", errors.New("block size is too short")
26 }
27 iv := cipherText[:aes.BlockSize]
28 cipherText = cipherText[aes.BlockSize:]
29 stream := cipher.NewCFBDecrypter(e.Block, iv)
30 stream.XORKeyStream(cipherText, cipherText)
31 return string(cipherText), nil
32}
33
34func NewEncoder(SecretKey string) (*Encoder, error) {
35 block, err := aes.NewCipher([]byte(SecretKey))
36 if err != nil {
37 return nil, err
38 }
39 return &Encoder{
40 SecretKey: SecretKey,
41 Block: block,
42 }, nil
43}