aes.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package crypto
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "errors"
  7. )
  8. // AES aes
  9. type AES struct {
  10. key []byte
  11. iv []byte
  12. }
  13. var (
  14. defaultAes AES
  15. )
  16. // NewAES new
  17. func NewAES(key, iv string) *AES {
  18. return &AES{
  19. key: []byte(key),
  20. iv: []byte(iv),
  21. }
  22. }
  23. // SetKeyIV set key & iv
  24. func (c *AES) SetKeyIV(key, iv string) {
  25. c.key = []byte(key)
  26. c.iv = []byte(iv)
  27. }
  28. // Encrypt encrypt data
  29. func (c *AES) Encrypt(bs []byte) (crypted []byte, err error) {
  30. block, err := aes.NewCipher(c.key)
  31. if err != nil {
  32. return nil, err
  33. }
  34. blockSize := block.BlockSize()
  35. bs = pkcs7Padding(bs, blockSize)
  36. blockMode := cipher.NewCBCEncrypter(block, c.iv[:blockSize])
  37. crypted = make([]byte, len(bs))
  38. blockMode.CryptBlocks(crypted, bs)
  39. return
  40. }
  41. // Decrypt decrypt data
  42. func (c *AES) Decrypt(bs []byte) (ds []byte, err error) {
  43. block, err := aes.NewCipher(c.key)
  44. if err != nil {
  45. return nil, err
  46. }
  47. n := len(bs)
  48. blockSize := block.BlockSize()
  49. if n%blockSize != 0 {
  50. return nil, errors.New(`crypto/cipher: input not full blocks`)
  51. }
  52. blockMode := cipher.NewCBCDecrypter(block, c.iv[:blockSize])
  53. ds = make([]byte, n)
  54. blockMode.CryptBlocks(ds, bs)
  55. ds = pkcs7UnPadding(ds)
  56. return
  57. }
  58. func pkcs7Padding(cipherText []byte, blockSize int) []byte {
  59. padding := blockSize - len(cipherText)%blockSize
  60. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  61. return append(cipherText, padtext...)
  62. }
  63. func pkcs7UnPadding(data []byte) []byte {
  64. length := len(data)
  65. unpadding := int(data[length-1])
  66. if unpadding >= length {
  67. return []byte(``)
  68. }
  69. return data[:(length - unpadding)]
  70. }
  71. // SetAESDefaultKeyIV set default key & iv
  72. func SetAESDefaultKeyIV(key, iv string) {
  73. defaultAes = AES{
  74. key: []byte(key),
  75. iv: []byte(iv),
  76. }
  77. }
  78. // AesEncrypt default key & iv encrypt
  79. func AesEncrypt(bs []byte) ([]byte, error) {
  80. return defaultAes.Encrypt(bs)
  81. }
  82. // AesDecrypt default key & iv decrypt
  83. func AesDecrypt(bs []byte) ([]byte, error) {
  84. return defaultAes.Decrypt(bs)
  85. }