golang DES跟base64相结合加解密

// DEStest project DEStest.go
//注意base64对中文不同编码加解密结果不一样,即UTF-8跟GBK
package main

import (
	"bytes"
	"crypto/cipher"
	"crypto/des"
	"encoding/base64"
	"fmt"

	"github.com/axgle/mahonia"
)

//DES加密
func DesEncrypt(origData, key []byte) (string, error) {
	//UTF-8 to GBK
	var enc mahonia.Encoder
	enc = mahonia.NewEncoder("gbk")
	origDataStr := enc.ConvertString(string(origData))
	origData = []byte(origDataStr)

	block, err := des.NewCipher(key)
	if err != nil {
		return "", err
	}
	origData = PKCS5Padding(origData, block.BlockSize())
	// origData = ZeroPadding(origData, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, key)
	crypted := make([]byte, len(origData))
	// 根据CryptBlocks方法的说明,如下方式初始化crypted也可以
	//crypted := origData
	blockMode.CryptBlocks(crypted, origData)
	//base64加密
	encodeString := base64.StdEncoding.EncodeToString(crypted)
	return encodeString, nil
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

//DES解密
func DesDecrypt(encodeString string, key []byte) (string, error) {
	var dec mahonia.Decoder
	//base64解密
	crypted, err := base64.StdEncoding.DecodeString(encodeString)
	block, err := des.NewCipher(key)
	if err != nil {
		return "", err
	}
	blockMode := cipher.NewCBCDecrypter(block, key)
	origData := crypted
	blockMode.CryptBlocks(origData, crypted)
	//origData = PKCS5UnPadding(origData)

	origData = ZeroUnPadding(origData)
	//GBK to UTF-8
	dec = mahonia.NewDecoder("gbk")
	origDataStr := dec.ConvertString(string(origData))

	return origDataStr, nil
}

func ZeroUnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

func main() {
	b := []byte("中国人")
	c := []byte("12345678")
	a, _ := DesEncrypt(b, c)
	fmt.Println(a)

	q, _ := DesDecrypt(a, c)
	fmt.Println(q)
}

你可能感兴趣的:(go学习)