Go实现aes加密,并带你手撸一个命令行应用程序

简介: Go实现aes加密,并带你手撸一个命令行应用程序

什么是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]#
相关文章
|
10月前
|
算法 测试技术 Go
go-dongle v1.1.7 发布,新增 SM4 国密分组对称加密算法支持
`dongle` 是一款轻量级、语义化、开发者友好的 Golang 密码库,100% 单元测试覆盖,获 2024 年 GVP 与 G-Star 双项荣誉。支持 SM4 国密算法,提供标准及流式处理,优化读取位置重置,提升安全性与易用性。文档齐全,开源免费,欢迎 Star!
441 0
|
10月前
|
算法 测试技术 Go
go-dongle v1.1.7 发布,新增 SM4 国密分组对称加密算法支持
`dongle` 是一款轻量级、语义化、开发者友好的 Golang 密码库,100% 单元测试覆盖,获 2024 年 GVP 与 G-Star 双项荣誉。支持 SM4 国密算法,提供标准及流式处理,优化读取位置重置,提升安全性与易用性。文档齐全,开源免费,欢迎 Star!
403 0
|
Kubernetes Linux Go
使用 Uber automaxprocs 正确设置 Go 程序线程数
`automaxprocs` 包就是专门用来解决此问题的,并且用法非常简单,只需要使用匿名导入的方式 `import _ "go.uber.org/automaxprocs"` 一行代码即可搞定。
594 78
|
算法 安全 数据安全/隐私保护
基于AES的遥感图像加密算法matlab仿真
本程序基于MATLAB 2022a实现,采用AES算法对遥感图像进行加密与解密。主要步骤包括:将彩色图像灰度化并重置大小为256×256像素,通过AES的字节替换、行移位、列混合及轮密钥加等操作完成加密,随后进行解密并验证图像质量(如PSNR值)。实验结果展示了原图、加密图和解密图,分析了图像直方图、相关性及熵的变化,确保加密安全性与解密后图像质量。该方法适用于保护遥感图像中的敏感信息,在军事、环境监测等领域具有重要应用价值。
629 35
|
存储 安全 数据安全/隐私保护
Mac如何用命令行处理文件加密压缩
本教程介绍在Mac中通过命令行实现文件和文件夹的加密压缩、分卷处理及解压操作。主要内容包括:1) 使用`zip -er`命令加密压缩文件夹,`zip -e`命令加密压缩单个文件;2) 使用`split`命令按指定大小分割ZIP文件;3) 通过`cat`命令合并分卷文件并使用`unzip`解压。适用于需要安全传输和存储数据的场景。
|
算法 安全 Go
Go语言中的加密和解密是如何实现的?
Go语言通过标准库中的`crypto`包提供丰富的加密和解密功能,包括对称加密(如AES)、非对称加密(如RSA、ECDSA)及散列函数(如SHA256)。`encoding/base64`包则用于Base64编码与解码。开发者可根据需求选择合适的算法和密钥,使用这些包进行加密操作。示例代码展示了如何使用`crypto/aes`包实现对称加密。加密和解密操作涉及敏感数据处理,需格外注意安全性。
440 14
|
Go 数据处理 开发者
Go 语言的反射机制允许程序在运行时动态检查和操作类型信息,提供极大的灵活性和扩展性
Go 语言的反射机制允许程序在运行时动态检查和操作类型信息,提供极大的灵活性和扩展性。本文探讨了反射的基本原理、主要操作、应用场景及注意事项,并通过实例展示了反射的实际应用,帮助开发者更好地理解和使用这一强大特性。
298 2
|
安全 测试技术 Go
Python 和 Go 实现 AES 加密算法的技术详解
Python 和 Go 实现 AES 加密算法的技术详解
1233 0
Go to Learn Go之命令行参数
Go to Learn Go之命令行参数
243 8
|
存储 安全 数据安全/隐私保护
浅谈对称加密(AES与DES)
浅谈对称加密(AES与DES)
716 1

热门文章

最新文章