AesCBCWithNoPadding.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package encryption
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "fmt"
  7. )
  8. type aesCBCWithNoPadding struct {
  9. key []byte
  10. iv []byte
  11. }
  12. func NewAesCBCWithNoPadding(key, iv []byte) *aesCBCWithNoPadding {
  13. return &aesCBCWithNoPadding{
  14. key: key,
  15. iv: iv,
  16. }
  17. }
  18. // AES加密函数
  19. func (a *aesCBCWithNoPadding) Encrypt(plaintext []byte) ([]byte, error) {
  20. if len(plaintext)%aes.BlockSize != 0 {
  21. padding := aes.BlockSize - len(plaintext)%aes.BlockSize
  22. plaintext = append(plaintext, bytes.Repeat([]byte{byte(padding)}, padding)...)
  23. }
  24. block, err := aes.NewCipher(a.key)
  25. if err != nil {
  26. return nil, err
  27. }
  28. //if len(plaintext)%aes.BlockSize != 0 {
  29. // return nil, fmt.Errorf("plaintext is not a multiple of the block size")
  30. //}
  31. ciphertext := make([]byte, len(plaintext))
  32. mode := cipher.NewCBCEncrypter(block, a.iv)
  33. mode.CryptBlocks(ciphertext, plaintext)
  34. return ciphertext, nil
  35. }
  36. // AES解密函数
  37. func (a *aesCBCWithNoPadding) Decrypt(ciphertext []byte) ([]byte, error) {
  38. block, err := aes.NewCipher(a.key)
  39. if err != nil {
  40. return nil, err
  41. }
  42. if len(ciphertext)%aes.BlockSize != 0 {
  43. return nil, fmt.Errorf("ciphertext is not a multiple of the block size")
  44. }
  45. plaintext := make([]byte, len(ciphertext))
  46. mode := cipher.NewCBCDecrypter(block, a.iv)
  47. mode.CryptBlocks(plaintext, ciphertext)
  48. return plaintext, nil
  49. }