不背锅运维:Go实现aes加密,并带你手撸一个命令行应用程序
2023-06-13 09:17:01 时间
什么是AES
关于AES更多的知识,请自行脑补,密码学中的高级加密标准(Advanced Encryption Standard,AES),又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。
go实现aes加密
在golang的标准库aes可以实现AES加密,官方标准库aes文档链接:https://pkg.go.dev/crypto/aes
小案例需求
本篇分享出在实际工作中的实际需求,需求很简单,就是需要实现一个命令行应用程序,可以对传入的明文字符串进行加密,传入密文进行解密。命令行应用叫做passctl,并带有帮助功能。实现命令行应用程序有很多强大的第三方库,因为需求过于简单,那么本篇就用标准库中os即可。
实战
加密代码
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)
var EncKey = []byte("QAZWSXEDCRFVTGBY") // 16位密码串
func pkcs7Padding(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}
func AesEncrypt(data []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
encryptBytes := pkcs7Padding(data, blockSize)
crypted := make([]byte, len(encryptBytes))
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
blockMode.CryptBlocks(crypted, encryptBytes)
return crypted, nil
}
func EncryptByAes(data []byte) (string, error) {
res, err := AesEncrypt(data, EncKey)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(res), nil
}
func main() {
plaintext := "2wsx$RFV!Qaz" // 假设这是明文密码
p := []byte(plaintext)
newp, _ := EncryptByAes(p) // 开始加密
fmt.Println(newp)
}
解密代码
基于上述加密后的密码,对其进行解密。
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"errors"
"fmt"
)
var EncKey = []byte("QAZWSXEDCRFVTGBY") // 16位密码串
func pkcs7UnPadding(data []byte) ([]byte, error) {
length := len(data)
if length == 0 {
return nil, errors.New("Sorry, the encryption string is wrong.")
}
unPadding := int(data[length-1])
return data[:(length - unPadding)], nil
}
func AesDecrypt(data []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
crypted := make([]byte, len(data))
blockMode.CryptBlocks(crypted, data)
crypted, err = pkcs7UnPadding(crypted)
if err != nil {
return nil, err
}
return crypted, nil
}
func DecryptByAes(data string) ([]byte, error) {
dataByte, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return nil, err
}
return AesDecrypt(dataByte, EncKey)
}
func main() {
ciphertext := "+LxjKS8N+Kpy/HNxsSJMIw==" // 密文
pwd, _ := DecryptByAes(ciphertext) // 开始解密
fmt.Println(string(pwd))
}
实现passctl命令行应用
代码
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"errors"
"fmt"
"os"
)
var EncKey = []byte("QAZWSXEDCRFVTGBY") // 16位密码串
func pkcs7Padding(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}
func pkcs7UnPadding(data []byte) ([]byte, error) {
length := len(data)
if length == 0 {
return nil, errors.New("Sorry, the encryption string is wrong.")
}
unPadding := int(data[length-1])
return data[:(length - unPadding)], nil
}
func AesEncrypt(data []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
encryptBytes := pkcs7Padding(data, blockSize)
crypted := make([]byte, len(encryptBytes))
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
blockMode.CryptBlocks(crypted, encryptBytes)
return crypted, nil
}
func AesDecrypt(data []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
crypted := make([]byte, len(data))
blockMode.CryptBlocks(crypted, data)
crypted, err = pkcs7UnPadding(crypted)
if err != nil {
return nil, err
}
return crypted, nil
}
func EncryptByAes(data []byte) (string, error) {
res, err := AesEncrypt(data, EncKey)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(res), nil
}
func DecryptByAes(data string) ([]byte, error) {
dataByte, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return nil, err
}
return AesDecrypt(dataByte, EncKey)
}
const help = `
Help description of encryption and decryption command line application
-h --help [Display help]
-e --encryption Plaintext string encryption
-d --decrypt Ciphertext string decryption
Example:
1. encryption example:
passctl -e "your plaintext password"
2. decryption example:
passctl -d "Your ciphertext string"
`
func main() {
args := os.Args[1]
if args == "-h" || args == "--help" {
fmt.Print(help)
} else if args == "-e" || args == "--encryption" {
plaintext := os.Args[2]
p := []byte(plaintext)
newp, _ := EncryptByAes(p)
fmt.Println(newp)
} else if args == "-d" || args == "--decrypt" {
ciphertext := os.Args[2]
a, _ := DecryptByAes(ciphertext)
fmt.Println(string(a))
} else {
fmt.Println("Invalid option")
}
}
编译成二进制后使用
# 编译
[root@devhost encryptionDecryption]# go build -o passctl main.go
# 查看帮助
[root@devhost encryptionDecryption]# ./passctl -h
Help description of encryption and decryption command line application
-h --help [Display help]
-e --encryption Plaintext string encryption
-d --decrypt Ciphertext string decryption
Example:
1. encryption example:
passctl -e "your plaintext password"
2. decryption example:
passctl -d "Your ciphertext string"
# 加密
[root@devhost encryptionDecryption]# ./passctl -e abc123456
nGi3ls+2yghdv7o8Ly2Z+A==
# 解密
[root@devhost encryptionDecryption]# ./passctl -d nGi3ls+2yghdv7o8Ly2Z+A==
abc123456
[root@devhost encryptionDecryption]#
本文转载于(喜欢的盆友关注我们):https://mp.weixin.qq.com/s/FsIfvsuu5jh5_yBXZUS7rA
相关文章
- 14.Go语言-协程
- Go 编程 | 连载 15 - Go 语言的函数
- Go 编程 | 连载 35 - testing 标准库的其他功能
- 数据库Go-sqlx实战
- 如何优雅的通过Shell脚本一键部署GO项目到服务器 |Go主题月
- 【Go】github.com/robfig/cron 源码阅读
- 工厂模式有三个Level,你能用Go写到第几层?
- 「Go工具箱」go语言csrf库的使用方式和实现原理
- 2023-03-07:x264的视频编码器,不用ffmpeg,用libx264.dll也行。请用go语言调用libx264.dll,将yuv文件编码成h264文
- Go语言正/反向代理的姿势
- Go 开发常用操作技巧--模块管理
- 从CPU角度理解Go中的结构体内存对齐
- GO 中 defer的实现原理
- client-go实战之十:标签选择(labels.Selector),重要
- 600+服务模块,1万+POD数量,作业帮从PHP迁移至Go实战总结
- client-go实战之七:准备一个工程管理后续实战的代码
- Go语言flag包:命令行参数解析
- Go语言—小白入门-命令行库Cobra的使用详解编程语言
- Go语言变量逃逸分析
- 深度探索Go语言与Redis结合(go-redis)
- SQL Server快速上手GO!(sqlserver go)
- 请求简单而快速用Go编写的Redis请求测试(用go写的redis)
- 给Oracle数据库添加专业技能,Go大发展(go_db_oracle)
- 踏上oracle编程之路,Go(go oracle编程)
- GO语言文件的创建与打开实例分析