使用Golang实现AES加解密的代码示例

来自:网络
时间:2024-06-07
阅读:

前言

在现代的数据安全中,加密和解密是极其重要的一环。其中,高级加密标准(AES)是最广泛使用的加密算法之一。本文将介绍如何使用Golang来实现AES加密和解密。

一、AES是什么?

高级加密标准(AES)是一种对称加密算法,也就是说,加密和解密使用相同的密钥。AES支持128、192和256位的密钥长度,越长的密钥提供了越高的安全性,但也需要更多的计算资源。AES使用固定的128位的块大小,不同的密钥长度和块大小可以组合成不同的AES变体,例如AES-128、AES-192和AES-256。

二、代码实现

以下是一个使用Golang实现AES加解密的简单示例:

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"fmt"
)

func main() {
	key := []byte("myverystrongpasswordo32bitlength") // 32 bytes key for AES-256
	plaintext := []byte("Hello, World!")

	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}

	ciphertext := make([]byte, len(plaintext))
	stream := cipher.NewCTR(block, make([]byte, block.BlockSize()))
	stream.XORKeyStream(ciphertext, plaintext)

	fmt.Printf("Encrypted: %s\n", base64.StdEncoding.EncodeToString(ciphertext))

	decrypted := make([]byte, len(ciphertext))
	stream = cipher.NewCTR(block, make([]byte, block.BlockSize()))
	stream.XORKeyStream(decrypted, ciphertext)

	fmt.Printf("Decrypted: %s\n", decrypted)
}

在这个例子中,我们首先创建了一个新的cipher block。然后我们创建了一个新的CTR(Counter)模式的cipher stream,并使用它来加密我们的明文。

对于解密,我们创建了一个新的CTR模式的cipher stream,并使用它来解密我们的密文。

拓展:AES加密和解密的三种模式实现

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))
}

输出结果:

=== 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生成公私钥

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加密和解密是非常直接的。虽然在实际应用中,你需要考虑如何安全地生成和存储密钥,如何处理错误,以及如何处理不同长度的数据等问题,但基本的AES加密和解密过程是相同的。希望这篇文章对你有所帮助。

以上就是使用Golang实现AES加解密的代码示例的详细内容,更多关于Golang AES加解密的资料请关注其它相关文章!

返回顶部
顶部