关于go:不背锅运维Go实现aes加密并带你手撸一个命令行应用程序

1次阅读

共计 5479 个字符,预计需要花费 14 分钟才能阅读完成。

什么是 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/Fs…

正文完
 0