crypto.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/cipher"
  5. "encoding/base64"
  6. "encoding/hex"
  7. "strings"
  8. )
  9. const (
  10. KeyLength = 8
  11. )
  12. func encrypt(block cipher.Block, src, key, iv []byte) []byte {
  13. blockSize := block.BlockSize()
  14. src = pkcs5Padding(src, blockSize)
  15. mode := cipher.NewCBCEncrypter(block, genBytes(iv, blockSize))
  16. encrypted := make([]byte, len(src))
  17. mode.CryptBlocks(encrypted, src)
  18. return encrypted
  19. }
  20. func decrypt(block cipher.Block, encrypted, key, iv []byte) []byte {
  21. mode := cipher.NewCBCDecrypter(block, genBytes(iv, block.BlockSize()))
  22. src := make([]byte, len(encrypted))
  23. mode.CryptBlocks(src, encrypted)
  24. return pkcs5UnPadding(src)
  25. }
  26. func pkcs5Padding(data []byte, blockSize int) []byte {
  27. padding := blockSize - len(data)%blockSize
  28. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  29. return append(data, padtext...)
  30. }
  31. func pkcs5UnPadding(data []byte) []byte {
  32. length := len(data)
  33. // 去掉最后一个字节 unpadding 次
  34. unpadding := int(data[length-1])
  35. return data[:(length - unpadding)]
  36. }
  37. func genBytes(originalBytes []byte, length int) []byte {
  38. tmp := make([]byte, length)
  39. if len(originalBytes) < length {
  40. for i := 0; i < length; i++ {
  41. tmp[i] = originalBytes[i%len(originalBytes)]
  42. }
  43. } else {
  44. for i := 0; i < length; i++ {
  45. tmp[i] = originalBytes[i]
  46. }
  47. }
  48. return tmp
  49. }
  50. func bytes2String(data []byte, base64Encoding bool) string {
  51. if base64Encoding {
  52. return base64.StdEncoding.EncodeToString(data)
  53. } else {
  54. return strings.ToUpper(hex.EncodeToString(data))
  55. }
  56. }
  57. func string2Bytes(data string, base64Encoding bool) ([]byte, error) {
  58. var tmp []byte
  59. var err error
  60. if base64Encoding {
  61. tmp, err = base64.StdEncoding.DecodeString(data)
  62. } else {
  63. tmp, err = hex.DecodeString(data)
  64. }
  65. return tmp, err
  66. }