|  | 
|  | 1 | +package mysqlfuncs | 
|  | 2 | + | 
|  | 3 | +import ( | 
|  | 4 | +	"crypto/cipher" | 
|  | 5 | +	"crypto/des" | 
|  | 6 | +	"crypto/md5" | 
|  | 7 | +	"errors" | 
|  | 8 | +	"fmt" | 
|  | 9 | +	"github.com/rnben/mysql-funcs-go/openssl" | 
|  | 10 | +) | 
|  | 11 | + | 
|  | 12 | +// DesDecrypt MySQL DES_DECRYPT | 
|  | 13 | +func DesDecrypt(encrypted []byte, plainKey string) (res string, err error) { | 
|  | 14 | +	defer func() { | 
|  | 15 | +		if r := recover(); r != nil { | 
|  | 16 | +			err = fmt.Errorf("err: %v", r) | 
|  | 17 | +			return | 
|  | 18 | +		} | 
|  | 19 | +	}() | 
|  | 20 | + | 
|  | 21 | +	length := len(encrypted) | 
|  | 22 | + | 
|  | 23 | +	if length == 0 { | 
|  | 24 | +		return "", nil | 
|  | 25 | +	} | 
|  | 26 | +	if encrypted[0] != 0xff { | 
|  | 27 | +		return "", errors.New("invalid encrypted text") | 
|  | 28 | +	} | 
|  | 29 | + | 
|  | 30 | +	encrypted = encrypted[1:] | 
|  | 31 | +	if len(encrypted)%8 != 0 { | 
|  | 32 | +		return "", errors.New("invalid encrypted text") | 
|  | 33 | +	} | 
|  | 34 | + | 
|  | 35 | +	iv := []byte{0, 0, 0, 0, 0, 0, 0, 0} | 
|  | 36 | +	key, _ := openssl.EVPBytesToKey(24, 8, md5.New(), nil, []byte(plainKey), 1) | 
|  | 37 | + | 
|  | 38 | +	block, err := des.NewTripleDESCipher(key) | 
|  | 39 | +	if err != nil { | 
|  | 40 | +		return "", err | 
|  | 41 | +	} | 
|  | 42 | + | 
|  | 43 | +	blockMode := cipher.NewCBCDecrypter(block, iv) | 
|  | 44 | +	decrypted := make([]byte, length-1) | 
|  | 45 | +	blockMode.CryptBlocks(decrypted, encrypted) | 
|  | 46 | +	return string(unPadding(decrypted)), nil | 
|  | 47 | +} | 
|  | 48 | + | 
|  | 49 | +func unPadding(decrypted []byte) []byte { | 
|  | 50 | +	length := len(decrypted) | 
|  | 51 | +	tail := int(decrypted[length-1]) | 
|  | 52 | +	return decrypted[:(length - tail)] | 
|  | 53 | +} | 
0 commit comments