1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- package utils
- import (
- "crypto/cipher"
- "crypto/des"
- "fmt"
- )
- type DES struct {
- block cipher.Block
- key, iv []byte
- }
- // 定义Key与向量的值
- var DesKey = []byte{102, 16, 93, 156, 78, 4, 218, 32}
- var DesIv = []byte{55, 103, 246, 79, 36, 99, 167, 3}
- func DESEncrypt(src []byte) []byte {
- des, err := newDESInstance(DesKey, DesIv)
- if err != nil {
- fmt.Println("DES Encrypt Error: ", err)
- return nil
- }
- return encrypt(des.block, src, des.key, des.iv)
- }
- func DESEncryptString(src string, base64Encoding bool) string {
- tmp := DESEncrypt([]byte(src))
- return bytes2String(tmp, base64Encoding)
- }
- func DESDecrypt(encrypted []byte) []byte {
- des, err := newDESInstance(DesKey, DesIv)
- if err != nil {
- fmt.Println("DES Encrypt Error: ", err)
- return nil
- }
- return decrypt(des.block, encrypted, des.key, des.iv)
- }
- func DESDecryptString(encrypted string, base64Encoding bool) (string, error) {
- tmp, err := string2Bytes(encrypted, base64Encoding)
- if err != nil {
- return "", err
- }
- return string(DESDecrypt(tmp)), err
- }
- func newDESInstance(key, iv []byte) (*DES, error) {
- key = genBytes(key, KeyLength)
- block, err := des.NewCipher(key)
- if err != nil {
- return nil, err
- }
- return &DES{block: block, key: key, iv: iv}, err
- }
|