国密SM —— SM3单向散列、SM3案例实现、SM4分组密码标准、Go语言实现SM4加密

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/The_Reader/article/details/84022101
func main() {
	hash := sm3.New()

	hash.Write([]byte("i am wek $$ The_Reader !"))

	result := hash.Sum(nil)

	println("sm3 hash = ",hex.EncodeToString(result))

	hash2 := sm3.Sm3Sum([]byte("i am wek $$ The_Reader !"))
	println("sm3 hash2 = ",hex.EncodeToString(hash2))
}

结果为:

 

SM4分组密码标准

它将明文分成多个等长的模块(block),使用确定的算法和对称密钥对每组分别加密解密。分组加密是极其重要的加密协议组成,SM4的密钥长度及分组长度均为128bit。

SM4加密解密案例:



func SM4Encrypt(src []byte, key []byte) []byte {

	block, e := sm4.NewCipher(key)
	if e != nil {
		fmt.Println("newCrypther faild !")
	}
	a := block.BlockSize() - len(src)%block.BlockSize()
	repeat := bytes.Repeat([]byte{byte(a)},a)
	newsrc := append(src, repeat...)

	dst := make([]byte, len(newsrc))
	blockMode := cipher.NewCBCEncrypter(block, key[:block.BlockSize()])
	blockMode.CryptBlocks(dst,newsrc)
	return dst

}




func SM4Decrypto(dst,key []byte)[]byte{

	block, e := sm4.NewCipher(key)
	if e!=nil{
		fmt.Println("newcipher faild! ")
	}
	blockMode := cipher.NewCBCDecrypter(block, key[:block.BlockSize()])

	src := make([]byte, len(dst))
	blockMode.CryptBlocks(src,dst)

	num := int(src[len(src)-1])
	newsrc := src[:len(src)-num]
	return newsrc
}

func main() {
	 a := []byte("erl1233312")
	key := []byte("aabbccddaabbccdd")
	decrypto := SM4Encrypt(a,key)
	fmt.Println("sm4加密后:",hex.EncodeToString(decrypto))
	i := SM4Decrypto(decrypto, key)
	fmt.Println("sm4解密后:",string(i))

}

结果为:

 

猜你喜欢

转载自blog.csdn.net/The_Reader/article/details/84022101