Go语言实现AES加密并编写一个命令行应用程序

 更新时间:2023年02月16日 11:23:15   作者:TtrOps  
密码学中的高级加密标准(Advanced Encryption Standard,AES),又称Rijndael加密法,是经常采用的一种区块加密标准。本文就来用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]# 

到此这篇关于Go语言实现AES加密并编写一个命令行应用程序的文章就介绍到这了,更多相关Go语言AES加密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • VsCode下开发Go语言的环境配置超详细图文详解

    VsCode下开发Go语言的环境配置超详细图文详解

    vscode是一款跨平台、轻量级、插件多的开源IDE,在vscode不仅可以配置C/C++、Python、R、Ruby等语言的环境,还可以配置Go语言的环境,下面这篇文章主要给大家介绍了关于VsCode下开发Go语言的环境配置,需要的朋友可以参考下
    2024-03-03
  • Go Java算法最大单词长度乘积示例详解

    Go Java算法最大单词长度乘积示例详解

    这篇文章主要为大家介绍了Go Java算法最大单词长度乘积示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-08-08
  • go实现Redis读写分离示例详解

    go实现Redis读写分离示例详解

    本篇文章将介绍Redis通信协议RESP, 而后在使用go来编写一个中间件,从而来完成Redis读写分离,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-08-08
  • Go语言Zap库Logger的定制化和封装使用详解

    Go语言Zap库Logger的定制化和封装使用详解

    这篇文章主要介绍了Go语言Zap库Logger的定制化和封装使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06
  • 详解golang中的结构体编解码神器Mapstructure库

    详解golang中的结构体编解码神器Mapstructure库

    mapstructure是GO字典(map[string]interface{})和Go结构体之间转换的编解码工具,这篇文章主要为大家介绍一下Mapstructure库的相关使用,希望对大家有所帮助
    2023-09-09
  • Go语言实现Base64、Base58编码与解码

    Go语言实现Base64、Base58编码与解码

    本文主要介绍了Base64、Base58编码与解码,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • Go语言中日志的规范使用建议分享

    Go语言中日志的规范使用建议分享

    在任何服务端的语言项目中,日志是至关重要的组成部分,本文为大家整理了一些如何规范使用GO语言日志的建议,以及相应的实际示例,希望对大家有事帮助
    2024-01-01
  • 使用Go语言生成二维码并在命令行中输出

    使用Go语言生成二维码并在命令行中输出

    二维码(QR code)是一种矩阵条码的标准,广泛应用于商业、移动支付和数据存储等领域,在开发过程中,我们可能需要在命令行中显示二维码,这可以帮助我们快速生成和分享二维码信息,本文将介绍如何使用Go语言生成二维码并在命令行中输出,需要的朋友可以参考下
    2023-11-11
  • 利用 Go 语言编写一个简单的 WebSocket 推送服务

    利用 Go 语言编写一个简单的 WebSocket 推送服务

    这篇文章主要介绍了利用 Go 语言编写一个简单的 WebSocket 推送服务,需要的朋友可以参考下
    2018-04-04
  • go依赖注入库samber/do使用示例讲解

    go依赖注入库samber/do使用示例讲解

    这篇文章主要介绍了go依赖注入库samber/do使用,在本文中,我们学习了如何使用samber/do在 Go 中提供依赖注入,需要的朋友可以参考下
    2024-02-02

最新评论