AES加密和解密的三种模式实现(CBC/ECB/CFB)
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"io"
"log"
)
func main() {
origData := []byte("杰哥的技术杂货铺") // 待加密的数据
key := []byte("ABCDEFGHIJKLMNOP") // 加密的密钥
log.Println("原文:", string(origData))
log.Println("------------------ CBC模式 --------------------")
encrypted := AesEncryptCBC(origData, key)
log.Println("密文(hex):", hex.EncodeToString(encrypted))
log.Println("密文(base64):", base64.StdEncoding.EncodeToString(encrypted))
decrypted := AesDecryptCBC(encrypted, key)
log.Println("解密结果:", string(decrypted))
log.Println("------------------ ECB模式 --------------------")
encrypted = AesEncryptECB(origData, key)
log.Println("密文(hex):", hex.EncodeToString(encrypted))
log.Println("密文(base64):", base64.StdEncoding.EncodeToString(encrypted))
decrypted = AesDecryptECB(encrypted, key)
log.Println("解密结果:", string(decrypted))
log.Println("------------------ CFB模式 --------------------")
encrypted = AesEncryptCFB(origData, key)
log.Println("密文(hex):", hex.EncodeToString(encrypted))
log.Println("密文(base64):", base64.StdEncoding.EncodeToString(encrypted))
decrypted = AesDecryptCFB(encrypted, key)
log.Println("解密结果:", string(decrypted))
}
CBC/ECB/CFB 解密方法
// =================== CBC ======================
func AesEncryptCBC(origData []byte, key []byte) (encrypted []byte) {
// 分组秘钥
// NewCipher该函数限制了输入k的长度必须为16, 24或者32
block, _ := aes.NewCipher(key)
blockSize := block.BlockSize() // 获取秘钥块的长度
origData = pkcs5Padding(origData, blockSize) // 补全码
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) // 加密模式
encrypted = make([]byte, len(origData)) // 创建数组
blockMode.CryptBlocks(encrypted, origData) // 加密
return encrypted
}
func AesDecryptCBC(encrypted []byte, key []byte) (decrypted []byte) {
block, _ := aes.NewCipher(key) // 分组秘钥
blockSize := block.BlockSize() // 获取秘钥块的长度
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) // 加密模式
decrypted = make([]byte, len(encrypted)) // 创建数组
blockMode.CryptBlocks(decrypted, encrypted) // 解密
decrypted = pkcs5UnPadding(decrypted) // 去除补全码
return decrypted
}
func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func pkcs5UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
// =================== ECB ======================
func AesEncryptECB(origData []byte, key []byte) (encrypted []byte) {
cipher, _ := aes.NewCipher(generateKey(key))
length := (len(origData) + aes.BlockSize) / aes.BlockSize
plain := make([]byte, length*aes.BlockSize)
copy(plain, origData)
pad := byte(len(plain) - len(origData))
for i := len(origData); i < len(plain); i++ {
plain[i] = pad
}
encrypted = make([]byte, len(plain))
// 分组分块加密
for bs, be := 0, cipher.BlockSize(); bs <= len(origData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
cipher.Encrypt(encrypted[bs:be], plain[bs:be])
}
return encrypted
}
func AesDecryptECB(encrypted []byte, key []byte) (decrypted []byte) {
cipher, _ := aes.NewCipher(generateKey(key))
decrypted = make([]byte, len(encrypted))
//
for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
cipher.Decrypt(decrypted[bs:be], encrypted[bs:be])
}
trim := 0
if len(decrypted) > 0 {
trim = len(decrypted) - int(decrypted[len(decrypted)-1])
}
return decrypted[:trim]
}
func generateKey(key []byte) (genKey []byte) {
genKey = make([]byte, 16)
copy(genKey, key)
for i := 16; i < len(key); {
for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
genKey[j] ^= key[i]
}
}
return genKey
}
// =================== CFB ======================
func AesEncryptCFB(origData []byte, key []byte) (encrypted []byte) {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
encrypted = make([]byte, aes.BlockSize+len(origData))
iv := encrypted[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(encrypted[aes.BlockSize:], origData)
return encrypted
}
func AesDecryptCFB(encrypted []byte, key []byte) (decrypted []byte) {
block, _ := aes.NewCipher(key)
if len(encrypted) < aes.BlockSize {
panic("ciphertext too short")
}
iv := encrypted[:aes.BlockSize]
encrypted = encrypted[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(encrypted, encrypted)
return encrypted
}
输出结果:
2022/08/02 20:02:24 原文: 杰哥的技术杂货铺
2022/08/02 20:02:24 ------------------ CBC模式 --------------------
2022/08/02 20:02:24 密文(hex): 6b11cae9b7831c3bbf1782a69e5504f5c32da4f6a5771e017f3a2d5ae8bf10b4
2022/08/02 20:02:24 密文(base64): axHK6beDHDu/F4KmnlUE9cMtpPaldx4BfzotWui/ELQ=
2022/08/02 20:02:24 解密结果: 杰哥的技术杂货铺
2022/08/02 20:02:24 ------------------ ECB模式 --------------------
2022/08/02 20:02:24 密文(hex): eb69b3c7921373408f371a9f608c5915bc72d09a06994af0788542bab88387a9
2022/08/02 20:02:24 密文(base64): 62mzx5ITc0CPNxqfYIxZFbxy0JoGmUrweIVCuriDh6k=
2022/08/02 20:02:24 解密结果: 杰哥的技术杂货铺
2022/08/02 20:02:24 ------------------ CFB模式 --------------------
2022/08/02 20:02:24 密文(hex): 483c4133a0ba7e0c8655d9e2a23acae4b13494a6036ab231b99bc01e7676fc0bb8c6ab7cbe6953ab
2022/08/02 20:02:24 密文(base64): SDxBM6C6fgyGVdniojrK5LE0lKYDarIxuZvAHnZ2/Au4xqt8vmlTqw==
2022/08/02 20:02:24 解密结果: 杰哥的技术杂货铺
测试用例编写解密
func TestAesEcbDecrypt(t *testing.T) {
origData := []byte("杰哥的技术杂货铺") // 待加密的数据
key := []byte("^%TytgUYGsefsq7JYU5F2OIJ") // 加密的密钥
log.Println("原文:", string(origData))
log.Println("------------------ CBC模式 --------------------")
encrypted := AesEncryptCBC(origData, key)
log.Println("密文(hex):", hex.EncodeToString(encrypted))
log.Println("密文(base64):", base64.StdEncoding.EncodeToString(encrypted))
decrypted := AesDecryptCBC(encrypted, key)
log.Println("解密结果:", string(decrypted))
log.Println("------------------ ECB模式 --------------------")
encrypted = AesEncryptECB(origData, key)
log.Println("密文(hex):", hex.EncodeToString(encrypted))
log.Println("密文(base64):", base64.StdEncoding.EncodeToString(encrypted))
decrypted = AesDecryptECB(encrypted, key)
log.Println("解密结果:", string(decrypted))
log.Println("------------------ CFB模式 --------------------")
encrypted = AesEncryptCFB(origData, key)
log.Println("密文(hex):", hex.EncodeToString(encrypted))
log.Println("密文(base64):", base64.StdEncoding.EncodeToString(encrypted))
decrypted = AesDecryptCFB(encrypted, key)
log.Println("解密结果:", string(decrypted))
}
输出结果:
=== RUN TestAesEcbDecrypt
2022/08/03 11:23:50 原文: 杰哥的技术杂货铺
2022/08/03 11:23:50 ------------------ CBC模式 --------------------
2022/08/03 11:23:50 密文(hex): 606072d10a591454e68069ff690e63ec0cd4dcd832922aa715aaf682ff645799
2022/08/03 11:23:50 密文(base64): YGBy0QpZFFTmgGn/aQ5j7AzU3NgykiqnFar2gv9kV5k=
2022/08/03 11:23:50 解密结果: 杰哥的技术杂货铺
2022/08/03 11:23:50 ------------------ ECB模式 --------------------
2022/08/03 11:23:50 密文(hex): d31dc8357a8ab488e453b0740e91d0c241b7743b6e02f942c0a15a4417ad518a
2022/08/03 11:23:50 密文(base64): 0x3INXqKtIjkU7B0DpHQwkG3dDtuAvlCwKFaRBetUYo=
2022/08/03 11:23:50 解密结果: 杰哥的技术杂货铺
2022/08/03 11:23:50 ------------------ CFB模式 --------------------
2022/08/03 11:23:50 密文(hex): e6da19018b091415326822560d16a8d614fcb0cad71bdbf3b3afe4bf3633d95e4036c5ed2a25272e
2022/08/03 11:23:50 密文(base64): 5toZAYsJFBUyaCJWDRao1hT8sMrXG9vzs6/kvzYz2V5ANsXtKiUnLg==
2022/08/03 11:23:50 解密结果: 杰哥的技术杂货铺
--- PASS: TestAesEcbDecrypt (0.04s)
PASS
仅进行解密
func TestAesEcbDecrypt(t *testing.T) {
key := []byte("^%TytgUYGsefsq7JYU5F2OIJ") // 加密的密钥
log.Println("------------------ CBC模式 --------------------")
encrypted,err1 := hex.DecodeString("606072d10a591454e68069ff690e63ec0cd4dcd832922aa715aaf682ff645799")
if err1 != nil {
t.Fatal(err1)
}
decrypted := AesDecryptCBC(encrypted, key)
log.Println("解密结果:", string(decrypted))
log.Println("------------------ ECB模式 --------------------")
encrypted,err2 := hex.DecodeString("d31dc8357a8ab488e453b0740e91d0c241b7743b6e02f942c0a15a4417ad518a")
if err2 != nil {
t.Fatal(err2)
}
decrypted = AesDecryptECB(encrypted, key)
log.Println("解密结果:", string(decrypted))
log.Println("------------------ CFB模式 --------------------")
encrypted,err3 := hex.DecodeString("ea9e17002777f1bc791d2be328c65206fff543c94b29341404926b6d0feb9a22428e6749c603352d")
if err3 != nil {
t.Fatal(err3)
}
decrypted = AesDecryptCFB(encrypted, key)
log.Println("解密结果:", string(decrypted))
}
输出结果:文章来源:https://www.toymoban.com/news/detail-506929.html
=== RUN TestAesEcbDecrypt
2022/08/03 11:21:27 ------------------ CBC模式 --------------------
2022/08/03 11:21:27 解密结果: 杰哥的技术杂货铺
2022/08/03 11:21:27 ------------------ ECB模式 --------------------
2022/08/03 11:21:27 解密结果: 杰哥的技术杂货铺
2022/08/03 11:21:27 ------------------ CFB模式 --------------------
2022/08/03 11:21:27 解密结果: 杰哥的技术杂货铺
--- PASS: TestAesEcbDecrypt (0.04s)
PASS
RSA
首先使用openssl生成公私钥文章来源地址https://www.toymoban.com/news/detail-506929.html
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
)
// 私钥生成
//openssl genrsa -out rsa_private_key.pem 1024
var privateKey = []byte(`
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDcGsUIIAINHfRTdMmgGwLrjzfMNSrtgIf4EGsNaYwmC1GjF/bM
h0Mcm10oLhNrKNYCTTQVGGIxuc5heKd1gOzb7bdTnCDPPZ7oV7p1B9Pud+6zPaco
qDz2M24vHFWYY2FbIIJh8fHhKcfXNXOLovdVBE7Zy682X1+R1lRK8D+vmQIDAQAB
AoGAeWAZvz1HZExca5k/hpbeqV+0+VtobMgwMs96+U53BpO/VRzl8Cu3CpNyb7HY
64L9YQ+J5QgpPhqkgIO0dMu/0RIXsmhvr2gcxmKObcqT3JQ6S4rjHTln49I2sYTz
7JEH4TcplKjSjHyq5MhHfA+CV2/AB2BO6G8limu7SheXuvECQQDwOpZrZDeTOOBk
z1vercawd+J9ll/FZYttnrWYTI1sSF1sNfZ7dUXPyYPQFZ0LQ1bhZGmWBZ6a6wd9
R+PKlmJvAkEA6o32c/WEXxW2zeh18sOO4wqUiBYq3L3hFObhcsUAY8jfykQefW8q
yPuuL02jLIajFWd0itjvIrzWnVmoUuXydwJAXGLrvllIVkIlah+lATprkypH3Gyc
YFnxCTNkOzIVoXMjGp6WMFylgIfLPZdSUiaPnxby1FNM7987fh7Lp/m12QJAK9iL
2JNtwkSR3p305oOuAz0oFORn8MnB+KFMRaMT9pNHWk0vke0lB1sc7ZTKyvkEJW0o
eQgic9DvIYzwDUcU8wJAIkKROzuzLi9AvLnLUrSdI6998lmeYO9x7pwZPukz3era
zncjRK3pbVkv0KrKfczuJiRlZ7dUzVO0b6QJr8TRAA==
-----END RSA PRIVATE KEY-----
`)
// 公钥: 根据私钥生成
//openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
var publicKey = []byte(`
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcGsUIIAINHfRTdMmgGwLrjzfM
NSrtgIf4EGsNaYwmC1GjF/bMh0Mcm10oLhNrKNYCTTQVGGIxuc5heKd1gOzb7bdT
nCDPPZ7oV7p1B9Pud+6zPacoqDz2M24vHFWYY2FbIIJh8fHhKcfXNXOLovdVBE7Z
y682X1+R1lRK8D+vmQIDAQAB
-----END PUBLIC KEY-----
`)
// 加密
func RsaEncrypt(origData []byte) ([]byte, error) {
//解密pem格式的公钥
block, _ := pem.Decode(publicKey)
if block == nil {
return nil, errors.New("public key error")
}
// 解析公钥
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
// 类型断言
pub := pubInterface.(*rsa.PublicKey)
//加密
return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}
// 解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
//解密
block, _ := pem.Decode(privateKey)
if block == nil {
return nil, errors.New("private key error!")
}
//解析PKCS1格式的私钥
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
// 解密
return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}
func main() {
data, _ := RsaEncrypt([]byte("hello world"))
fmt.Println(base64.StdEncoding.EncodeToString(data))
origData, _ := RsaDecrypt(data)
fmt.Println(string(origData))
}
到了这里,关于Golang里的AES加密、解密的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!