aes_encrypt.go 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * Copyright (c) 2022 Yansen Zhang
  3. * wxcomponent is licensed under Mulan PSL v2.
  4. * You can use this software according to the terms and conditions of the Mulan PSL v2.
  5. * You may obtain a copy of Mulan PSL v2 at:
  6. * http://license.coscl.org.cn/MulanPSL2
  7. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
  8. * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
  9. * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
  10. * See the Mulan PSL v2 for more details.
  11. **/
  12. package encrypt
  13. import (
  14. "bytes"
  15. "crypto/aes"
  16. "crypto/cipher"
  17. "errors"
  18. )
  19. // AESEncode 使用 AES CBC 模式加密数据
  20. // data 为待加密数据
  21. func AESEncode(data, key []byte) ([]byte, error) {
  22. if nil == data || len(data) == 0 {
  23. return nil, errors.New("待加密 消息 为空")
  24. }
  25. if nil == key || len(key) == 0 {
  26. return nil, errors.New("加密 AESKey 为空")
  27. }
  28. block, e2 := aes.NewCipher(key)
  29. if e2 != nil {
  30. return nil, e2
  31. }
  32. blockSize := block.BlockSize()
  33. cipherData := pkcs7(data, blockSize)
  34. dist := make([]byte, len(cipherData))
  35. // CBC
  36. mode := cipher.NewCBCEncrypter(block, key[:blockSize])
  37. mode.CryptBlocks(dist, cipherData)
  38. // 如果需要拿到字符串, 请使用
  39. // fmt.Sprintf("%x", xxx)
  40. // 或者使用 base64 转码
  41. return dist, nil
  42. }
  43. // AESDecode 是 AESEncode 的反操作, 用来解密数据
  44. // data 为待解密数据
  45. func AESDecode(data, key []byte) ([]byte, error) {
  46. if nil == data || len(data) == 0 {
  47. return nil, errors.New("待解密 消息 为空")
  48. }
  49. if nil == key || len(key) == 0 {
  50. return nil, errors.New("解密 AESKey 为空")
  51. }
  52. block, err := aes.NewCipher(key)
  53. if err != nil {
  54. return nil, err
  55. }
  56. blockSize := block.BlockSize()
  57. dist := make([]byte, len(data))
  58. mode := cipher.NewCBCDecrypter(block, key[:blockSize])
  59. mode.CryptBlocks(dist, data)
  60. // 如果需要拿到字符串, 请使用
  61. // fmt.Sprintf("%s", xxx)
  62. return unpkcs7(dist), nil
  63. }
  64. // pkcs7 填充
  65. func pkcs7(data []byte, blockSize int) []byte {
  66. paddingBlock := blockSize - len(data)%blockSize
  67. padding := bytes.Repeat([]byte{byte(paddingBlock)}, paddingBlock)
  68. return append(data, padding...)
  69. }
  70. // unpkcs7 取消 pkcs7 填充
  71. func unpkcs7(data []byte) []byte {
  72. length := len(data)
  73. unpadding := int(data[length-1])
  74. return data[:(length - unpadding)]
  75. }