|
@@ -0,0 +1,49 @@
|
|
|
+package spiderutil
|
|
|
+
|
|
|
+import (
|
|
|
+ "crypto/aes"
|
|
|
+)
|
|
|
+
|
|
|
+//aes ecb加密
|
|
|
+func AesECBEncrypt(data, key []byte) []byte {
|
|
|
+ cipher, _ := aes.NewCipher(generateKey([]byte(key)))
|
|
|
+ length := (len(data) + aes.BlockSize) / aes.BlockSize
|
|
|
+ plain := make([]byte, length*aes.BlockSize)
|
|
|
+ copy(plain, data)
|
|
|
+ pad := byte(len(plain) - len(data))
|
|
|
+ for i := len(data); i < len(plain); i++ {
|
|
|
+ plain[i] = pad
|
|
|
+ }
|
|
|
+ encrypted := make([]byte, len(plain))
|
|
|
+ // 分组分块加密
|
|
|
+ for bs, be := 0, cipher.BlockSize(); bs <= len(data); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
|
|
|
+ cipher.Encrypt(encrypted[bs:be], plain[bs:be])
|
|
|
+ }
|
|
|
+ return encrypted
|
|
|
+}
|
|
|
+
|
|
|
+//aes ecb解密
|
|
|
+func AesECBDecrypter(data, key []byte) []byte {
|
|
|
+ cipher, _ := aes.NewCipher(generateKey(key))
|
|
|
+ decrypted := make([]byte, len(data))
|
|
|
+ for bs, be := 0, cipher.BlockSize(); bs < len(data); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
|
|
|
+ cipher.Decrypt(decrypted[bs:be], data[bs:be])
|
|
|
+ }
|
|
|
+ trim := 0
|
|
|
+ if len(decrypted) > 0 {
|
|
|
+ trim = len(decrypted) - int(decrypted[len(decrypted)-1])
|
|
|
+ }
|
|
|
+
|
|
|
+ return decrypted[:trim]
|
|
|
+}
|
|
|
+
|
|
|
+func generateKey(key []byte) (genKey []byte) {
|
|
|
+ genKey = make([]byte, 16)
|
|
|
+ copy(genKey, key)
|
|
|
+ for i := 16; i < len(key); {
|
|
|
+ for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
|
|
|
+ genKey[j] ^= key[i]
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return genKey
|
|
|
+}
|