go语言实现DES加密 解密

package main

import (
		"bytes"
	"crypto/des"
	"crypto/cipher"
	"fmt"
)

func padding(src []byte,blocksize int) []byte {
	paddingNum:=blocksize-len(src)%blocksize
	pad:=bytes.Repeat([]byte{byte(paddingNum)},paddingNum)
	dst:=append(src,pad...)
	return dst
}

func unpadding(src []byte) []byte {
	n:=len(src)
	unpadnum:=int(src[n-1])
	dst:=src[:n-unpadnum]
	return dst
}

func encryptDES(src []byte,key []byte) []byte {
	block,_:=des.NewCipher(key)
	src=padding(src,block.BlockSize())
	blockmode:=cipher.NewCBCEncrypter(block,key)
	dst:=make([]byte,len(src))
	blockmode.CryptBlocks(dst,src)
	return dst
}

func decryptDES(src []byte,key []byte) []byte {
	block,_:=des.NewCipher(key)
	blockmode:=cipher.NewCBCDecrypter(block,key)
	blockmode.CryptBlocks(src,src)
	dst:=unpadding(src)
	return dst
}

func main()  {
	src:=[]byte("长长的头发,黑黑的眼睛。")
	key:=[]byte("12345678")
	x:=encryptDES(src,key)
	x=decryptDES(x,key)
	fmt.Print(string(x))
}

 

你可能感兴趣的:(Go语言)