Go语言实现AES加密算法(CTR模式)

Go语言实现AES加密算法(CTR模式)


AES是目前比较流行的对称加密算法,是一种分组密码算法,AES的分组长度为128比特(16字节),而密钥长度可以是128比特、192比特或256比特。

CTR模式(计数器模式)是常用的一种分组密码的模式。(点击查看分组密码及CTR模式概述)

实现代码如下:

import (
	"crypto/aes"
	"crypto/cipher"
	"fmt"
)

//AEC加密和解密(CRT模式)
func AEC_CRT_Crypt(text []byte,key []byte) []byte{
	//指定加密、解密算法为AES,返回一个AES的Block接口对象
	block,err:=aes.NewCipher(key)
	if err!=nil{
		panic(err)
	}
	//指定计数器,长度必须等于block的块尺寸
	count:=[]byte("12345678abcdefgh")
	//指定分组模式
	blockMode:=cipher.NewCTR(block,count)
	//执行加密、解密操作
	message:=make([]byte,len(text))
	blockMode.XORKeyStream(message,text)
	//返回明文或密文
	return message
}

测试代码如下:

func main(){
	message:=[]byte("Hello!My name is X.")
	//指定密钥
	key:=[]byte("14725836qazwsxed")
	//加密
	cipherText:=AEC_CRT_Crypt(message,key)
	fmt.Println("加密后为:",string(cipherText))
	//解密
	plainText:=AEC_CRT_Crypt(cipherText,key)
	fmt.Println("解密后为:",string(plainText))
}

测试结果如下:
AES(CRT)测试结果

你可能感兴趣的:(Go,AES,CTR)