aes_128.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package util
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. )
  7. const (
  8. BLOCK_SIZE_16 = 16
  9. )
  10. func NewAesCipher128(key, iv []byte) *AesCipher128 {
  11. if len(key) == 0 || len(key) > BLOCK_SIZE_16 {
  12. return nil
  13. }
  14. if len(iv) < BLOCK_SIZE_16 {
  15. newIv := make([]byte, BLOCK_SIZE_16)
  16. copy(newIv, iv)
  17. iv = newIv
  18. } else {
  19. iv = iv[:BLOCK_SIZE_16]
  20. }
  21. newKey := make([]byte, BLOCK_SIZE_16)
  22. copy(newKey, key)
  23. block, err := aes.NewCipher(newKey)
  24. if err != nil {
  25. return nil
  26. }
  27. return &AesCipher128{
  28. key: newKey,
  29. iv: iv,
  30. block: block,
  31. }
  32. }
  33. type AesCipher128 struct {
  34. key []byte
  35. iv []byte
  36. block cipher.Block
  37. }
  38. func (aesCipher *AesCipher128) BlockSize() int {
  39. return BLOCK_SIZE_16
  40. }
  41. func (aesCipher *AesCipher128) Encrypt(origData []byte) []byte {
  42. encodeBytes := []byte(origData)
  43. blockSize := aesCipher.BlockSize()
  44. encodeBytes = padding(encodeBytes, blockSize)
  45. blockMode := cipher.NewCBCEncrypter(aesCipher.block, aesCipher.iv)
  46. crypted := make([]byte, len(encodeBytes))
  47. blockMode.CryptBlocks(crypted, encodeBytes)
  48. return crypted
  49. }
  50. func (aesCipher *AesCipher128) Decrypt(encrData []byte) []byte {
  51. blockMode := cipher.NewCBCDecrypter(aesCipher.block, aesCipher.iv)
  52. result := make([]byte, len(encrData))
  53. blockMode.CryptBlocks(result, encrData)
  54. return bytes.Trim(result, "\x00")
  55. }
  56. func padding(ciphertext []byte, blockSize int) []byte {
  57. dataSize := ((len(ciphertext)-1)/blockSize + 1) * blockSize
  58. if dataSize == len(ciphertext) {
  59. return ciphertext
  60. }
  61. newData := make([]byte, dataSize)
  62. copy(newData, ciphertext)
  63. return newData
  64. }