crypto.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package utilx
  2. import (
  3. "crypto/aes"
  4. "crypto/md5"
  5. "encoding/hex"
  6. )
  7. func Md5(input []byte) string {
  8. hash := md5.New()
  9. hash.Write(input)
  10. return hex.EncodeToString(hash.Sum(nil))
  11. }
  12. //AesEncryptECB AES-EBC
  13. func AesEncryptECB(origData []byte, key []byte) (encrypted []byte) {
  14. cipher, _ := aes.NewCipher(generateKey(key))
  15. length := (len(origData) + aes.BlockSize) / aes.BlockSize
  16. plain := make([]byte, length*aes.BlockSize)
  17. copy(plain, origData)
  18. pad := byte(len(plain) - len(origData))
  19. for i := len(origData); i < len(plain); i++ {
  20. plain[i] = pad
  21. }
  22. encrypted = make([]byte, len(plain))
  23. // 分组分块加密
  24. for bs, be := 0, cipher.BlockSize(); bs <= len(origData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
  25. cipher.Encrypt(encrypted[bs:be], plain[bs:be])
  26. }
  27. return encrypted
  28. }
  29. //AesDecryptECB AES-EBC
  30. func AesDecryptECB(encrypted []byte, key []byte) (decrypted []byte) {
  31. cipher, _ := aes.NewCipher(generateKey(key))
  32. decrypted = make([]byte, len(encrypted))
  33. //
  34. for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
  35. cipher.Decrypt(decrypted[bs:be], encrypted[bs:be])
  36. }
  37. trim := 0
  38. if len(decrypted) > 0 {
  39. trim = len(decrypted) - int(decrypted[len(decrypted)-1])
  40. }
  41. return decrypted[:trim]
  42. }
  43. func generateKey(key []byte) (genKey []byte) {
  44. genKey = make([]byte, 16)
  45. copy(genKey, key)
  46. for i := 16; i < len(key); {
  47. for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
  48. genKey[j] ^= key[i]
  49. }
  50. }
  51. return genKey
  52. }