67 lines
1.6 KiB
Go
67 lines
1.6 KiB
Go
|
|
package xcrypto
|
||
|
|
|
||
|
|
import (
|
||
|
|
"crypto/aes"
|
||
|
|
"encoding/base64"
|
||
|
|
"errors"
|
||
|
|
)
|
||
|
|
|
||
|
|
// key字节长度16
|
||
|
|
type Aes struct {
|
||
|
|
key []byte
|
||
|
|
}
|
||
|
|
|
||
|
|
// NewAes
|
||
|
|
func NewAes(key []byte) *Aes {
|
||
|
|
return &Aes{key: generateKey(key)}
|
||
|
|
}
|
||
|
|
|
||
|
|
func (a Aes) EncryptECB(src string) string {
|
||
|
|
origData := []byte(src)
|
||
|
|
cipher, _ := aes.NewCipher(a.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 base64.StdEncoding.EncodeToString(encrypted)
|
||
|
|
}
|
||
|
|
func (a Aes) DecryptECB(src string) (string, error) {
|
||
|
|
encrypted, err := base64.StdEncoding.DecodeString(src)
|
||
|
|
if err != nil {
|
||
|
|
return "", err
|
||
|
|
}
|
||
|
|
cipher, _ := aes.NewCipher(a.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])
|
||
|
|
}
|
||
|
|
if trim < 0 {
|
||
|
|
return "", errors.New("decrypt error")
|
||
|
|
}
|
||
|
|
return string(decrypted[:trim]), nil
|
||
|
|
}
|
||
|
|
|
||
|
|
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
|
||
|
|
}
|