golang aes cbc

发布时间:2024-07-05 00:47:41

Golang AES CBC加密与解密

AES(高级加密标准)是一种对称加密算法,常用于数据的加密和解密。其中CBC(密码分组链接模式)是AES的一个工作模式。本文将介绍如何在Golang中使用AES CBC进行数据的加密与解密。

加密

步骤1:定义密钥和明文

``` key := []byte("abcdefghijklmnop") // 16字节的密钥 plaintext := []byte("Hello, world!") // 待加密的明文 ```

步骤2:创建AES cipher块

``` block, err := aes.NewCipher(key) if err != nil { panic(err) } ```

步骤3:填充明文

``` paddingSize := aes.BlockSize - len(plaintext)%aes.BlockSize padding := bytes.Repeat([]byte{byte(paddingSize)}, paddingSize) plaintext = append(plaintext, padding...) ```

步骤4:创建CBC加密器

``` iv := make([]byte, aes.BlockSize) // 初始化向量,长度等于块大小 cipher.NewCBCEncrypter(block, iv) ```

步骤5:加密数据

``` ciphertext := make([]byte, len(plaintext)) cipher.Encrypt(ciphertext, plaintext) ```

解密

步骤1:创建CBC解密器

``` cipher.NewCBCDecrypter(block, iv) ```

步骤2:解密数据

``` decrypted := make([]byte, len(ciphertext)) cipher.Decrypt(decrypted, ciphertext) ```

步骤3:去除填充

``` paddingSize := decrypted[len(decrypted)-1] decrypted = decrypted[:len(decrypted)-int(paddingSize)] ```

示例代码

``` package main import ( "bytes" "crypto/aes" "crypto/cipher" "fmt" ) func main() { key := []byte("abcdefghijklmnop") plaintext := []byte("Hello, world!") block, err := aes.NewCipher(key) if err != nil { panic(err) } paddingSize := aes.BlockSize - len(plaintext)%aes.BlockSize padding := bytes.Repeat([]byte{byte(paddingSize)}, paddingSize) plaintext = append(plaintext, padding...) iv := make([]byte, aes.BlockSize) cipher.NewCBCEncrypter(block, iv) ciphertext := make([]byte, len(plaintext)) cipher.Encrypt(ciphertext, plaintext) cipher.NewCBCDecrypter(block, iv) decrypted := make([]byte, len(ciphertext)) cipher.Decrypt(decrypted, ciphertext) paddingSize = decrypted[len(decrypted)-1] decrypted = decrypted[:len(decrypted)-int(paddingSize)] fmt.Println("Original:", string(plaintext)) fmt.Println("Decrypted:", string(decrypted)) } ```

以上代码演示了Golang中使用AES CBC进行加密与解密的过程。首先,我们定义了密钥和明文。然后,创建AES cipher块,并对明文进行填充。接下来,我们创建CBC加密器,对明文进行加密。对于解密过程,我们需要创建CBC解密器,并对密文进行解密。最后,我们去除填充,得到解密后的明文。

通过以上步骤,我们可以成功地使用Golang实现AES CBC加密与解密。AES CBC是一种常用的加密模式,可用于保护敏感数据的安全性。

相关推荐