encoding.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package encoding
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/md5"
  7. "crypto/sha1"
  8. "crypto/sha256"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "fmt"
  12. )
  13. func AESEncrypt(originData string, key string) (string, error) {
  14. keyBytes := []byte(key)
  15. block, err := aes.NewCipher(keyBytes)
  16. if err != nil {
  17. return "", err
  18. }
  19. originDataBytes := []byte(originData)
  20. blockSize := block.BlockSize()
  21. originDataBytes = pkcs7Padding(originDataBytes, blockSize)
  22. blockMode := cipher.NewCBCEncrypter(block, keyBytes[:blockSize])
  23. encrypted := make([]byte, len(originDataBytes))
  24. blockMode.CryptBlocks(encrypted, originDataBytes)
  25. return base64.StdEncoding.EncodeToString(encrypted), nil
  26. }
  27. func AESDecrypt(encrypted string, key string) (string, error) {
  28. keyBytes := []byte(key)
  29. block, err := aes.NewCipher(keyBytes)
  30. if err != nil {
  31. return "", err
  32. }
  33. decoded, err := base64.StdEncoding.DecodeString(encrypted)
  34. if err != nil {
  35. return "", err
  36. }
  37. blockSize := block.BlockSize()
  38. blockMode := cipher.NewCBCDecrypter(block, keyBytes[:blockSize])
  39. originData := make([]byte, len(decoded))
  40. blockMode.CryptBlocks(originData, decoded)
  41. originData = pkcs7UnPadding(originData)
  42. return string(originData), nil
  43. }
  44. func MD5(origin string, salt string) string {
  45. if salt != "" {
  46. origin = origin + salt
  47. }
  48. return fmt.Sprintf("%x", md5.New().Sum([]byte(origin)))
  49. }
  50. func SHA256(origin string, salt string) string {
  51. if salt != "" {
  52. origin = origin + salt
  53. }
  54. return fmt.Sprintf("%x", sha256.Sum256([]byte(origin)))
  55. }
  56. func SHA1(origin string, salt string) string {
  57. if salt != "" {
  58. origin = origin + salt
  59. }
  60. o := sha1.New()
  61. o.Write([]byte(origin))
  62. return hex.EncodeToString(o.Sum(nil))
  63. }
  64. func Base64Encode(content []byte) string {
  65. return base64.StdEncoding.EncodeToString(content)
  66. }
  67. func Base64Decode(content string) ([]byte, error) {
  68. return base64.StdEncoding.DecodeString(content)
  69. }
  70. func pkcs7Padding(ciphertext []byte, blockSize int) []byte {
  71. padding := blockSize - len(ciphertext)%blockSize
  72. padText := bytes.Repeat([]byte{byte(padding)}, padding)
  73. return append(ciphertext, padText...)
  74. }
  75. func pkcs7UnPadding(originData []byte) []byte {
  76. length := len(originData)
  77. unPadding := int(originData[length-1])
  78. return originData[:(length - unPadding)]
  79. }