aes.go 1.8 KB

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