在 Go 项目中封装 AES 加解密客户端接口
在一个中型以上的项目项目中, 我们一般会在项目工程中开辟一个pkg文件夹用来存放一些基础工具接口,比如:数据库、中间件、中封装加解密算法、加解接口基础协议等等 。密客在这篇文章中,户端 我主要分享一下在基于Go语言的项目中, 加解密算法中如何封装一个通用的加解密接口, 并以使用比较广泛的AES加解密算法实现为基础进行讲解, 最后模拟客户端分别演示调用AES的加密接口和解密接口。

在一个正规项目中,项目 我们要封装的文件主要添加在算法文件夹下, 目录结构规划如下:
复制pkg | ---- algorithm | ---- base.go // 基础接口函数定义 | ---- aes.go // aes加解密算法接口 | ---- aes_test.go // aes加解密算法接口函数测试1.2.3.4.5.6.7.8.9.我在名为"algorithm"文件夹下新建了三个文件, 其中base.go为基础接口函数定义, 因为以后可能要加入进来的源码下载算法会比较多,因此需要有一个基础类文件来定义通用函数接口 。
aes.go文件中主要实现AES算法的中封装加解密过程, 并提供一个对外的初始化接口,方便应用层调用。
aes_test.go是加解接口作为单元测试的文件, 在里面可以针对AES加密函数和解密函数写测试用例, 不用编译整个工程实现单元测试 。
如果后面有新的密客算法加入进来, 例如:des算法, 只需要添加一个des.go和des_test.go文件, 在里面实现函数功能即可 。
3.基础接口实现基础接口实现主要在base.go文件中,户端 因为对于所有加密算法来讲, 都有两个最基础通用的方法:加密函数和解密函数,因此这里定义了两个通用的建站模板方法接口:
复制type IAlgorithm interface { Encrypt() // 加密函数接口 Decrypt() // 解密函数接口 }1.2.3.4.因为现在不知道项目默认需要使用什么算法,因此实现这两个方法的空接口:
复制type DefaultAlgorithm struct{ } func (dal DefaultAlgorithm) Encrypt() { } func (dal DefaultAlgorithm) Decrypt() { }1.2.3.4.5.考虑在应用层方便切换不同的算法, 这里需要设计一个管理接口的方法, 首先定义一个结构体:
复制type AlgorithmManager struct { algorithm IAlgorithm }1.2.3.在这个结构体中, 成员是上面接口名称的对象 。
然后我定义了两个方法,项目 一个是设置算法对象的方法, 另一个是执行算法方式的方法。免费模板
首先是中封装设置算法对象的方法:
复制func (gor *AlgorithmManager) SetAlgorithm(algorithm IAlgorithm) { gor.algorithm = algorithm }1.2.3.这个方法会接收一个参数,这个参数就是用户想要调用哪种算法的对象, 只有给接口赋对应算法的对象,接口才知道调用哪个算法的方法 。
其次是加解接口运行算法类型的方法:
复制const ( encryptMode = "encrypt" decryptMode = "decrypt" ) func (gor *AlgorithmManager) RunAlgorithm(runMode string) { switch runMode { case encryptMode: gor.algorithm.Encrypt() break case decryptMode: gor.algorithm.Decrypt() break } }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.这里我定义了两个模式用来标识加密模式和解密模式, 当给RunAlgorithm传参encryptMode, 则会执行加密函数,反之则执行解密函数。
4.AES加解密算法实现在AES加解密客户端调用接口中,密客 我选择了选项设计模式, 用户可以根据加密算法和解密算法参数不同进行灵活的源码库选项传参 。
首先定义一个方法结构体:
复制type AesAlgorithm struct { AppAlg *AlgorithmManager EncryptKey string // 密钥 PlaintextContent string // 明文内容 CiphertextContent string // 密文内容 }1.2.3.4.5.6.在这个结构体中,户端 密钥 、明文内容 、密文内容是我们在使用功能过程中必须传入的参数, 其中还带有一个结构对象指针: *AlgorithmManager, 方便我们将AES算法的对象传给接口,让其调用AES的加密方法或解密方法。
其次定义一个方便客户端调用的接口, 并使用动态选项传参,实现代码如下:
复制type AesAlgorithmOption func(aes *AesAlgorithm) // 用户初始化调用并传参 func NewAesAlgorithm(options ...AesAlgorithmOption) *AesAlgorithm { aesAlg := &AesAlgorithm{ AppAlg: new(AlgorithmManager), EncryptKey: "", PlaintextContent: "", CiphertextContent: "", } for _, option := range options { option(aesAlg) } return aesAlg } // 通过该选项函数传入key func WithEncryptKey(key string) AesAlgorithmOption { return func(aes *AesAlgorithm) { aes.EncryptKey = key } } // 通过该选项函数传入明文 func WithPlaintextContent(plainText string) AesAlgorithmOption { return func(aes *AesAlgorithm) { aes.PlaintextContent = plainText } } // 通过该选项函数传入密文 func WithCiphertextContent(cipherContent string) AesAlgorithmOption { return func(aes *AesAlgorithm) { aes.CiphertextContent = cipherContent } }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.下面我们还实现了两个内部函数,分别是加密和解密过程中需要填充块的亿华云实现方法,代码如下:
加密填充块:
复制func pkcs5Padding(cipherText []byte, blockSize int) []byte { padding := blockSize - len(cipherText)%blockSize padtext := bytes.Repeat([]byte{ byte(padding)}, padding) return append(cipherText, padtext...) }1.2.3.4.5.解密填充块:
复制func pkcs5UnPadding(origData []byte) []byte { length := len(origData) unpadding := int(origData[length-1]) return origData[:(length - unpadding)] }1.2.3.4.5.最后实现了加密接口函数和解密接口函数,代码如下:
加密接口函数实现:
复制func (aalg *AesAlgorithm) Encrypt() { tmpKeys := []byte(aalg.EncryptKey) tmpPlaintext := aalg.PlaintextContent block, err := aes.NewCipher(tmpKeys) if err != nil { fmt.Println("aes加密失败,原因:" + err.Error()) return } blockSize := block.BlockSize() origData := pkcs5Padding([]byte(tmpPlaintext), blockSize) blockMode := cipher.NewCBCEncrypter(block, tmpKeys[:blockSize]) crypted := make([]byte, len(origData)) blockMode.CryptBlocks(crypted, origData) aalg.CiphertextContent = hex.EncodeToString(crypted) }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.解密接口函数实现:
复制func (aalg *AesAlgorithm) Decrypt() { tmpKeys := []byte(aalg.EncryptKey) cryptedByte, _ := hex.DecodeString(aalg.CiphertextContent) block, err := aes.NewCipher(tmpKeys) if err != nil { fmt.Println("aes解密失败,原因:" + err.Error()) return } blockSize := block.BlockSize() blockMode := cipher.NewCBCDecrypter(block, tmpKeys[:blockSize]) origin := make([]byte, len(cryptedByte)) blockMode.CryptBlocks(origin, cryptedByte) decryptStrings := pkcs5UnPadding(origin) aalg.PlaintextContent = string(decryptStrings) }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15. 5.AES加密函数验证我在aes_test.go中实现加密函数测试模块:TestEncrypt(t *testing.T), 代码如下:
复制func TestEncrypt(t *testing.T) { aesAlg := NewAesAlgorithm( WithEncryptKey("ZEplYJFPLlhhMaJI"), WithPlaintextContent("qYWwo7!!Eq-TX3q"), ) aesAlg.AppAlg.SetAlgorithm(aesAlg) aesAlg.AppAlg.RunAlgorithm("encrypt") fmt.Println(aesAlg.CiphertextContent) }1.2.3.4.5.6.7.8.9.在上面的代码中, 我们调用了AES算法的对外统一接口函数:NewAesAlgorithm, 并分别调用WithEncryptKey和WithPlaintextContent传入了Key内容和明文内容, 并调用接口管理方法:SetAlgorithm进行对象赋值, 最后调用RunAlgorithm("encrypt")方法进行AES加密,实际结果如下:

同样在aes_test.go中实现加密函数测试模块:TestDecrypt(t *testing.T), 代码如下:
复制func TestDecrypt(t *testing.T) { aesAlg := NewAesAlgorithm( WithEncryptKey("ZEplYJFPLlhhMaJI"), WithCiphertextContent("31404e2eb60e2d16faae152106882f4b"), ) aesAlg.AppAlg.SetAlgorithm(aesAlg) aesAlg.AppAlg.RunAlgorithm("decrypt") fmt.Println(aesAlg.PlaintextContent) }1.2.3.4.5.6.7.8.9.在上面的代码中, 我们调用了AES算法的对外统一接口函数:NewAesAlgorithm, 并分别调用WithEncryptKey和WithCiphertextContent传入了Key内容和上面加密的密文内容, 并调用接口管理方法:SetAlgorithm进行对象赋值, 最后调用RunAlgorithm("decrypt")方法进行AES解密,实际结果如下:

可以看到 ,成功解密出密文且跟加密时传入的明文一致,解密正确。
相关文章
大约53%的工业企业认为大多数未来的网络威胁将以智能工厂为主要目标,其中包括60%的重工业企业和56%的制药和生命科学公司。然而,高水平的网络安全意识并不会自动转化为业务准备。缺乏最高管理层的关注、有2025-12-07
如今,手机已经成为我们生活中必不可少的一部分。除了通讯、娱乐等功能外,手机摄影也成为人们追求美好瞬间的利器。在众多手机品牌中,小米以其出色的性价比和优秀的拍照能力备受推崇。其中,米4作为小米旗舰机型之2025-12-07
随着数字经济的快速发展,加密货币成为了一个备受瞩目的话题。作为加密货币的产生途径之一,电脑挖矿机在近年来也备受关注。本文将探讨电脑挖矿机在未来的前景,并分析其所面临的机遇和挑战。1.电脑挖矿机的概念与2025-12-07
用iPadmini2唱歌体验如何?(探索iPadmini2在音乐创作中的潜力)
在当今数字化时代,iPadmini2作为一款功能强大的移动设备,不仅可用于工作学习,还能带给用户更多的娱乐体验。其中,以iPadmini2唱歌,成为了很多音乐爱好者的选择。本文将探索iPadmini22025-12-07
网络安全研究人员披露了正在进行的网络钓鱼活动的细节,该活动利用招聘和工作主题的诱饵来投放名为 WARMCOOKIE 的基于 Windows 的后门。Elastic Security Labs 研究员2025-12-07
昂达V703(全面功能与高性价比,昂达V703给你带来不一样的体验)
在如今智能设备领域,平板电脑作为一种流行的移动设备,已经成为人们日常生活中不可或缺的一部分。昂达V703作为一款备受推崇的平板电脑,以其全面的功能和高性价比受到了广大消费者的喜爱和追捧。本文将详细介绍2025-12-07

最新评论