aes.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package service
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "encoding/base64"
  6. "errors"
  7. )
  8. //func pad(src []byte) []byte {
  9. // padding := aes.BlockSize - len(src)%aes.BlockSize
  10. // padText := bytes.Repeat([]byte{byte(padding)}, padding)
  11. // return append(src, padText...)
  12. //}
  13. func unpad(src []byte) ([]byte, error) {
  14. length := len(src)
  15. unpadding := int(src[length-1])
  16. if unpadding > length {
  17. return nil, errors.New("unpad error. This could happen when incorrect encryption key is used")
  18. }
  19. return src[:(length - unpadding)], nil
  20. }
  21. //func (s *Service) encrypt(text string) (string, error) {
  22. // msg := pad([]byte(text))
  23. // cipherText := make([]byte, aes.BlockSize+len(msg))
  24. // iv := cipherText[:aes.BlockSize]
  25. // if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  26. // return "", err
  27. // }
  28. //
  29. // cfb := cipher.NewCFBEncrypter(s.AESBlock, iv)
  30. // cfb.XORKeyStream(cipherText[aes.BlockSize:], []byte(msg))
  31. // finalMsg := base64.URLEncoding.EncodeToString(cipherText)
  32. // return finalMsg, nil
  33. //}
  34. func (s *Service) decrypt(text string) (string, error) {
  35. decodedMsg, err := base64.URLEncoding.DecodeString(text)
  36. if err != nil {
  37. return "", err
  38. }
  39. if (len(decodedMsg) % aes.BlockSize) != 0 {
  40. return "", errors.New("blocksize must be multipe of decoded message length")
  41. }
  42. iv := decodedMsg[:aes.BlockSize]
  43. msg := decodedMsg[aes.BlockSize:]
  44. cfb := cipher.NewCFBDecrypter(s.AESBlock, iv)
  45. cfb.XORKeyStream(msg, msg)
  46. unpadMsg, err := unpad(msg)
  47. if err != nil {
  48. return "", err
  49. }
  50. return string(unpadMsg), nil
  51. }