Skip to content

Instantly share code, notes, and snippets.

@hteen
Created May 22, 2020 07:44
Show Gist options
  • Select an option

  • Save hteen/2625aad7dc871c592a3539d491b289ec to your computer and use it in GitHub Desktop.

Select an option

Save hteen/2625aad7dc871c592a3539d491b289ec to your computer and use it in GitHub Desktop.
package main
import (
"crypto/aes"
"encoding/hex"
_ "github.com/jinzhu/gorm/dialects/mysql"
"log"
"time"
)
func main() {
// 加密的密钥
key := []byte("key")
// 加密
origData := []byte("张三")
encrypted := AesEncryptECB(origData, key)
log.Println("密文(hex):", hex.EncodeToString(encrypted))
// 解密
encrypted, _ = hex.DecodeString("0b5aee2ebd31bb57da7af8a47f1c0f06")
decrypted := AesDecryptECB(encrypted, key)
log.Println("解密结果:", string(decrypted))
}
func AesEncryptECB(origData []byte, key []byte) (encrypted []byte) {
cipher, _ := aes.NewCipher(generateKey(key))
length := (len(origData) + aes.BlockSize) / aes.BlockSize
plain := make([]byte, length*aes.BlockSize)
copy(plain, origData)
pad := byte(len(plain) - len(origData))
for i := len(origData); i < len(plain); i++ {
plain[i] = pad
}
encrypted = make([]byte, len(plain))
for bs, be := 0, cipher.BlockSize(); bs <= len(origData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
cipher.Encrypt(encrypted[bs:be], plain[bs:be])
}
return encrypted
}
func AesDecryptECB(encrypted []byte, key []byte) (decrypted []byte) {
cipher, _ := aes.NewCipher(generateKey(key))
decrypted = make([]byte, len(encrypted))
for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
cipher.Decrypt(decrypted[bs:be], encrypted[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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment