golang--base64编码加des加密

最近在做一个项目的时候,需要用到des加base64编码。无奈网上关于golang的des加密相关的文档非常少。在踩了不少坑的情况下,终于搞掂了。代码如下:

package main

import (
	"bytes"
	"crypto/cipher"
	"crypto/des"
	"encoding/base64"
	"log"
)

func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	log.Println("程序开始....")
	key := []byte("76543456")
	iv := []byte("34234323")
	data := []byte("hello worldDFDFDF")
	out, _ := MyEncrypt(data, key, iv)
	debyte := base64Encode(out)
	log.Println("加密后:", debyte)
	enbyte, _ := base64Decode(debyte)
	//log.Println("base:", enbyte)
	out, _ = MyDecrypt(enbyte, key, iv)
	log.Println("解密后:", string(out))
}
func MyEncrypt(data, key []byte, iv []byte) ([]byte, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	bs := block.BlockSize()
	data = PKCS5Padding(data, bs)
	blockMode := cipher.NewCBCEncrypter(block, iv)
	out := make([]byte, len(data))
	blockMode.CryptBlocks(out, data)
	return out, nil
}
func MyDecrypt(data []byte, key []byte, iv []byte) ([]byte, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockMode := cipher.NewCBCDecrypter(block, iv)
	out := make([]byte, len(data))
	blockMode.CryptBlocks(out, data)
	out = PKCS5UnPadding(out)
	return out, nil
}

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

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

func base64Encode(src []byte) []byte {
	return []byte(base64.StdEncoding.EncodeToString(src))
}

func base64Decode(src []byte) ([]byte, error) {
	return base64.StdEncoding.DecodeString(string(src))
}
程序直接编译就可以使用。

你可能感兴趣的:(golang,golang,base64,des,加密,编码)