技术文摘
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
- Web 端原生 JS 自定义截屏的实现
- JavaScript 数组反转之教程
- Python 在 2021 年会走向消亡吗?
- Python 代码中装饰器重要性探究
- TIOBE 2 月榜单:R、Go 与 Swift 等谁可稳居前十?
- TIOBE 2 月榜单公布,编程语言领域近年是否未变?
- 深入探究高并发大对象处理
- Spring 的 Registrar 倒排理念分享给你
- 每日一技:图片格式的识别方法
- 善用 ActionFilterAttribute 记录 API 日志
- Java 中易混淆的小细节
- Python 基础篇:发送 Post 请求的传参方式(包括参数位置、数据类型和不同方式)
- Python 编程中 Dict 和 Set 常用用法大盘点
- C#+Selenium+ChromeDriver 实现网页爬取及真实用户浏览行为模拟
- IDEA 中的敏捷开发实时模版技巧