Created
August 11, 2017 12:31
-
-
Save zweite/1c3bfa7a6864c35f25420c6b56c0b3a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"crypto/cipher" | |
"crypto/des" | |
"encoding/base64" | |
) | |
type Decrypter struct { | |
Ekey []byte // 加密 key | |
Ikey []byte // 校验 key | |
} | |
func NewDecrypter(ekey, ikey []byte) *Decrypter { | |
return &Decrypter{ | |
Ekey: ekey, | |
Ikey: ikey, | |
} | |
} | |
func (d *Decrypter) Decode(src string) (text string, err error) { | |
data, err := base64.StdEncoding.DecodeString(src) | |
if err != nil { | |
return | |
} | |
block, err := des.NewTripleDESCipher(d.Ekey) | |
if err != nil { | |
return | |
} | |
ci := cipher.NewCBCDecrypter(block, d.Ikey) | |
dst := make([]byte, len(data)) | |
ci.CryptBlocks(dst, data) | |
text = string(dst) | |
return | |
} | |
func (d *Decrypter) Encode(src string) (text string, err error) { | |
block, err := des.NewTripleDESCipher(d.Ekey) | |
if err != nil { | |
return | |
} | |
data := []byte(src) | |
data = PKCS5Padding(data, block.BlockSize()) | |
ci := cipher.NewCBCEncrypter(block, d.Ikey) | |
dst := make([]byte, len(data)) | |
ci.CryptBlocks(dst, data) | |
text = base64.StdEncoding.EncodeToString(dst) | |
return | |
} | |
func PKCS5Padding(ciphertext []byte, blockSize int) []byte { | |
padding := blockSize - len(ciphertext)%blockSize | |
padtext := bytes.Repeat([]byte{byte(padding)}, padding) | |
return append(ciphertext, padtext...) | |
} | |
func main() { | |
dec := NewDecrypter([]byte("liuyunqiang@lx100$#365#$"), []byte("01234567")) | |
text, _ := dec.Decode("U4UwyX30n0E=") | |
println(text) | |
text, _ = dec.Encode("123456") | |
println(text) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment