技术文摘
Golang 实现 AES 加解密的代码示例
2024-12-28 22:32:08 小编
Golang 实现 AES 加解密的代码示例
在现代的信息安全领域,加密技术起着至关重要的作用。AES(Advanced Encryption Standard)是一种广泛使用的对称加密算法,具有高效、安全的特点。在 Go 语言中,我们可以轻松地实现 AES 加解密。
我们需要导入必要的包:
import (
"crypto/aes"
"crypto/cipher"
"encoding/hex"
)
接下来,定义密钥和明文:
key := []byte("ThisIsASecretKey")
plaintext := []byte("Hello, AES Encryption!")
加密函数如下:
func encrypt(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err!= nil {
return nil, err
}
ciphertext := make([]byte, aes.BlockSize + len(plaintext))
iv := ciphertext[:aes.BlockSize]
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
return ciphertext, nil
}
解密函数与加密函数类似:
func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err!= nil {
return nil, err
}
plaintext := make([]byte, len(ciphertext) - aes.BlockSize)
iv := ciphertext[:aes.BlockSize]
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(plaintext, ciphertext[aes.BlockSize:])
return plaintext, nil
}
在主函数中,我们调用加密和解密函数:
func main() {
ciphertext, err := encrypt(plaintext, key)
if err!= nil {
panic(err)
}
plaintextDecrypted, err := decrypt(ciphertext, key)
if err!= nil {
panic(err)
}
// 输出加密后的十六进制字符串
fmt.Println("Encrypted: ", hex.EncodeToString(ciphertext))
// 输出解密后的明文
fmt.Println("Decrypted: ", string(plaintextDecrypted))
}
通过以上代码示例,我们成功地在 Go 语言中实现了 AES 加解密的功能。在实际应用中,确保妥善保管密钥,并根据具体需求进行适当的错误处理和优化。
AES 加密算法为我们的数据安全提供了有力的保障,通过 Go 语言简洁高效的特性,能够方便地将其应用到各种需要加密的场景中。
TAGS: Golang_AES 加密 Golang_AES 解密 AES 加密_Golang AES 解密_Golang
- 鸿蒙系统文字识别方法教程
- openSUSE11.0 更新地址
- Suse 10.3 root 密码遗忘的解决之道
- 鸿蒙系统按键解锁息屏延迟的解决之道
- 虚拟机中打开 DMG 的方法与教程
- 如何在 Ubuntu 中安装轻量级 LXDE 桌面
- 深度操作系统 15.4 Beta 的主要更新内容是什么
- 鸿蒙系统驾驶模式开启方法
- 鸿蒙系统安装第三方软件的方法及无法安装的解决之道
- 如何在 Ubuntu18.04 中打造 Win10 桌面布局风格
- UG 多边形草图绘制方法:以整八边形为例的教程
- 华为鸿蒙系统看图识物的使用方法及教程
- CSS 新手的 CSS 技巧汇总
- 鸿蒙侧边栏应用的删除方式
- VirtualBox 中与主机共享文件夹的手把手教程(含图文)