encrypt_aes.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package xorm
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "encoding/base64"
  6. )
  7. const (
  8. tempkey = "1234567890!@#$%^&*()_+-="
  9. )
  10. type AesEncrypt struct {
  11. PubKey string
  12. }
  13. func (this *AesEncrypt) getKey() []byte {
  14. strKey := this.PubKey
  15. keyLen := len(strKey)
  16. if keyLen < 16 {
  17. rs := []rune(tempkey)
  18. strKey = strKey + string(rs[0:16-keyLen])
  19. }
  20. if keyLen > 16 && keyLen < 24 {
  21. rs := []rune(tempkey)
  22. strKey = strKey + string(rs[0:24-keyLen])
  23. }
  24. if keyLen > 24 && keyLen < 32 {
  25. rs := []rune(tempkey)
  26. strKey = strKey + string(rs[0:32-keyLen])
  27. }
  28. arrKey := []byte(strKey)
  29. if keyLen >= 32 {
  30. return arrKey[:32]
  31. }
  32. if keyLen >= 24 {
  33. return arrKey[:24]
  34. }
  35. return arrKey[:16]
  36. }
  37. //加密字符串
  38. func (this *AesEncrypt) Encrypt(strMesg string) ([]byte, error) {
  39. key := this.getKey()
  40. var iv = []byte(key)[:aes.BlockSize]
  41. encrypted := make([]byte, len(strMesg))
  42. aesBlockEncrypter, err := aes.NewCipher(key)
  43. if err != nil {
  44. return nil, err
  45. }
  46. aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, iv)
  47. aesEncrypter.XORKeyStream(encrypted, []byte(strMesg))
  48. return encrypted, nil
  49. }
  50. //解密字符串
  51. func (this *AesEncrypt) Decrypt(src []byte) (decrypted []byte, err error) {
  52. defer func() {
  53. if e := recover(); e != nil {
  54. err = e.(error)
  55. }
  56. }()
  57. src, err = base64.StdEncoding.DecodeString(string(src))
  58. if err != nil {
  59. return nil, err
  60. }
  61. key := this.getKey()
  62. var iv = []byte(key)[:aes.BlockSize]
  63. decrypted = make([]byte, len(src))
  64. var aesBlockDecrypter cipher.Block
  65. aesBlockDecrypter, err = aes.NewCipher([]byte(key))
  66. if err != nil {
  67. return nil, err
  68. }
  69. aesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, iv)
  70. aesDecrypter.XORKeyStream(decrypted, src)
  71. return decrypted, nil
  72. }