crypt.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package crypt
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/md5"
  7. "encoding/hex"
  8. "errors"
  9. "math/rand"
  10. "time"
  11. )
  12. //en
  13. func AesEncrypt(origData, key []byte) ([]byte, error) {
  14. block, err := aes.NewCipher(key)
  15. if err != nil {
  16. return nil, err
  17. }
  18. blockSize := block.BlockSize()
  19. origData = PKCS5Padding(origData, blockSize)
  20. blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
  21. crypted := make([]byte, len(origData))
  22. blockMode.CryptBlocks(crypted, origData)
  23. return crypted, nil
  24. }
  25. //de
  26. func AesDecrypt(crypted, key []byte) ([]byte, error) {
  27. block, err := aes.NewCipher(key)
  28. if err != nil {
  29. return nil, err
  30. }
  31. blockSize := block.BlockSize()
  32. blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
  33. origData := make([]byte, len(crypted))
  34. blockMode.CryptBlocks(origData, crypted)
  35. err, origData = PKCS5UnPadding(origData)
  36. return origData, err
  37. }
  38. //Completion when the length is insufficient
  39. func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
  40. padding := blockSize - len(ciphertext)%blockSize
  41. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  42. return append(ciphertext, padtext...)
  43. }
  44. //Remove excess
  45. func PKCS5UnPadding(origData []byte) (error, []byte) {
  46. length := len(origData)
  47. unpadding := int(origData[length-1])
  48. if (length - unpadding) < 0 {
  49. return errors.New("len error"), nil
  50. }
  51. return nil, origData[:(length - unpadding)]
  52. }
  53. //Generate 32-bit MD5 strings
  54. func Md5(s string) string {
  55. h := md5.New()
  56. h.Write([]byte(s))
  57. return hex.EncodeToString(h.Sum(nil))
  58. }
  59. //Generating Random Verification Key
  60. func GetRandomString(l int) string {
  61. str := "0123456789abcdefghijklmnopqrstuvwxyz"
  62. bytes := []byte(str)
  63. result := []byte{}
  64. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  65. for i := 0; i < l; i++ {
  66. result = append(result, bytes[r.Intn(len(bytes))])
  67. }
  68. return string(result)
  69. }