aes.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/rand"
  7. "errors"
  8. "io"
  9. )
  10. // GenerateAESKey 生成 AES 密钥
  11. func GenerateAESKey(len int) ([]byte, error) {
  12. key := make([]byte, len)
  13. _, err := io.ReadFull(rand.Reader, key)
  14. if err != nil {
  15. return nil, err
  16. }
  17. return key, nil
  18. }
  19. func pad(buf []byte, blockSize int) []byte {
  20. padding := blockSize - (len(buf) % blockSize)
  21. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  22. return append(buf, padtext...)
  23. }
  24. // EncryptWithAES 使用 AES 加密数据
  25. func EncryptWithAES(key []byte, plaintext []byte) ([]byte, error) {
  26. block, err := aes.NewCipher(key)
  27. if err != nil {
  28. return nil, err
  29. }
  30. plaintext = pad(plaintext, aes.BlockSize)
  31. ciphertext := make([]byte, aes.BlockSize+len(plaintext))
  32. iv := ciphertext[:aes.BlockSize]
  33. if _, err = io.ReadFull(rand.Reader, iv); err != nil {
  34. return nil, err
  35. }
  36. stream := cipher.NewCFBEncrypter(block, iv)
  37. stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
  38. return ciphertext, nil
  39. }
  40. // DecryptWithAES 使用 AES 解密数据
  41. func DecryptWithAES(key []byte, ciphertext []byte) ([]byte, error) {
  42. block, err := aes.NewCipher(key)
  43. if err != nil {
  44. return nil, err
  45. }
  46. if len(ciphertext) < aes.BlockSize {
  47. return nil, errors.New("ciphertext too short")
  48. }
  49. iv := ciphertext[:aes.BlockSize]
  50. ciphertext = ciphertext[aes.BlockSize:]
  51. stream := cipher.NewCFBDecrypter(block, iv)
  52. stream.XORKeyStream(ciphertext, ciphertext)
  53. return ciphertext, nil
  54. }