123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- package util
- import (
- "bytes"
- "crypto/aes"
- "crypto/cipher"
- "encoding/hex"
- "errors"
- "strings"
- )
- var PwdKey = "4MTGXKRGWVHCVC7C"
- func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
- padding := blockSize - len(ciphertext)%blockSize
-
- padtext := bytes.Repeat([]byte{byte(padding)}, padding)
- return append(ciphertext, padtext...)
- }
- func PKCS7UnPadding1(origData []byte) ([]byte, error) {
-
- length := len(origData)
- if length == 0 {
- return nil, errors.New("加密字符串错误!")
- } else {
-
- unpadding := int(origData[length-1])
-
- return origData[:(length - unpadding)], nil
- }
- }
- func AesEcrypt(origData []byte, key []byte) ([]byte, error) {
-
- block, err := aes.NewCipher(key)
- if err != nil {
- return nil, err
- }
-
- blockSize := block.BlockSize()
-
- origData = PKCS7Padding(origData, blockSize)
-
- blocMode := cipher.NewCBCEncrypter(block, key[:blockSize])
- crypted := make([]byte, len(origData))
-
- blocMode.CryptBlocks(crypted, origData)
- return crypted, nil
- }
- func AesDeCrypt(cypted []byte, key []byte) (string, error) {
-
- block, err := aes.NewCipher(key)
- if err != nil {
- return "", err
- }
-
- blockSize := block.BlockSize()
-
- blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
- origData := make([]byte, len(cypted))
-
- blockMode.CryptBlocks(origData, cypted)
-
- origData, err = PKCS7UnPadding1(origData)
- if err != nil {
- return "", err
- }
- return string(origData), err
- }
- func EnPwdCode(pwdStr,PwdKey string) string {
- pwd := []byte(pwdStr)
- result, err := AesEcrypt(pwd, []byte(PwdKey))
- if err != nil {
- return ""
- }
- return hex.EncodeToString(result)
- }
- func dePwdCode(pwd,PwdKey string) string {
- temp, _ := hex.DecodeString(pwd)
-
- res, _:=AesDeCrypt(temp, []byte(PwdKey))
- return res
- }
- func GetPri(pwd,PwdKey string)string {
- result :=dePwdCode(pwd,strings.ToUpper(PwdKey))
- return result
- }
- func EnPriCode(pwdStr,PwdKey string)string{
- result :=EnPwdCode(pwdStr,strings.ToUpper(PwdKey))
- return result
- }
|