Go语言实现DEC加密算法(CBC模式)

Go语言实现DEC加密算法(CBC模式)


DES是一种将64比特的明文加密成64比特的密文的对称加密算法,它的密钥长度是56比特,但每隔7比特会设置一个用于错误检查的比特,所以DES实质上其密钥长度是56比特。

DES是一种分组密码算法,CBC模式(密码分组链接模式)是常用的一种分组密码的模式。(点击查看分组密码及CBC模式概述)

实现代码如下:

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

//对明文进行填充
func Padding(plainText []byte,blockSize int) []byte{
	//计算要填充的长度
	n:= blockSize-len(plainText)%blockSize
	//对原来的明文填充n个n
	temp:=bytes.Repeat([]byte{byte(n)},n)
	plainText=append(plainText,temp...)
	return plainText
}
//对密文删除填充
func UnPadding(cipherText []byte) []byte{
	//取出密文最后一个字节end
	end:=cipherText[len(cipherText)-1]
	//删除填充
	cipherText=cipherText[:len(cipherText)-int(end)]
	return cipherText
}
//DEC加密(CBC模式)
func DEC_CBC_Encrypt(plainText []byte,key []byte) []byte{
	//指定加密算法,创建并返回一个使用DES算法的cipher.Block接口对象
	block,err:=des.NewCipher(key)
	if err!=nil{
		panic(err)
	}
	//对明文进行分组填充
	plainText=Padding(plainText,block.BlockSize())
	//指定初始化向量IV,长度必须等于block的块尺寸
	iv:=[]byte("abcdefgh")
	//指定分组模式,返回一个BlockMode接口对象
	blockMode:=cipher.NewCBCEncrypter(block,iv)
	//加密连续的数据块
	cipherText:=make([]byte,len(plainText))
	blockMode.CryptBlocks(cipherText,plainText)
	//返回密文
	return cipherText
}
//DEC解密(CBC模式)
func DEC_CBC_Decrypt(cipherText []byte,key []byte) []byte{
	//指定解密算法
	block,err:=des.NewCipher(key)
	if err!=nil{
		panic(err)
	}
	//指定初始化向量IV,长度必须等于block的块尺寸(和加密的一致)
	iv:=[]byte("abcdefgh")
	//指定分组模式,返回一个BlockMode接口对象
	blockMode:=cipher.NewCBCDecrypter(block,iv)
	//解密
	plainText:=make([]byte,len(cipherText))
	blockMode.CryptBlocks(plainText,cipherText)
	//删除填充
	plainText=UnPadding(plainText)
	//返回明文
	return plainText
}

测试代码如下:

func main(){
	message:=[]byte("hello world")
	//指定密钥
	key:=[]byte("abcd1234")
	//加密
	cipherText:=DEC_CBC_Encrypt(message,key)
	fmt.Println("加密后为:",string(cipherText))
	//解密
	plainText:=DEC_CBC_Decrypt(cipherText,key)
	fmt.Println("解密后为:",string(plainText))

}

测试结果如下:
测试结果

你可能感兴趣的:(Go语言实现DEC加密算法(CBC模式))