em-aes.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package util
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. )
  7. // 全零填充
  8. func zero_padding(text []byte, block_size int) []byte {
  9. // 计算最后一个区块的长度
  10. last_block := len(text) % block_size
  11. // 计算填充长度
  12. padding_len := block_size - last_block
  13. // 全零填充
  14. padding := bytes.Repeat([]byte{0}, padding_len)
  15. result := append(text, padding...)
  16. return result
  17. }
  18. // 去除填充
  19. func un_padding(encode_text []byte) []byte {
  20. // 去除尾部的0
  21. un_pad := bytes.TrimRightFunc(encode_text, func(r rune)bool{
  22. return r == rune(0)
  23. })
  24. return un_pad
  25. }
  26. // AES加密
  27. func AES_encrypt(text, key []byte)([]byte, error) {
  28. // 创建密码, 根据密码加密
  29. block, err := aes.NewCipher(key)
  30. if err != nil {
  31. return nil, err
  32. }
  33. // 定义大小 (16byte=128bit)
  34. block_size := block.BlockSize()
  35. // 定义偏移量
  36. iv := key[:block_size]
  37. // 填充
  38. text_padded := zero_padding(text, block_size)
  39. // 创建加密算法
  40. block_mode := cipher.NewCBCEncrypter(block, iv)
  41. // 创建空间
  42. encrypt := make([]byte, len(text_padded))
  43. // 加密
  44. block_mode.CryptBlocks(encrypt, text_padded)
  45. return encrypt, nil
  46. }
  47. // AES解密
  48. func AES_decrypt(text, key []byte)([]byte, error) {
  49. // 创建密码, 根据密码解密
  50. block, err := aes.NewCipher(key)
  51. if err != nil {
  52. return nil, err
  53. }
  54. // 定义大小 (16byte=128bit)
  55. block_size := block.BlockSize()
  56. // 定义偏移量
  57. iv := key[:block_size]
  58. // 创建加密算法
  59. block_mode := cipher.NewCBCDecrypter(block, iv)
  60. // 创建空间
  61. decrypt := make([]byte, len(text))
  62. // 解密
  63. block_mode.CryptBlocks(decrypt, text)
  64. // 去除填充
  65. result := un_padding(decrypt)
  66. return result, nil
  67. }