技术文摘
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
- 人工智能工程师必知的顶级编程语言
- Python程序实现数字列表排序方法
- Python代码准确统计输入内容中字母数量的方法
- SQLRAG:借助自然语言和大型语言模型变革数据库交互
- Python获取网页尺寸的方法
- Go语言中正确解析含错误日期时间字符串的方法
- 我的 zip() 函数为何生成空列表
- Lithe上的Seeders:轻松填充数据库
- Go语言中实现类似继承功能及访问嵌套结构体字段的方法
- PHP连接SQL Server的方法
- Python3 中怎样把列表里多个字符串字典合并成一个字典
- 怎样在PHP代码中实现MongoDB的$substr运算符转换
- 自建 PHP 页面怎样使用 WordPress 评论功能
- PHP二维数组转JSON失效原因探究
- 利用AJAX把修改后的HTML页面发送至数据库并覆盖原有内容的方法