AesCBCWithPadding.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package encryption
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "fmt"
  7. )
  8. type AesCBCWithPadding struct {
  9. key []byte
  10. iv []byte
  11. }
  12. func NewAesCBCWithPadding(key, iv []byte) *AesCBCWithPadding {
  13. return &AesCBCWithPadding{
  14. key: key,
  15. iv: iv,
  16. }
  17. }
  18. // ZeroPadding 填充(填充0x00到块大小)
  19. func zeroPad(data []byte, blockSize int) []byte {
  20. padding := blockSize - len(data)%blockSize
  21. padText := bytes.Repeat([]byte{0}, padding)
  22. return append(data, padText...)
  23. }
  24. // ZeroUnPadding 去除填充的0x00
  25. func zeroUnPad(data []byte) []byte {
  26. return bytes.TrimRightFunc(data, func(r rune) bool {
  27. return r == rune(0)
  28. })
  29. }
  30. // AES加密函数
  31. func (a *AesCBCWithPadding) Encrypt(plaintext []byte) ([]byte, error) {
  32. block, err := aes.NewCipher(a.key)
  33. if err != nil {
  34. return nil, err
  35. }
  36. //if len(plaintext)%aes.BlockSize != 0 {
  37. // return nil, fmt.Errorf("plaintext is not a multiple of the block size")
  38. //}
  39. plaintext = zeroPad(plaintext, aes.BlockSize)
  40. ciphertext := make([]byte, aes.BlockSize+len(plaintext))
  41. copy(ciphertext[:aes.BlockSize], a.iv)
  42. mode := cipher.NewCBCEncrypter(block, a.iv)
  43. mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
  44. return ciphertext[aes.BlockSize:], nil
  45. }
  46. // AES解密函数
  47. func (a *AesCBCWithPadding) Decrypt(ciphertext []byte) ([]byte, error) {
  48. block, err := aes.NewCipher(a.key)
  49. if err != nil {
  50. return nil, err
  51. }
  52. if len(ciphertext)%aes.BlockSize != 0 {
  53. return nil, fmt.Errorf("ciphertext is not a multiple of the block size")
  54. }
  55. decrypted := make([]byte, len(ciphertext))
  56. copy(decrypted, ciphertext)
  57. mode := cipher.NewCBCDecrypter(block, a.iv)
  58. mode.CryptBlocks(decrypted, ciphertext)
  59. plaintext := zeroUnPad(decrypted)
  60. return plaintext, nil
  61. }