msg_encrypt.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package encrypt
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "encoding/base64"
  7. "errors"
  8. )
  9. // MsgEncode 使用 AES CBC 模式加密数据
  10. // data 为待加密数据
  11. func MsgEncode(data []byte, encodingAESKey, iv string) ([]byte, error) {
  12. if encodingAESKey == "" {
  13. return nil, errors.New("加密 EncodingAESKey 为空")
  14. }
  15. if iv == "" {
  16. return nil, errors.New("加密 IV 为空")
  17. }
  18. if nil == data || len(data) == 0 {
  19. return nil, errors.New("待加密 消息 为空")
  20. }
  21. aesKey, e1 := base64.StdEncoding.DecodeString(encodingAESKey + "=")
  22. if e1 != nil {
  23. return nil, e1
  24. }
  25. block, e2 := aes.NewCipher(aesKey)
  26. if e2 != nil {
  27. return nil, e2
  28. }
  29. blockSize := block.BlockSize()
  30. dist := pkcs7(data, blockSize)
  31. // CBC
  32. mode := cipher.NewCBCEncrypter(block, []byte(iv))
  33. mode.CryptBlocks(dist, data)
  34. // 如果需要拿到字符串, 请使用
  35. // fmt.Sprintf("%x", xxx)
  36. // 或者使用 base64 转码
  37. return dist, nil
  38. }
  39. // MsgDecode 是 MsgEncode 的反操作, 用来解密数据
  40. // data 为待解密数据
  41. func MsgDecode(data []byte, encodingAESKey, iv string) ([]byte, error) {
  42. if encodingAESKey == "" {
  43. return nil, errors.New("解密 EncodingAESKey 为空")
  44. }
  45. if iv == "" {
  46. return nil, errors.New("解密 IV 为空")
  47. }
  48. if nil == data || len(data) == 0 {
  49. return nil, errors.New("待解密 消息 为空")
  50. }
  51. aesKey, e1 := base64.StdEncoding.DecodeString(encodingAESKey + "=")
  52. if e1 != nil {
  53. return nil, e1
  54. }
  55. block, err := aes.NewCipher(aesKey)
  56. if err != nil {
  57. return nil, err
  58. }
  59. dist := make([]byte, len(data))
  60. mode := cipher.NewCBCDecrypter(block, []byte(iv))
  61. mode.CryptBlocks(dist, data)
  62. // 如果需要拿到字符串, 请使用
  63. // fmt.Sprintf("%s", xxx)
  64. return unpkcs7(dist), nil
  65. }
  66. // pkcs7 填充
  67. func pkcs7(data []byte, blockSize int) []byte {
  68. paddingBlock := blockSize - len(data)%blockSize
  69. if paddingBlock == 0 {
  70. paddingBlock = blockSize
  71. }
  72. padding := bytes.Repeat([]byte{byte(paddingBlock)}, paddingBlock)
  73. return append(data, padding...)
  74. }
  75. // unpkcs7 取消 pkcs7 填充
  76. func unpkcs7(data []byte) []byte {
  77. length := len(data)
  78. unpadding := int(data[length-1])
  79. return data[:(length - unpadding)]
  80. }