crypto.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/md5"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "net/url"
  10. )
  11. func PKCS7UnPadding(origData []byte) []byte {
  12. length := len(origData)
  13. unpadding := int(origData[length-1])
  14. return origData[:(length - unpadding)]
  15. }
  16. func AesCBCDecrypt(encryptData, key, iv []byte) ([]byte, error) {
  17. block, err := aes.NewCipher(key)
  18. if err != nil {
  19. panic(err)
  20. }
  21. blockSize := block.BlockSize()
  22. if len(encryptData) < blockSize {
  23. panic("ciphertext too short")
  24. }
  25. if len(encryptData)%blockSize != 0 {
  26. panic("ciphertext is not a multiple of the block size")
  27. }
  28. mode := cipher.NewCBCDecrypter(block, iv)
  29. decryptedData := make([]byte, len(encryptData))
  30. mode.CryptBlocks(decryptedData, encryptData)
  31. decryptedData = PKCS7UnPadding(decryptedData)
  32. return decryptedData, nil
  33. }
  34. func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
  35. padding := blockSize - len(ciphertext)%blockSize
  36. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  37. return append(ciphertext, padtext...)
  38. }
  39. //AES加密
  40. func AesEncrypt(origData, key []byte) ([]byte, error) {
  41. block, err := aes.NewCipher(key)
  42. if err != nil {
  43. return nil, err
  44. }
  45. blockSize := block.BlockSize()
  46. origData = PKCS7Padding(origData, blockSize)
  47. blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
  48. crypted := make([]byte, len(origData))
  49. blockMode.CryptBlocks(crypted, origData)
  50. return crypted, nil
  51. }
  52. //AES解密
  53. func AesDecrypt(crypted, key []byte) ([]byte, error) {
  54. block, err := aes.NewCipher(key)
  55. if err != nil {
  56. return nil, err
  57. }
  58. blockSize := block.BlockSize()
  59. blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
  60. origData := make([]byte, len(crypted))
  61. blockMode.CryptBlocks(origData, crypted)
  62. origData = PKCS7UnPadding(origData)
  63. return origData, nil
  64. }
  65. func Md5(str string) string {
  66. h := md5.New()
  67. h.Write([]byte(str))
  68. return hex.EncodeToString(h.Sum(nil))
  69. }
  70. func Base64Encode(str string) string {
  71. return base64.StdEncoding.EncodeToString([]byte(str))
  72. }
  73. func Base64Decode(str string) string {
  74. decodestr, _ := base64.StdEncoding.DecodeString(str)
  75. return string(decodestr)
  76. }
  77. func UrlEncode(str string) (string, error) {
  78. u, err := url.Parse(str)
  79. if err != nil {
  80. return "", err
  81. }
  82. return u.String(), nil
  83. }