1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import ( "bytes" "crypto/aes" "crypto/cipher" "encoding/base64" "encoding/json" "fmt" "github.com/lxn/walk" . "github.com/lxn/walk/declarative" "strings" )
const ( ivParameter = "abcdefghijklmnop" )
func PswEncrypt(src string, sKey string) string { key := []byte(sKey) iv := []byte(ivParameter) result, err := Aes128Encrypt([]byte(src), key, iv) if err != nil { panic(err) } return base64.RawStdEncoding.EncodeToString(result) }
func PswDecrypt(src string, keyStr string) (string, error) { key := []byte(keyStr) iv := []byte(ivParameter) var result []byte var err error result, err = base64.StdEncoding.DecodeString(src) if err != nil { return "", err } origData, err := Aes128Decrypt(result, key, iv) if err != nil { return "", err } fmt.Println(string(origData)) index := strings.LastIndex(string(origData), "}") return string(origData)[:index + 1], nil } func Aes128Encrypt(origData, key []byte, IV []byte) ([]byte, error) { if key == nil || len(key) != 16 { return nil, nil } if IV != nil && len(IV) != 16 { return nil, nil } block, err := aes.NewCipher(key) if err != nil { return nil, err } blockSize := block.BlockSize() origData = PKCS5Padding(origData, blockSize) blockMode := cipher.NewCBCEncrypter(block, IV[:blockSize]) crypted := make([]byte, len(origData)) blockMode.CryptBlocks(crypted, origData) return crypted, nil } func Aes128Decrypt(crypted, key []byte, IV []byte) ([]byte, error) { if key == nil || len(key) != 16 { return nil, nil } if IV != nil && len(IV) != 16 { return nil, nil } block, err := aes.NewCipher(key) if err != nil { return nil, err } blockSize := block.BlockSize() blockMode := cipher.NewCBCDecrypter(block, IV[:blockSize]) origData := make([]byte, len(crypted)) blockMode.CryptBlocks(origData, crypted) origData = PKCS5UnPadding(origData) return origData, nil } func PKCS5Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } func PKCS5UnPadding(origData []byte) []byte { length := len(origData) unpadding := int(origData[length-1]) return origData[:(length - unpadding)] }
|