encrypt_utils.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package auth
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "encoding/base64"
  7. "fmt"
  8. "io"
  9. )
  10. // GenerateAESKey 生成一个随机的AES密钥
  11. func GenerateAESKey(keySize int) ([]byte, error) {
  12. if keySize != 16 && keySize != 24 && keySize != 32 {
  13. return nil, fmt.Errorf("unsupported key size: %d", keySize)
  14. }
  15. key := make([]byte, keySize)
  16. _, err := io.ReadFull(rand.Reader, key)
  17. if err != nil {
  18. return nil, err
  19. }
  20. return key, nil
  21. }
  22. // AESEncrypt 使用AES CBC模式加密数据
  23. func AESEncrypt(key []byte, plaintext []byte) (string, error) {
  24. block, err := aes.NewCipher(key)
  25. if err != nil {
  26. return "", err
  27. }
  28. // 生成一个随机的初始化向量
  29. ciphertext := make([]byte, aes.BlockSize+len(plaintext))
  30. iv := ciphertext[:aes.BlockSize]
  31. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  32. return "", err
  33. }
  34. mode := cipher.NewCBCEncrypter(block, iv)
  35. mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
  36. // 返回Base64编码后的字符串
  37. return base64.StdEncoding.EncodeToString(ciphertext), nil
  38. }
  39. // AESDecrypt 使用AES CBC模式解密数据
  40. func AESDecrypt(key []byte, ciphertext string) (string, error) {
  41. ciphertextBytes, err := base64.StdEncoding.DecodeString(ciphertext)
  42. if err != nil {
  43. return "", err
  44. }
  45. block, err := aes.NewCipher(key)
  46. if err != nil {
  47. return "", err
  48. }
  49. if len(ciphertextBytes) < aes.BlockSize {
  50. return "", fmt.Errorf("ciphertext too short")
  51. }
  52. iv := ciphertextBytes[:aes.BlockSize]
  53. ciphertextBytes = ciphertextBytes[aes.BlockSize:]
  54. mode := cipher.NewCBCDecrypter(block, iv)
  55. mode.CryptBlocks(ciphertextBytes, ciphertextBytes)
  56. // 去除PKCS#7填充
  57. unPadded := unPad(ciphertextBytes)
  58. return string(unPadded), nil
  59. }
  60. // unPad 去除PKCS#7填充
  61. func unPad(src []byte) []byte {
  62. padding := src[len(src)-1]
  63. return src[:len(src)-int(padding)]
  64. }
  65. func main() {
  66. key := []byte("this is a key123") // 16字节长的密钥
  67. plaintext := []byte("Hello, World!")
  68. // 加密
  69. encrypted, err := AESEncrypt(key, plaintext)
  70. if err != nil {
  71. fmt.Println("Error encrypting:", err)
  72. return
  73. }
  74. fmt.Println("Encrypted:", encrypted)
  75. // 解密
  76. decrypted, err := AESDecrypt(key, encrypted)
  77. if err != nil {
  78. fmt.Println("Error decrypting:", err)
  79. return
  80. }
  81. fmt.Println("Decrypted:", decrypted)
  82. }