Go语言实现AES加密并编写一个命令行应用程序
来源:脚本之家
2023-02-25 09:14:36
0浏览
收藏
从现在开始,努力学习吧!本文《Go语言实现AES加密并编写一个命令行应用程序》主要讲解了加密、AES等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!
什么是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]#
今天关于《Go语言实现AES加密并编写一个命令行应用程序》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
版本声明
本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
增删改查sql语法基础教程
- 上一篇
- 增删改查sql语法基础教程
- 下一篇
- Mysql分组排序取每组第一条的2种实现方式
查看更多
最新文章
-
- Golang · Go教程 | 3小时前 | goroutine · pprof · Go教程 · 运行时 · Go pprof 性能诊断 goroutine profile pprof.Lookup
- Go pprof.Lookup 怎样读取 goroutine profile 文本
- 465浏览 收藏
-
- Golang · Go教程 | 3小时前 | 标准库 · HTTP · Go教程 · Go 请求头 textproto CanonicalMIMEHeaderKey MIMEHeader
- Go textproto.CanonicalMIMEHeaderKey 怎样统一请求头键名
- 283浏览 收藏
-
- Golang · Go教程 | 3小时前 |
- Go image.NewRGBA 怎样创建可修改的 RGBA 画布
- 289浏览 收藏
-
- Golang · Go教程 | 3小时前 |
- Go compress/gzip Reader 怎样复用并正确关闭
- 454浏览 收藏
-
- Golang · Go教程 | 3小时前 |
- Go archive/zip FileHeader.ExternalAttrs 读取条目权限属性
- 460浏览 收藏
-
- Golang · Go教程 | 3小时前 | 标准库 · Go教程 · Go 邮箱地址 net/mail ParseAddressList 收件人列表
- Go net/mail ParseAddressList 怎样解析多个收件人
- 465浏览 收藏
-
- Golang · Go教程 | 3小时前 | Go教程 · Go crypto/rand 随机令牌 随机字节 密钥材料
- Go crypto/rand 怎样生成固定字节数随机值
- 443浏览 收藏
-
- Golang · Go教程 | 3小时前 |
- Go net.Dialer 怎样配置连接建立超时
- 151浏览 收藏
-
- Golang · Go教程 | 3小时前 |
- Go tls.Config 怎样限制最低 TLS 版本
- 197浏览 收藏
-
- Golang · Go教程 | 3小时前 | go · Plugin · Go plugin 版本兼容 buildmode=plugin
- Go plugin 包为什么不适合跨版本加载
- 426浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 598次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 639次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 671次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 637次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 458次使用
查看更多
相关文章
-
- Go 语言简单实现Vigenere加密算法
- 2022-12-29 319浏览
-
- Go实现凯撒密码加密解密
- 2022-12-29 327浏览
-
- Go语言使用对称加密的示例详解
- 2023-02-16 322浏览
-
- 通过Golang编写一个AES加密解密工具
- 2022-12-30 373浏览
-
- Golang实现AES加密和解密的示例代码
- 2023-01-07 307浏览

