微信公众号“dotNET跨平台”的文章《开箱即用,.NET最全的加解密开源库》介绍了开源通用工具库NETCore.Encrypt,其支持对称加密算法、非对称加密算法、摘要算法等多种常用算法,使用方便,不过目前仅支持.net core。本文主要测试调用其中的RSA算法进行加解密(RSA算法的原理介绍请见参考文献4)。
新建Winform项目,在NuGet包管理器中安装NETCore.Encrypt,如下图所示:
在NETCore.Encrypt模块中,最重要的类是EncryptProvider,其支持的所有算法都以静态函数的形式定义在该类中,加密算法的话,一般都是以算法简称+Encryp/Decrypt的形式提供,如果需要密钥,EncryptProvider类中也提供有对应的密钥创建函数。
EncryptProvider类中与RSA相关的的函数主要分成三类:密钥创建函数(CreateRsaKey)、加密/解密函数(RSAEncrypt/RSADecrypt)、签名/验签函数(RSASign/RSAVerify):
密钥创建函数生成RSA算法所需的公钥、私钥、公开整数n和e,支持2048、3072、4096位数,默认为2048位。生成的密钥如下图所示。由于EncryptProvider类都是静态函数,并且RSA加解密函数的输入参数中仅包含公钥/私钥,其它密钥信息都包含在密钥创建函数的各个返回值中,并且值用base64处理。
公钥:{"Modulus":"rIzt6+VMrqGnzDZYAMRTKyRSZSO/jBOfx8i+UkGcaJy9NpogEHavZfLC7z/Jkutv2SGPdrB7feBW3wYrpik03JKVlgc9KJeQH/jGOCmTerN66gxSXTkjX4SOmzXDw3FbQ0HIoR2R8HyPmatls2F99rYIxnFBnBzfUhwmSMFMDzvByzwyFam8YN92xt3vTRw+3tZ9CjM0MEzqNpU8xbDbrLm8iVwWemvCcmHEBmCOfz+eV2WavYOpwIfwS2bNqZkVkbtRfAMjY/hULwQZZzXq/wmvZ2aNCTk3meK4p9laUPcqMSJ+nyKgCTIh7BdOpbhZ+fuuMCDe8yGijIPInw/nvQ==","Exponent":"AQAB","P":null,"Q":null,"DP":null,"DQ":null,"InverseQ":null,"D":null}
私钥:{"Modulus":"rIzt6+VMrqGnzDZYAMRTKyRSZSO/jBOfx8i+UkGcaJy9NpogEHavZfLC7z/Jkutv2SGPdrB7feBW3wY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rNsCS8cCUAFiKzoOsbVcUUIbUqHRNTslyyUBkP6k2nYPy0mnlh4x0D9T1wxuVfN+o91Y9EJiX/nxXOUwlZYAtPQeOqQI=","D":"fNJiFqDErRuSGB9D4CIli/L1i+alXT6g+lRUoYqHDAI+um4aPe6tiZFoxMwfFKIuQiON9a1LWE7eaO28y7HJZLrBbUuFSYUCpK5BLkWdQ0js5LzPJFL+LM3mn47wM8Uf4PKIoUyT0yU4eFDN/ErNZZhflrY9YSJdxrdIVp9GV0mRyPHNldllSGq6lP1+pYCpXuTDV2iLctiAde4/t5Iaqyl6dkcDd+Y/9P20kcL7GMDp8gH9ZG/rXPZf81UyBA64PIX5uS7M9LtGdaeWDHNBE6Ihp+irYP3s3nWPRxlSjDVW2vqHPI31X9YFafv6tQmFend/F0EysJ1G0uODe6H7nQ=="}
e:010001
n:AC8CEDEBE54CAEA1A7CC365800C4532B24526523BF8C139FC7C8BE52419C689CBD369A201076AF65F2C2EF3FC992EB6FD9218F76B07B7DE056DF062BA62934DC929596073D2897901FF8C63829937AB37AEA0C525D39235F848E9B35C3C3715B4341C8A11D91F07C8F99AB65B3617DF6B608C671419C1CDF521C2648C14C0F3BC1CB3C3215A9BC60DF76C6DDEF4D1C3EDED67D0A3334304CEA36953CC5B0DBACB9BC895C167A6BC27261C406608E7F3F9E57659ABD83A9C087F04B66CDA9991591BB517C032363F8542F04196735EAFF09AF67668D09393799E2B8A7D95A50F72A31227E9F22A0093221EC174EA5B859F9FBAE3020DEF321A28C83C89F0FE7BD
函数调用比较简单,本文使用以下函数进行加解密(EncryptProvider类中的RSA函数有多种重载函数,支持多种明文形式),加解密的测试截图如下图所示:
public static string RSAEncrypt(string publicKey, string srcString)
public static string RSADecrypt(string privateKey, string srcString)
参考文献:
[1]https://blog.csdn.net/sD7O95O/article/details/132893071
[2]https://github.com/myloveCc/NETCore.Encrypt
[3]https://www.cnblogs.com/piscesLoveCc/p/7423205.html
[4]https://baike.baidu.com/item/RSA%E7%AE%97%E6%B3%95