├── .gitattributes
├── .gitignore
├── Bing.Encryption.sln
├── LICENSE
├── README.md
├── build
├── pack.bat
└── version.props
├── src
└── Bing.Encryption
│ ├── Abstractions
│ ├── IEncryptionAlgorithm.cs
│ └── ISymmetricEncyption.cs
│ ├── Asymmetric
│ └── RSA
│ │ ├── RSAEncryptionProvider.cs
│ │ ├── RSAKey.cs
│ │ ├── RSAKeySizeType.cs
│ │ ├── RSAKeyType.cs
│ │ └── RSAType.cs
│ ├── Base64ConvertProvider.cs
│ ├── Bing.Encryption.csproj
│ ├── Core
│ ├── HMACHashingBase.cs
│ ├── Internals
│ │ ├── Extensions
│ │ │ ├── BytesAndStringExtensions.cs
│ │ │ └── RSAKeyExtensions.cs
│ │ ├── RSAParametersJson.cs
│ │ └── RandomStringGenerator.cs
│ ├── OutType.cs
│ ├── SHAHashingBase.cs
│ └── SymmetricEncryptionBase.cs
│ ├── Hash
│ ├── HMAC
│ │ ├── HMACMD5HashingProvider.cs
│ │ ├── HMACSHA1HashingProvider.cs
│ │ ├── HMACSHA256HashingProvider.cs
│ │ ├── HMACSHA384HashingProvider.cs
│ │ └── HMACSHA512HashingProvider.cs
│ ├── MD4
│ │ ├── MD4CryptoServiceProvider.cs
│ │ └── MD4HashingProvider.cs
│ ├── MD5
│ │ ├── MD5BitType.cs
│ │ └── MD5HasingProvider.cs
│ └── SHA
│ │ ├── SHA1HashingProvider.cs
│ │ ├── SHA256HashingProvider.cs
│ │ ├── SHA384HashingProvider.cs
│ │ └── SHA512HashingProvider.cs
│ └── Symmetric
│ ├── AES
│ ├── AESEncryptionProvider.cs
│ ├── AESKey.cs
│ └── AESKeySizeType.cs
│ ├── DES
│ ├── DESEncryptionProvider.cs
│ └── DESKey.cs
│ ├── RC4EncryptionProvider.cs
│ └── TripleDES
│ ├── TripleDESEncryptionProvider.cs
│ ├── TripleDESKey.cs
│ └── TripleDESKeySizeType.cs
└── tests
└── Bing.Encryption.Tests
├── Asymmetric
└── RsaTest.cs
├── Base64ConvertProviderTest.cs
├── Bing.Encryption.Tests.csproj
├── Hash
├── HmacTest.cs
├── Md4Test.cs
├── Md5Test.cs
└── ShaTest.cs
├── Symmetric
├── AesTest.cs
├── DesTest.cs
├── Rc4Test.cs
└── TripleDesTest.cs
└── TestBase.cs
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | project.fragment.lock.json
46 | artifacts/
47 |
48 | *_i.c
49 | *_p.c
50 | *_i.h
51 | *.ilk
52 | *.meta
53 | *.obj
54 | *.pch
55 | *.pdb
56 | *.pgc
57 | *.pgd
58 | *.rsp
59 | *.sbr
60 | *.tlb
61 | *.tli
62 | *.tlh
63 | *.tmp
64 | *.tmp_proj
65 | *.log
66 | *.vspscc
67 | *.vssscc
68 | .builds
69 | *.pidb
70 | *.svclog
71 | *.scc
72 |
73 | # Chutzpah Test files
74 | _Chutzpah*
75 |
76 | # Visual C++ cache files
77 | ipch/
78 | *.aps
79 | *.ncb
80 | *.opendb
81 | *.opensdf
82 | *.sdf
83 | *.cachefile
84 | *.VC.db
85 | *.VC.VC.opendb
86 |
87 | # Visual Studio profiler
88 | *.psess
89 | *.vsp
90 | *.vspx
91 | *.sap
92 |
93 | # TFS 2012 Local Workspace
94 | $tf/
95 |
96 | # Guidance Automation Toolkit
97 | *.gpState
98 |
99 | # ReSharper is a .NET coding add-in
100 | _ReSharper*/
101 | *.[Rr]e[Ss]harper
102 | *.DotSettings.user
103 |
104 | # JustCode is a .NET coding add-in
105 | .JustCode
106 |
107 | # TeamCity is a build add-in
108 | _TeamCity*
109 |
110 | # DotCover is a Code Coverage Tool
111 | *.dotCover
112 |
113 | # NCrunch
114 | _NCrunch_*
115 | .*crunch*.local.xml
116 | nCrunchTemp_*
117 |
118 | # MightyMoose
119 | *.mm.*
120 | AutoTest.Net/
121 |
122 | # Web workbench (sass)
123 | .sass-cache/
124 |
125 | # Installshield output folder
126 | [Ee]xpress/
127 |
128 | # DocProject is a documentation generator add-in
129 | DocProject/buildhelp/
130 | DocProject/Help/*.HxT
131 | DocProject/Help/*.HxC
132 | DocProject/Help/*.hhc
133 | DocProject/Help/*.hhk
134 | DocProject/Help/*.hhp
135 | DocProject/Help/Html2
136 | DocProject/Help/html
137 |
138 | # Click-Once directory
139 | publish/
140 |
141 | # Publish Web Output
142 | *.[Pp]ublish.xml
143 | *.azurePubxml
144 | # TODO: Comment the next line if you want to checkin your web deploy settings
145 | # but database connection strings (with potential passwords) will be unencrypted
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
150 | # checkin your Azure Web App publish settings, but sensitive information contained
151 | # in these scripts will be unencrypted
152 | PublishScripts/
153 |
154 | # NuGet Packages
155 | *.nupkg
156 | # The packages folder can be ignored because of Package Restore
157 | **/packages/*
158 | # except build/, which is used as an MSBuild target.
159 | !**/packages/build/
160 | # Uncomment if necessary however generally it will be regenerated when needed
161 | #!**/packages/repositories.config
162 | # NuGet v3's project.json files produces more ignoreable files
163 | *.nuget.props
164 | *.nuget.targets
165 |
166 | # Microsoft Azure Build Output
167 | csx/
168 | *.build.csdef
169 |
170 | # Microsoft Azure Emulator
171 | ecf/
172 | rcf/
173 |
174 | # Windows Store app package directories and files
175 | AppPackages/
176 | BundleArtifacts/
177 | Package.StoreAssociation.xml
178 | _pkginfo.txt
179 |
180 | # Visual Studio cache files
181 | # files ending in .cache can be ignored
182 | *.[Cc]ache
183 | # but keep track of directories ending in .cache
184 | !*.[Cc]ache/
185 |
186 | # Others
187 | ClientBin/
188 | ~$*
189 | *~
190 | *.dbmdl
191 | *.dbproj.schemaview
192 | *.jfm
193 | *.pfx
194 | *.publishsettings
195 | node_modules/
196 | orleans.codegen.cs
197 |
198 | # Since there are multiple workflows, uncomment next line to ignore bower_components
199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
200 | #bower_components/
201 |
202 | # RIA/Silverlight projects
203 | Generated_Code/
204 |
205 | # Backup & report files from converting an old project file
206 | # to a newer Visual Studio version. Backup files are not needed,
207 | # because we have git ;-)
208 | _UpgradeReport_Files/
209 | Backup*/
210 | UpgradeLog*.XML
211 | UpgradeLog*.htm
212 |
213 | # SQL Server files
214 | *.mdf
215 | *.ldf
216 |
217 | # Business Intelligence projects
218 | *.rdl.data
219 | *.bim.layout
220 | *.bim_*.settings
221 |
222 | # Microsoft Fakes
223 | FakesAssemblies/
224 |
225 | # GhostDoc plugin setting file
226 | *.GhostDoc.xml
227 |
228 | # Node.js Tools for Visual Studio
229 | .ntvs_analysis.dat
230 |
231 | # Visual Studio 6 build log
232 | *.plg
233 |
234 | # Visual Studio 6 workspace options file
235 | *.opt
236 |
237 | # Visual Studio LightSwitch build output
238 | **/*.HTMLClient/GeneratedArtifacts
239 | **/*.DesktopClient/GeneratedArtifacts
240 | **/*.DesktopClient/ModelManifest.xml
241 | **/*.Server/GeneratedArtifacts
242 | **/*.Server/ModelManifest.xml
243 | _Pvt_Extensions
244 |
245 | # Paket dependency manager
246 | .paket/paket.exe
247 | paket-files/
248 |
249 | # FAKE - F# Make
250 | .fake/
251 |
252 | # JetBrains Rider
253 | .idea/
254 | *.sln.iml
255 |
256 | # CodeRush
257 | .cr/
258 |
259 | # Python Tools for Visual Studio (PTVS)
260 | __pycache__/
261 | *.pyc
--------------------------------------------------------------------------------
/Bing.Encryption.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.28307.168
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "00-document", "00-document", "{8488CD5D-F624-4236-8356-6FBF87D3F787}"
7 | ProjectSection(SolutionItems) = preProject
8 | README.md = README.md
9 | EndProjectSection
10 | EndProject
11 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "01-src", "01-src", "{8354214D-5DEC-4FCE-A6EC-DDD4D9F5087C}"
12 | EndProject
13 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "02-tests", "02-tests", "{826F2D53-2E3F-4367-8B9C-378DA0F9DD20}"
14 | EndProject
15 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bing.Encryption", "src\Bing.Encryption\Bing.Encryption.csproj", "{DC7882FF-1F21-444F-935F-6F37861CD33F}"
16 | EndProject
17 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bing.Encryption.Tests", "tests\Bing.Encryption.Tests\Bing.Encryption.Tests.csproj", "{E410B200-A2A1-4C97-8AF2-3BB2D99BBDFF}"
18 | EndProject
19 | Global
20 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
21 | Debug|Any CPU = Debug|Any CPU
22 | Release|Any CPU = Release|Any CPU
23 | EndGlobalSection
24 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
25 | {DC7882FF-1F21-444F-935F-6F37861CD33F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
26 | {DC7882FF-1F21-444F-935F-6F37861CD33F}.Debug|Any CPU.Build.0 = Debug|Any CPU
27 | {DC7882FF-1F21-444F-935F-6F37861CD33F}.Release|Any CPU.ActiveCfg = Release|Any CPU
28 | {DC7882FF-1F21-444F-935F-6F37861CD33F}.Release|Any CPU.Build.0 = Release|Any CPU
29 | {E410B200-A2A1-4C97-8AF2-3BB2D99BBDFF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
30 | {E410B200-A2A1-4C97-8AF2-3BB2D99BBDFF}.Debug|Any CPU.Build.0 = Debug|Any CPU
31 | {E410B200-A2A1-4C97-8AF2-3BB2D99BBDFF}.Release|Any CPU.ActiveCfg = Release|Any CPU
32 | {E410B200-A2A1-4C97-8AF2-3BB2D99BBDFF}.Release|Any CPU.Build.0 = Release|Any CPU
33 | EndGlobalSection
34 | GlobalSection(SolutionProperties) = preSolution
35 | HideSolutionNode = FALSE
36 | EndGlobalSection
37 | GlobalSection(NestedProjects) = preSolution
38 | {DC7882FF-1F21-444F-935F-6F37861CD33F} = {8354214D-5DEC-4FCE-A6EC-DDD4D9F5087C}
39 | {E410B200-A2A1-4C97-8AF2-3BB2D99BBDFF} = {826F2D53-2E3F-4367-8B9C-378DA0F9DD20}
40 | EndGlobalSection
41 | GlobalSection(ExtensibilityGlobals) = postSolution
42 | SolutionGuid = {33FAC9DB-62D8-4517-9F70-4C9D5CEE80C0}
43 | EndGlobalSection
44 | EndGlobal
45 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 jianxuanbing
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Bing.Encryption
2 | [](https://mit-license.org/)
3 |
4 | Bing.Encryption是Bing应用框架的加密操作类库。
5 |
6 | 对各种常用的加密算法进行封装,Base64、对称密码(DES、3DES、AES)、非对称密码(RSA)等实现。
7 |
8 | ## Nuget
9 | |Nuget|版本号|说明|
10 | |---|---|---|
11 | |Bing.Encryption|[](https://www.nuget.org/packages/Bing.Encryption)|
12 |
13 | ## 功能
14 | ### 对称加密算法
15 | #### RSA
16 |
17 | ### 非对称加密算法
18 | #### AES
19 | #### DES
20 | #### TripleDES
21 |
22 | ### Hash
23 | #### MD5
24 |
25 | #### HMAC
26 | ##### HMAC-MD5
27 | ##### HMAC-SHA1
28 | ##### HMAC-SHA256
29 | ##### HMAC-SHA384
30 | ##### HMAC-SHA512
31 |
32 | #### SHA
33 | ##### SHA1
34 | ##### SHA256
35 | ##### SHA384
36 | ##### SHA512
37 |
38 | ### Base64
39 |
40 | ## 依赖类库
41 |
42 |
43 | ## 使用方式
44 | ```c#
45 |
46 | ```
47 |
48 | ## 作者
49 |
50 | 简玄冰
51 |
52 | ## 贡献与反馈
53 |
54 | > 如果你在阅读或使用Bing中任意一个代码片断时发现Bug,或有更佳实现方式,请通知我们。
55 |
56 | > 为了保持代码简单,目前很多功能只建立了基本结构,细节特性未进行迁移,在后续需要时进行添加,如果你发现某个类无法满足你的需求,请通知我们。
57 |
58 | > 你可以通过github的Issue或Pull Request向我们提交问题和代码,如果你更喜欢使用QQ进行交流,请加入我们的交流QQ群。
59 |
60 | > 对于你提交的代码,如果我们决定采纳,可能会进行相应重构,以统一代码风格。
61 |
62 | > 对于热心的同学,将会把你的名字放到**贡献者**名单中。
63 |
64 | ## 免责声明
65 | - 虽然我们对代码已经进行高度审查,并用于自己的项目中,但依然可能存在某些未知的BUG,如果你的生产系统蒙受损失,Bing 团队不会对此负责。
66 | - 出于成本的考虑,我们不会对已发布的API保持兼容,每当更新代码时,请注意该问题。
67 |
68 | ## 开源地址
69 | [https://github.com/bing-framework/Bing.Encryption](https://github.com/bing-framework/Bing.Encryption)
70 |
71 | ## License
72 |
73 | **MIT**
74 |
75 | > 这意味着你可以在任意场景下使用 Bing 应用框架而不会有人找你要钱。
76 |
77 | > Bing 会尽量引入开源免费的第三方技术框架,如有意外,还请自行了解。
78 |
--------------------------------------------------------------------------------
/build/pack.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | echo %1
3 | cd ..
4 |
5 | rem clear old packages
6 | del output\* /q/f/s
7 |
8 | rem build
9 | dotnet build Bing.Encryption.sln -c Release
10 |
11 | rem pack
12 | dotnet pack ./src/Bing.Encryption/Bing.Encryption.csproj
13 |
14 | rem push
15 | for %%i in (output\release\*.nupkg) do dotnet nuget push %%i -k %1 -s https://www.nuget.org/api/v2/package
--------------------------------------------------------------------------------
/build/version.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | 0
4 | 0
5 | 1
6 | 20190116-1
7 | $(VersionMajor).$(VersionMinor).$(VersionPatch)
8 | preview-$(VersionQuality)
9 |
10 |
11 | 简玄冰
12 | 简玄冰
13 | 简玄冰
14 | https://github.com/bing-framework/Bing.Encryption/blob/master/LICENSE
15 | https://github.com/bing-framework/Bing.Encryption
16 | https://github.com/bing-framework/Bing.Encryption
17 | git
18 | bing;applicationframework;dotnetcore;aspnetcore;
19 | Bing应用框架以MIT开源发布,可随意使用
20 |
21 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Abstractions/IEncryptionAlgorithm.cs:
--------------------------------------------------------------------------------
1 | namespace Bing.Encryption.Abstractions
2 | {
3 | ///
4 | /// 加密算法
5 | ///
6 | public interface IEncryptionAlgorithm
7 | {
8 | ///
9 | /// 加密
10 | ///
11 | /// 明文
12 | ///
13 | string Encrypt(string plainText);
14 |
15 | ///
16 | /// 解密
17 | ///
18 | /// 密文
19 | ///
20 | string Decrypt(string cipher);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Abstractions/ISymmetricEncyption.cs:
--------------------------------------------------------------------------------
1 | namespace Bing.Encryption.Abstractions
2 | {
3 | ///
4 | /// 非对称加密
5 | ///
6 | public interface ISymmetricEncyption
7 | {
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Asymmetric/RSA/RSAEncryptionProvider.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Security.Cryptography;
4 | using System.Security.Cryptography.X509Certificates;
5 | using System.Text;
6 | using Bing.Encryption.Core;
7 | using Bing.Encryption.Core.Internals.Extensions;
8 |
9 | // ReSharper disable once CheckNamespace
10 | namespace Bing.Encryption
11 | {
12 | ///
13 | /// RSA 加密提供程序
14 | ///
15 | // ReSharper disable once InconsistentNaming
16 | public static class RSAEncryptionProvider
17 | {
18 | ///
19 | /// 创建 RSA 密钥
20 | ///
21 | /// 密钥长度类型,默认为
22 | /// 密钥类型,默认为
23 | ///
24 | public static RSAKey CreateKey(RSAKeySizeType size = RSAKeySizeType.L2048, RSAKeyType keyType = RSAKeyType.Xml)
25 | {
26 | using (var rsa = new RSACryptoServiceProvider((int) size))
27 | {
28 | var publicKey = keyType == RSAKeyType.Json ? rsa.ToJsonString(false) : rsa.ToExtXmlString(false);
29 |
30 | var privateKey = keyType == RSAKeyType.Json ? rsa.ToJsonString(true) : rsa.ToExtXmlString(true);
31 |
32 | return new RSAKey()
33 | {
34 | PublickKey = publicKey,
35 | PrivateKey = privateKey,
36 | Exponent = rsa.ExportParameters(false).Exponent.ToHexString(),
37 | Modulus = rsa.ExportParameters(false).Modulus.ToHexString()
38 | };
39 | }
40 | }
41 |
42 | ///
43 | /// 从 xml 或 json 字符串中获取RSA实例
44 | ///
45 | /// rsa密钥
46 | /// 密钥类型,默认为
47 | ///
48 | public static RSA RsaFromString(string rsaKey, RSAKeyType keyType = RSAKeyType.Xml)
49 | {
50 | if (string.IsNullOrWhiteSpace(rsaKey))
51 | {
52 | throw new ArgumentNullException(nameof(keyType));
53 | }
54 |
55 | var rsa = RSA.Create();
56 | if (keyType == RSAKeyType.Xml)
57 | {
58 | rsa.FromExtXmlString(rsaKey);
59 | }
60 | else if (keyType == RSAKeyType.Base64)
61 | {
62 | rsa.FromBase64StringByPrivateKey(rsaKey);
63 | }
64 | else
65 | {
66 | rsa.FromJsonString(rsaKey);
67 | }
68 |
69 | return rsa;
70 | }
71 |
72 | ///
73 | /// 获取 RSA 私钥
74 | ///
75 | /// 证书文件路径
76 | /// 密码
77 | ///
78 | public static string GetPrivateKey(string certFile, string password)
79 | {
80 | if (!File.Exists(certFile))
81 | {
82 | throw new FileNotFoundException(nameof(certFile));
83 | }
84 |
85 | var cert = new X509Certificate2(certFile, password, X509KeyStorageFlags.Exportable);
86 | return cert.PrivateKey.ToXmlString(true);
87 | }
88 |
89 | ///
90 | /// 获取 RSA 公钥
91 | ///
92 | /// 证书文件路径
93 | ///
94 | public static string GetPublicKey(string certFile)
95 | {
96 | if (!File.Exists(certFile))
97 | {
98 | throw new FileNotFoundException(nameof(certFile));
99 | }
100 |
101 | var cert = new X509Certificate2(certFile);
102 | return cert.PublicKey.Key.ToXmlString(false);
103 | }
104 |
105 | ///
106 | /// 使用指定公钥加密字符串
107 | ///
108 | /// 要加密的明文字符串
109 | /// 公钥
110 | /// 编码类型
111 | /// 输出类型
112 | /// 密钥类型
113 | ///
114 | public static string Encrypt(string value, string publicKey, Encoding encoding = null,
115 | OutType outType = OutType.Base64, RSAKeyType keyType = RSAKeyType.Xml)
116 | {
117 | if (encoding == null)
118 | {
119 | encoding = Encoding.UTF8;
120 | }
121 |
122 | var result = Encrypt(encoding.GetBytes(value), publicKey, keyType);
123 |
124 | if (outType == OutType.Base64)
125 | {
126 | return Convert.ToBase64String(result);
127 | }
128 |
129 | return result.ToHexString();
130 | }
131 |
132 | ///
133 | /// 使用指定公钥加密字节数组
134 | ///
135 | /// 要加密的明文字节数组
136 | /// 公钥
137 | /// 密钥类型
138 | ///
139 | public static byte[] Encrypt(byte[] sourceBytes, string publicKey, RSAKeyType keyType = RSAKeyType.Xml)
140 | {
141 | using (var rsa = RSA.Create())
142 | {
143 | if (keyType == RSAKeyType.Xml)
144 | {
145 | rsa.FromExtXmlString(publicKey);
146 | }
147 | else if (keyType == RSAKeyType.Base64)
148 | {
149 | rsa.FromBase64StringByPrivateKey(publicKey);
150 | }
151 | else
152 | {
153 | rsa.FromJsonString(publicKey);
154 | }
155 |
156 | return rsa.Encrypt(sourceBytes, RSAEncryptionPadding.Pkcs1);
157 | }
158 | }
159 |
160 | ///
161 | /// 使用指定私钥解密字符串
162 | ///
163 | /// 要解密的密文字符串
164 | /// 私钥
165 | /// 编码类型
166 | /// 输出类型
167 | /// 密钥类型
168 | ///
169 | public static string Decrypt(string value, string privateKey, Encoding encoding = null,
170 | OutType outType = OutType.Base64, RSAKeyType keyType = RSAKeyType.Xml)
171 | {
172 | if (encoding == null)
173 | {
174 | encoding = Encoding.UTF8;
175 | }
176 |
177 | var result = Decrypt(value.GetEncryptBytes(outType), privateKey, keyType);
178 | return encoding.GetString(result);
179 | }
180 |
181 | ///
182 | /// 使用指定私钥解密字节数组
183 | ///
184 | /// 要解密的密文字节数组
185 | /// 私钥
186 | /// 密钥类型
187 | ///
188 | public static byte[] Decrypt(byte[] sourceBytes, string privateKey, RSAKeyType keyType = RSAKeyType.Xml)
189 | {
190 | using (var rsa = RSA.Create())
191 | {
192 | if (keyType == RSAKeyType.Xml)
193 | {
194 | rsa.FromExtXmlString(privateKey);
195 | }
196 | else if (keyType == RSAKeyType.Base64)
197 | {
198 | rsa.FromBase64StringByPrivateKey(privateKey);
199 | }
200 | else
201 | {
202 | rsa.FromJsonString(privateKey);
203 | }
204 |
205 | return rsa.Decrypt(sourceBytes, RSAEncryptionPadding.Pkcs1);
206 | }
207 | }
208 |
209 | ///
210 | /// 使用指定密钥对明文进行签名,返回明文签名的字符串
211 | ///
212 | /// 要签名的明文字符串
213 | /// 私钥
214 | /// 编码类型
215 | /// 输出类型
216 | /// 算法类型
217 | /// 密钥类型
218 | ///
219 | public static string SignData(string source, string privateKey, Encoding encoding = null,
220 | OutType outType = OutType.Base64, RSAType rsaType = RSAType.RSA,
221 | RSAKeyType keyType = RSAKeyType.Xml)
222 | {
223 | if (encoding == null)
224 | {
225 | encoding = Encoding.UTF8;
226 | }
227 |
228 | var result = SignData(encoding.GetBytes(source), privateKey, rsaType, keyType);
229 | if (outType == OutType.Base64)
230 | {
231 | return Convert.ToBase64String(result);
232 | }
233 |
234 | return result.ToHexString();
235 | }
236 |
237 | ///
238 | /// 使用指定私钥对明文进行签名,返回明文签名的字节数组
239 | ///
240 | /// 要签名的明文字节数组
241 | /// 私钥
242 | /// 算法类型
243 | /// 密钥类型
244 | ///
245 | public static byte[] SignData(byte[] source, string privateKey, RSAType rsaType = RSAType.RSA,
246 | RSAKeyType keyType = RSAKeyType.Xml)
247 | {
248 | using (var rsa = RSA.Create())
249 | {
250 | if (keyType == RSAKeyType.Xml)
251 | {
252 | rsa.FromExtXmlString(privateKey);
253 | }
254 | else if (keyType == RSAKeyType.Base64)
255 | {
256 | rsa.FromBase64StringByPrivateKey(privateKey);
257 | }
258 | else
259 | {
260 | rsa.FromJsonString(privateKey);
261 | }
262 |
263 | return rsa.SignData(source, rsaType == RSAType.RSA ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256,
264 | RSASignaturePadding.Pkcs1);
265 | }
266 | }
267 |
268 | ///
269 | /// 使用指定公钥验证解密得到的明文是否符合签名
270 | ///
271 | /// 解密得到的明文
272 | /// 明文签名字符串
273 | /// 公钥
274 | /// 编码类型
275 | /// 输出类型
276 | /// 算法类型
277 | /// 密钥类型
278 | ///
279 | public static bool VerifyData(string source, string signData, string publicKey, Encoding encoding = null,
280 | OutType outType = OutType.Base64, RSAType rsaType = RSAType.RSA, RSAKeyType keyType = RSAKeyType.Xml)
281 | {
282 | if (encoding == null)
283 | {
284 | encoding = Encoding.UTF8;
285 | }
286 |
287 | byte[] sourceBytes = encoding.GetBytes(source);
288 | byte[] signBytes = signData.GetEncryptBytes(outType);
289 |
290 | return VerifyData(sourceBytes, signBytes, publicKey, rsaType, keyType);
291 | }
292 |
293 | ///
294 | /// 使用指定公钥验证解密得到的明文是否符合签名
295 | ///
296 | /// 解密得到的明文字节数组
297 | /// 明文签名字节数组
298 | /// 公钥
299 | /// 算法类型
300 | /// 密钥类型
301 | ///
302 | public static bool VerifyData(byte[] source, byte[] signData, string publicKey, RSAType rsaType = RSAType.RSA,
303 | RSAKeyType keyType = RSAKeyType.Xml)
304 | {
305 | using (var rsa = RSA.Create())
306 | {
307 | if (keyType == RSAKeyType.Xml)
308 | {
309 | rsa.FromExtXmlString(publicKey);
310 | }
311 | else if (keyType == RSAKeyType.Base64)
312 | {
313 | rsa.FromBase64StringByPublicKey(publicKey);
314 | }
315 | else
316 | {
317 | rsa.FromJsonString(publicKey);
318 | }
319 |
320 | return rsa.VerifyData(source, signData,
321 | rsaType == RSAType.RSA ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256,
322 | RSASignaturePadding.Pkcs1);
323 | }
324 | }
325 | }
326 | }
327 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Asymmetric/RSA/RSAKey.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable once CheckNamespace
2 | namespace Bing.Encryption
3 | {
4 | ///
5 | /// RSA 密钥
6 | ///
7 | // ReSharper disable once InconsistentNaming
8 | public class RSAKey
9 | {
10 | ///
11 | /// 公钥
12 | ///
13 | public string PublickKey { get; set; }
14 |
15 | ///
16 | /// 私钥
17 | ///
18 | public string PrivateKey { get; set; }
19 |
20 | ///
21 | /// 公钥 指数
22 | ///
23 | public string Exponent { get; set; }
24 |
25 | ///
26 | /// 公钥 系数
27 | ///
28 | public string Modulus { get; set; }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Asymmetric/RSA/RSAKeySizeType.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable once CheckNamespace
2 | namespace Bing.Encryption
3 | {
4 | ///
5 | /// RSA 密钥长度类型
6 | ///
7 | // ReSharper disable once InconsistentNaming
8 | public enum RSAKeySizeType
9 | {
10 | ///
11 | /// 1024
12 | ///
13 | L1024 = 1024,
14 | ///
15 | /// 2048
16 | ///
17 | L2048 = 2048,
18 | ///
19 | /// 3072
20 | ///
21 | L3072 = 3072,
22 | ///
23 | /// 4096
24 | ///
25 | L4096 = 4096
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Asymmetric/RSA/RSAKeyType.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable once CheckNamespace
2 | namespace Bing.Encryption
3 | {
4 | ///
5 | /// RSA 密钥类型
6 | ///
7 | // ReSharper disable once InconsistentNaming
8 | public enum RSAKeyType
9 | {
10 | Xml,
11 | Json,
12 | Base64
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Asymmetric/RSA/RSAType.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable once CheckNamespace
2 | namespace Bing.Encryption
3 | {
4 | ///
5 | /// RSA 算法类型
6 | ///
7 | // ReSharper disable once InconsistentNaming
8 | public enum RSAType
9 | {
10 | ///
11 | /// SHA1
12 | ///
13 | RSA,
14 |
15 | ///
16 | /// SHA256
17 | ///
18 | RSA2
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Base64ConvertProvider.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text;
3 |
4 | namespace Bing.Encryption
5 | {
6 | ///
7 | /// Base64 转换提供程序
8 | ///
9 | public static class Base64ConvertProvider
10 | {
11 | ///
12 | /// 加密,返回Base64字符串
13 | ///
14 | /// 待加密的值
15 | /// 编码类型,默认为
16 | ///
17 | public static string Encode(string value, Encoding encoding = null)
18 | {
19 | if (value == null)
20 | {
21 | throw new ArgumentNullException(nameof(value));
22 | }
23 |
24 | if (encoding == null)
25 | {
26 | encoding=Encoding.UTF8;
27 | }
28 |
29 | return Convert.ToBase64String(encoding.GetBytes(value));
30 | }
31 |
32 | ///
33 | /// 解密
34 | ///
35 | /// 待解密的值
36 | /// 编码类型,默认为
37 | ///
38 | public static string Decode(string value, Encoding encoding = null)
39 | {
40 | if (value == null)
41 | {
42 | throw new ArgumentNullException(nameof(value));
43 | }
44 |
45 | if (encoding == null)
46 | {
47 | encoding = Encoding.UTF8;
48 | }
49 |
50 | return encoding.GetString(Convert.FromBase64String(value));
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Bing.Encryption.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | Bing.Encryption是Bing应用框架的加密操作类库。
6 | 对各种常用的加密算法进行封装,Base64、对称密码(DES、3DES、AES)、非对称密码(RSA)等实现。
7 |
8 |
9 |
10 | ..\..\output\release\
11 | ..\..\output\release\netstandard2.0\Bing.Encryption.xml
12 |
13 |
14 |
15 | ..\..\output\release\
16 | ..\..\output\release\netstandard2.0\Bing.Encryption.xml
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Core/HMACHashingBase.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Security.Cryptography;
3 | using System.Text;
4 | using Bing.Encryption.Core.Internals.Extensions;
5 |
6 | namespace Bing.Encryption.Core
7 | {
8 | ///
9 | /// HMAC哈希加密基类
10 | ///
11 | // ReSharper disable once InconsistentNaming
12 | public abstract class HMACHashingBase
13 | {
14 | ///
15 | /// 加密
16 | ///
17 | /// 密钥哈希算法类型
18 | /// 待加密的值
19 | /// 密钥
20 | /// 编码
21 | /// 输出类型
22 | ///
23 | protected static string Encrypt(string value,string key, Encoding encoding = null, OutType outType = OutType.Hex)
24 | where T : KeyedHashAlgorithm, new()
25 | {
26 | if (value == null)
27 | {
28 | throw new ArgumentNullException(nameof(value));
29 | }
30 |
31 | if (key == null)
32 | {
33 | throw new ArgumentNullException(nameof(key));
34 | }
35 |
36 | if (encoding == null)
37 | {
38 | encoding = Encoding.UTF8;
39 | }
40 |
41 | using (KeyedHashAlgorithm hash=new T())
42 | {
43 | hash.Key = encoding.GetBytes(key);
44 | var result=hash.ComputeHash(encoding.GetBytes(value));
45 |
46 | if (outType == OutType.Base64)
47 | {
48 | return Convert.ToBase64String(result);
49 | }
50 |
51 | return result.ToHexString();
52 | }
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Core/Internals/Extensions/BytesAndStringExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text;
3 |
4 | namespace Bing.Encryption.Core.Internals.Extensions
5 | {
6 | ///
7 | /// 字节数组及字符串扩展
8 | ///
9 | internal static class BytesAndStringExtensions
10 | {
11 | ///
12 | /// 将字节数组转换成16进制字符串
13 | ///
14 | /// 字节数组
15 | ///
16 | internal static string ToHexString(this byte[] bytes)
17 | {
18 | var sb=new StringBuilder();
19 | for (int i = 0; i < bytes.Length; i++)
20 | {
21 | sb.Append(bytes[i].ToString("X2"));
22 | }
23 | return sb.ToString();
24 | }
25 |
26 | ///
27 | /// 获取加密字符串的加密字节数组
28 | ///
29 | /// 加密字符串
30 | /// 输出类型
31 | ///
32 | internal static byte[] GetEncryptBytes(this string data, OutType outType)
33 | {
34 | switch (outType)
35 | {
36 | case OutType.Base64:
37 | return Convert.FromBase64String(data);
38 | case OutType.Hex:
39 | return ToBytes(data);
40 | }
41 | throw new NotImplementedException();
42 | }
43 |
44 | ///
45 | /// 将16进制字符串转换成字节数组
46 | ///
47 | /// 16进制字符串
48 | ///
49 | internal static byte[] ToBytes(this string hex)
50 | {
51 | if (hex.Length == 0)
52 | {
53 | return new byte[]{0};
54 | }
55 |
56 | if (hex.Length % 2 == 1)
57 | {
58 | hex = "0" + hex;
59 | }
60 | byte[] result=new byte[hex.Length/2];
61 | for (int i = 0; i < hex.Length / 2; i++)
62 | {
63 | result[i] = byte.Parse(hex.Substring(2 * i, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
64 | }
65 |
66 | return result;
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Core/Internals/Extensions/RSAKeyExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Security.Cryptography;
4 | using System.Xml;
5 | using Newtonsoft.Json;
6 |
7 | namespace Bing.Encryption.Core.Internals.Extensions
8 | {
9 | ///
10 | /// RSA 密钥扩展
11 | ///
12 | // ReSharper disable once InconsistentNaming
13 | internal static class RSAKeyExtensions
14 | {
15 | ///
16 | /// 获取RSA key序列化Json
17 | ///
18 | /// RSA
19 | /// 是否包含私钥
20 | internal static string ToJsonString(this RSA rsa, bool includePrivateParameters)
21 | {
22 | var parameters = rsa.ExportParameters(includePrivateParameters);
23 |
24 | var parasJson=new RSAParametersJson()
25 | {
26 | Modulus = parameters.Modulus!=null?Convert.ToBase64String(parameters.Modulus):null,
27 | Exponent = parameters.Exponent != null ? Convert.ToBase64String(parameters.Exponent) : null,
28 | P = parameters.P != null ? Convert.ToBase64String(parameters.P) : null,
29 | Q = parameters.Q != null ? Convert.ToBase64String(parameters.Q) : null,
30 | DP = parameters.DP != null ? Convert.ToBase64String(parameters.DP) : null,
31 | DQ = parameters.DQ != null ? Convert.ToBase64String(parameters.DQ) : null,
32 | InverseQ = parameters.InverseQ != null ? Convert.ToBase64String(parameters.InverseQ) : null,
33 | D = parameters.D != null ? Convert.ToBase64String(parameters.D) : null,
34 | };
35 |
36 | return JsonConvert.SerializeObject(parasJson);
37 | }
38 |
39 | ///
40 | /// 从Json字符串中获取RSA
41 | ///
42 | /// RSA
43 | /// Json字符串
44 | internal static void FromJsonString(this RSA rsa, string jsonString)
45 | {
46 | if (string.IsNullOrWhiteSpace(jsonString))
47 | {
48 | throw new ArgumentNullException(nameof(jsonString));
49 | }
50 |
51 | var parameters=new RSAParameters();
52 |
53 | try
54 | {
55 | var paramsJson = JsonConvert.DeserializeObject(jsonString);
56 | parameters.Modulus = paramsJson.Modulus != null ? Convert.FromBase64String(paramsJson.Modulus) : null;
57 | parameters.Exponent = paramsJson.Exponent != null ? Convert.FromBase64String(paramsJson.Exponent) : null;
58 | parameters.P = paramsJson.P != null ? Convert.FromBase64String(paramsJson.P) : null;
59 | parameters.Q = paramsJson.Q != null ? Convert.FromBase64String(paramsJson.Q) : null;
60 | parameters.DP = paramsJson.DP != null ? Convert.FromBase64String(paramsJson.DP) : null;
61 | parameters.DQ = paramsJson.DQ != null ? Convert.FromBase64String(paramsJson.DQ) : null;
62 | parameters.InverseQ = paramsJson.InverseQ != null ? Convert.FromBase64String(paramsJson.InverseQ) : null;
63 | parameters.D = paramsJson.D != null ? Convert.FromBase64String(paramsJson.D) : null;
64 | }
65 | catch
66 | {
67 | throw new Exception("Invalid Json RSA key.");
68 | }
69 | rsa.ImportParameters(parameters);
70 | }
71 |
72 | ///
73 | /// 从Xml字符串中获取RSA
74 | ///
75 | /// RSA
76 | /// Xml字符串
77 | public static void FromExtXmlString(this RSA rsa, string xmlString)
78 | {
79 | RSAParameters parameters = new RSAParameters();
80 | XmlDocument doc = new XmlDocument();
81 | doc.LoadXml(xmlString);
82 | if (doc.DocumentElement.Name.Equals("RSAKeyValue"))
83 | {
84 | foreach (XmlNode node in doc.DocumentElement.ChildNodes)
85 | {
86 | switch (node.Name)
87 | {
88 | case "Modulus":
89 | parameters.Modulus = string.IsNullOrWhiteSpace(node.InnerText)
90 | ? null
91 | : Convert.FromBase64String(node.InnerText);
92 | break;
93 | case "Exponent":
94 | parameters.Exponent = string.IsNullOrWhiteSpace(node.InnerText)
95 | ? null
96 | : Convert.FromBase64String(node.InnerText);
97 | break;
98 | case "P":
99 | parameters.P = string.IsNullOrWhiteSpace(node.InnerText)
100 | ? null
101 | : Convert.FromBase64String(node.InnerText);
102 | break;
103 | case "Q":
104 | parameters.Q = string.IsNullOrWhiteSpace(node.InnerText)
105 | ? null
106 | : Convert.FromBase64String(node.InnerText);
107 | break;
108 | case "DP":
109 | parameters.DP = string.IsNullOrWhiteSpace(node.InnerText)
110 | ? null
111 | : Convert.FromBase64String(node.InnerText);
112 | break;
113 | case "DQ":
114 | parameters.DQ = string.IsNullOrWhiteSpace(node.InnerText)
115 | ? null
116 | : Convert.FromBase64String(node.InnerText);
117 | break;
118 | case "InverseQ":
119 | parameters.InverseQ = string.IsNullOrWhiteSpace(node.InnerText)
120 | ? null
121 | : Convert.FromBase64String(node.InnerText);
122 | break;
123 | case "D":
124 | parameters.D = string.IsNullOrWhiteSpace(node.InnerText)
125 | ? null
126 | : Convert.FromBase64String(node.InnerText);
127 | break;
128 | }
129 | }
130 | }
131 | else
132 | {
133 | throw new Exception("Invalid Xml RSA Key");
134 | }
135 | rsa.ImportParameters(parameters);
136 | }
137 |
138 | ///
139 | /// 获取RSA key序列化Xml
140 | ///
141 | /// RSA
142 | /// 是否包含私钥
143 | ///
144 | public static string ToExtXmlString(this RSA rsa, bool includePrivateParameters)
145 | {
146 | RSAParameters parameters = rsa.ExportParameters(includePrivateParameters);
147 |
148 | if (includePrivateParameters)
149 | {
150 | return string.Format("{0}{1}{2}
{3}
{4}{5}{6}{7}",
151 | parameters.Modulus != null ? Convert.ToBase64String(parameters.Modulus) : null,
152 | parameters.Exponent != null ? Convert.ToBase64String(parameters.Exponent) : null,
153 | parameters.P != null ? Convert.ToBase64String(parameters.P) : null,
154 | parameters.Q != null ? Convert.ToBase64String(parameters.Q) : null,
155 | parameters.DP != null ? Convert.ToBase64String(parameters.DP) : null,
156 | parameters.DQ != null ? Convert.ToBase64String(parameters.DQ) : null,
157 | parameters.InverseQ != null ? Convert.ToBase64String(parameters.InverseQ) : null,
158 | parameters.D != null ? Convert.ToBase64String(parameters.D) : null);
159 | }
160 | return string.Format("{0}{1}",
161 | parameters.Modulus != null ? Convert.ToBase64String(parameters.Modulus) : null,
162 | parameters.Exponent != null ? Convert.ToBase64String(parameters.Exponent) : null);
163 | }
164 |
165 | ///
166 | /// 从私钥Base64字符串中获取RSA
167 | ///
168 | /// RSA
169 | /// Base64字符串
170 | public static void FromBase64StringByPrivateKey(this RSA rsa, string base64String)
171 | {
172 | var base64Bytes = Convert.FromBase64String(base64String);
173 |
174 | var rsaParameters=new RSAParameters();
175 |
176 | using (BinaryReader binr = new BinaryReader(new MemoryStream(base64Bytes)))
177 | {
178 | byte bt = 0;
179 | ushort twobytes = 0;
180 | twobytes = binr.ReadUInt16();
181 | if (twobytes == 0x8130)
182 | binr.ReadByte();
183 | else if (twobytes == 0x8230)
184 | binr.ReadInt16();
185 | else
186 | throw new Exception("Unexpected value read binr.ReadUInt16()");
187 |
188 | twobytes = binr.ReadUInt16();
189 | if (twobytes != 0x0102)
190 | throw new Exception("Unexpected version");
191 |
192 | bt = binr.ReadByte();
193 | if (bt != 0x00)
194 | throw new Exception("Unexpected value read binr.ReadByte()");
195 |
196 | rsaParameters.Modulus = binr.ReadBytes(GetIntegerSize(binr));
197 | rsaParameters.Exponent = binr.ReadBytes(GetIntegerSize(binr));
198 | rsaParameters.D = binr.ReadBytes(GetIntegerSize(binr));
199 | rsaParameters.P = binr.ReadBytes(GetIntegerSize(binr));
200 | rsaParameters.Q = binr.ReadBytes(GetIntegerSize(binr));
201 | rsaParameters.DP = binr.ReadBytes(GetIntegerSize(binr));
202 | rsaParameters.DQ = binr.ReadBytes(GetIntegerSize(binr));
203 | rsaParameters.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
204 | }
205 |
206 | rsa.ImportParameters(rsaParameters);
207 | }
208 |
209 | ///
210 | /// 从公钥Base64字符串中获取RSA
211 | ///
212 | /// RSA
213 | /// Base64字符串
214 | public static void FromBase64StringByPublicKey(this RSA rsa, string base64String)
215 | {
216 | // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
217 | byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
218 | byte[] seq = new byte[15];
219 |
220 | var x509Key = System.Convert.FromBase64String(base64String);
221 |
222 | // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------
223 | using (MemoryStream mem = new MemoryStream(x509Key))
224 | {
225 | using (BinaryReader binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading
226 | {
227 | byte bt = 0;
228 | ushort twobytes = 0;
229 |
230 | twobytes = binr.ReadUInt16();
231 | if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
232 | binr.ReadByte(); //advance 1 byte
233 | else if (twobytes == 0x8230)
234 | binr.ReadInt16(); //advance 2 bytes
235 | else
236 | return;
237 |
238 | seq = binr.ReadBytes(15); //read the Sequence OID
239 | if (!CompareBytearrays(seq, seqOid)) //make sure Sequence for OID is correct
240 | return;
241 |
242 | twobytes = binr.ReadUInt16();
243 | if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
244 | binr.ReadByte(); //advance 1 byte
245 | else if (twobytes == 0x8203)
246 | binr.ReadInt16(); //advance 2 bytes
247 | else
248 | return;
249 |
250 | bt = binr.ReadByte();
251 | if (bt != 0x00) //expect null byte next
252 | return;
253 |
254 | twobytes = binr.ReadUInt16();
255 | if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
256 | binr.ReadByte(); //advance 1 byte
257 | else if (twobytes == 0x8230)
258 | binr.ReadInt16(); //advance 2 bytes
259 | else
260 | return;
261 |
262 | twobytes = binr.ReadUInt16();
263 | byte lowbyte = 0x00;
264 | byte highbyte = 0x00;
265 |
266 | if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
267 | lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
268 | else if (twobytes == 0x8202)
269 | {
270 | highbyte = binr.ReadByte(); //advance 2 bytes
271 | lowbyte = binr.ReadByte();
272 | }
273 | else
274 | return;
275 | byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order
276 | int modsize = BitConverter.ToInt32(modint, 0);
277 |
278 | int firstbyte = binr.PeekChar();
279 | if (firstbyte == 0x00)
280 | { //if first byte (highest order) of modulus is zero, don't include it
281 | binr.ReadByte(); //skip this null byte
282 | modsize -= 1; //reduce modulus buffer size by 1
283 | }
284 |
285 | byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes
286 |
287 | if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data
288 | return;
289 | int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values)
290 | byte[] exponent = binr.ReadBytes(expbytes);
291 |
292 | // ------- create RSACryptoServiceProvider instance and initialize with public key -----
293 | RSAParameters rsaKeyInfo = new RSAParameters
294 | {
295 | Modulus = modulus,
296 | Exponent = exponent
297 | };
298 | rsa.ImportParameters(rsaKeyInfo);
299 | }
300 |
301 | }
302 | }
303 |
304 | #region 导入密钥算法
305 |
306 | private static int GetIntegerSize(BinaryReader binr)
307 | {
308 | byte bt = 0;
309 | int count = 0;
310 | bt = binr.ReadByte();
311 | if (bt != 0x02)
312 | return 0;
313 | bt = binr.ReadByte();
314 |
315 | if (bt == 0x81)
316 | count = binr.ReadByte();
317 | else
318 | if (bt == 0x82)
319 | {
320 | var highbyte = binr.ReadByte();
321 | var lowbyte = binr.ReadByte();
322 | byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
323 | count = BitConverter.ToInt32(modint, 0);
324 | }
325 | else
326 | {
327 | count = bt;
328 | }
329 |
330 | while (binr.ReadByte() == 0x00)
331 | {
332 | count -= 1;
333 | }
334 | binr.BaseStream.Seek(-1, SeekOrigin.Current);
335 | return count;
336 | }
337 |
338 | private static bool CompareBytearrays(byte[] a, byte[] b)
339 | {
340 | if (a.Length != b.Length)
341 | return false;
342 | int i = 0;
343 | foreach (byte c in a)
344 | {
345 | if (c != b[i])
346 | return false;
347 | i++;
348 | }
349 | return true;
350 | }
351 |
352 | #endregion
353 | }
354 | }
355 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Core/Internals/RSAParametersJson.cs:
--------------------------------------------------------------------------------
1 | namespace Bing.Encryption.Core.Internals
2 | {
3 | ///
4 | /// RSA 参数Json
5 | ///
6 | internal class RSAParametersJson
7 | {
8 | ///
9 | /// 表示 RSA 算法的 Modulus 参数
10 | ///
11 | public string Modulus { get; set; }
12 |
13 | ///
14 | /// 表示 RSA 算法的 Exponent 参数
15 | ///
16 | public string Exponent { get; set; }
17 |
18 | ///
19 | /// 表示 RSA 算法的 P 参数
20 | ///
21 | public string P { get; set; }
22 |
23 | ///
24 | /// 表示 RSA 算法的 Q 参数
25 | ///
26 | public string Q { get; set; }
27 |
28 | ///
29 | /// 表示 RSA 算法的 DP 参数
30 | ///
31 | public string DP { get; set; }
32 |
33 | ///
34 | /// 表示 RSA 算法的 DQ 参数
35 | ///
36 | public string DQ { get; set; }
37 |
38 | ///
39 | /// 表示 RSA 算法的 InverseQ 参数
40 | ///
41 | public string InverseQ { get; set; }
42 |
43 | ///
44 | /// 表示 RSA 算法的 D 参数
45 | ///
46 | public string D { get; set; }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Core/Internals/RandomStringGenerator.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Security.Cryptography;
3 | using System.Text;
4 |
5 | namespace Bing.Encryption.Core.Internals
6 | {
7 | ///
8 | /// 随机字符串生成器
9 | ///
10 | internal static class RandomStringGenerator
11 | {
12 | ///
13 | /// 字符串字典长度
14 | ///
15 | private static readonly int StringDictionaryLength;
16 |
17 | ///
18 | /// 字符串字典
19 | ///
20 | private const string STRING_DICTIONARY =
21 | "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
22 |
23 | ///
24 | /// 初始化一个类型的静态实例
25 | ///
26 | static RandomStringGenerator()
27 | {
28 | StringDictionaryLength = STRING_DICTIONARY.Length;
29 | }
30 |
31 | ///
32 | /// 生成字符串
33 | ///
34 | /// 字符串长度,默认为8
35 | ///
36 | public static string Generate(int bits = 8)
37 | {
38 | var builder=new StringBuilder();
39 |
40 | var b = new byte[4];
41 | using (var provider=new RNGCryptoServiceProvider())
42 | {
43 | provider.GetBytes(b);
44 | }
45 |
46 | var random=new Random(BitConverter.ToInt32(b,0));
47 |
48 | for (int i = 0; i < bits; i++)
49 | {
50 | builder.Append(STRING_DICTIONARY.Substring(random.Next(0, StringDictionaryLength), 1));
51 | }
52 |
53 | return builder.ToString();
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Core/OutType.cs:
--------------------------------------------------------------------------------
1 | namespace Bing.Encryption.Core
2 | {
3 | ///
4 | /// 输出类型
5 | ///
6 | public enum OutType
7 | {
8 | ///
9 | /// Base64字符串
10 | ///
11 | Base64,
12 | ///
13 | /// 16进制字符串
14 | ///
15 | Hex
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Core/SHAHashingBase.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Security.Cryptography;
3 | using System.Text;
4 | using Bing.Encryption.Core.Internals.Extensions;
5 |
6 | namespace Bing.Encryption.Core
7 | {
8 | ///
9 | /// SHA哈希加密基类
10 | ///
11 | // ReSharper disable once InconsistentNaming
12 | public abstract class SHAHashingBase
13 | {
14 | ///
15 | /// 加密
16 | ///
17 | /// 哈希算法类型
18 | /// 待加密的值
19 | /// 编码
20 | /// 输出类型
21 | ///
22 | protected static string Encrypt(string value, Encoding encoding = null, OutType outType = OutType.Hex)
23 | where T : HashAlgorithm, new()
24 | {
25 | if (value == null)
26 | {
27 | throw new ArgumentNullException(nameof(value));
28 | }
29 |
30 | if (encoding == null)
31 | {
32 | encoding = Encoding.UTF8;
33 | }
34 |
35 | using (HashAlgorithm hash = new T())
36 | {
37 | var bytes = hash.ComputeHash(encoding.GetBytes(value));
38 |
39 | return outType == OutType.Base64 ? Convert.ToBase64String(bytes) : bytes.ToHexString();
40 | }
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Core/SymmetricEncryptionBase.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Security.Cryptography;
4 | using System.Text;
5 |
6 | namespace Bing.Encryption.Core
7 | {
8 | ///
9 | /// 对称加密基类
10 | ///
11 | public abstract class SymmetricEncryptionBase
12 | {
13 | ///
14 | /// 获取真实 Key/IV 的值
15 | ///
16 | ///
17 | protected static Func>>> ComputeRealValueFunc() =>
18 | originString => salt => encoding =>
19 | size =>
20 | {
21 | if (string.IsNullOrWhiteSpace(originString))
22 | {
23 | return new byte[] {0};
24 | }
25 |
26 | if (encoding == null)
27 | {
28 | encoding = Encoding.UTF8;
29 | }
30 |
31 | var len = size / 8;
32 |
33 | if (string.IsNullOrWhiteSpace(salt))
34 | {
35 | var retBytes = new byte[len];
36 | Array.Copy(encoding.GetBytes(originString.PadRight(len)), retBytes, len);
37 | return retBytes;
38 | }
39 |
40 | var saltBytes = encoding.GetBytes(salt);
41 | var rfcOriginStringData = new Rfc2898DeriveBytes(encoding.GetBytes(originString), saltBytes, 1000);
42 | return rfcOriginStringData.GetBytes(len);
43 | };
44 |
45 | ///
46 | /// 核心加密方法
47 | ///
48 | /// 对称加密算法类型
49 | /// 待加密的字节数组
50 | /// 密钥字节数组
51 | /// 偏移量字节数组
52 | ///
53 | protected static byte[] EncryptCore(byte[] sourceBytes, byte[] keyBytes, byte[] ivBytes)
54 | where TCryptoServiceProvider : SymmetricAlgorithm, new()
55 | {
56 | using (var provider=new TCryptoServiceProvider())
57 | {
58 | provider.Key = keyBytes;
59 | provider.IV = ivBytes;
60 | using (MemoryStream ms=new MemoryStream())
61 | {
62 | using (CryptoStream cs=new CryptoStream(ms,provider.CreateEncryptor(),CryptoStreamMode.Write))
63 | {
64 | cs.Write(sourceBytes,0,sourceBytes.Length);
65 | cs.FlushFinalBlock();
66 | return ms.ToArray();
67 | }
68 | }
69 | }
70 | }
71 |
72 | ///
73 | /// 核心解密方法
74 | ///
75 | /// 对称加密算法类型
76 | /// 待解密的字节数组
77 | /// 密钥字节数组
78 | /// 偏移量字节数组
79 | ///
80 | protected static byte[] DecryptCore(byte[] encryptBytes, byte[] keyBytes,
81 | byte[] ivBytes) where TCryptoServiceProvider : SymmetricAlgorithm, new()
82 | {
83 | using (var provider = new TCryptoServiceProvider())
84 | {
85 | provider.Key = keyBytes;
86 | provider.IV = ivBytes;
87 | using (MemoryStream ms = new MemoryStream())
88 | {
89 | using (CryptoStream cs = new CryptoStream(ms, provider.CreateDecryptor(), CryptoStreamMode.Write))
90 | {
91 | cs.Write(encryptBytes, 0, encryptBytes.Length);
92 | cs.FlushFinalBlock();
93 | return ms.ToArray();
94 | }
95 | }
96 | }
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Hash/HMAC/HMACMD5HashingProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 | using System.Text;
3 | using Bing.Encryption.Core;
4 |
5 | // ReSharper disable once CheckNamespace
6 | namespace Bing.Encryption
7 | {
8 | ///
9 | /// HMAC_MD5 哈希加密提供程序
10 | ///
11 | public sealed class HMACMD5HashingProvider:HMACHashingBase
12 | {
13 | ///
14 | /// 初始化一个类型的实例
15 | ///
16 | private HMACMD5HashingProvider() { }
17 |
18 | ///
19 | /// 获取字符串的 HMAC_MD5 哈希值,默认编码为
20 | ///
21 | /// 待加密的值
22 | /// 密钥
23 | /// 输出类型,默认为
24 | /// 编码类型,默认为
25 | ///
26 | public static string Signature(string value, string key, OutType outType = OutType.Hex,
27 | Encoding encoding = null) => Encrypt(value, key, encoding, outType);
28 |
29 | ///
30 | /// 验证签名
31 | ///
32 | /// 对比的值
33 | /// 待加密的值
34 | /// 密钥
35 | /// 输出类型,默认为
36 | /// 编码类型,默认为
37 | ///
38 | public static bool Verify(string comparison, string value, string key, OutType outType = OutType.Hex,
39 | Encoding encoding = null) => comparison == Signature(value, key, outType, encoding);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Hash/HMAC/HMACSHA1HashingProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 | using System.Text;
3 | using Bing.Encryption.Core;
4 |
5 | // ReSharper disable once CheckNamespace
6 | namespace Bing.Encryption
7 | {
8 | ///
9 | /// HMAC_SHA1 哈希加密提供程序
10 | ///
11 | public sealed class HMACSHA1HashingProvider : HMACHashingBase
12 | {
13 | ///
14 | /// 初始化一个类型的实例
15 | ///
16 | private HMACSHA1HashingProvider() { }
17 |
18 | ///
19 | /// 获取字符串的 HMAC_SHA1 哈希值,默认编码为
20 | ///
21 | /// 待加密的值
22 | /// 密钥
23 | /// 输出类型,默认为
24 | /// 编码类型,默认为
25 | ///
26 | public static string Signature(string value, string key, OutType outType = OutType.Hex,
27 | Encoding encoding = null) => Encrypt(value, key, encoding, outType);
28 |
29 | ///
30 | /// 验证签名
31 | ///
32 | /// 对比的值
33 | /// 待加密的值
34 | /// 密钥
35 | /// 输出类型,默认为
36 | /// 编码类型,默认为
37 | ///
38 | public static bool Verify(string comparison, string value, string key, OutType outType = OutType.Hex,
39 | Encoding encoding = null) => comparison == Signature(value, key, outType, encoding);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Hash/HMAC/HMACSHA256HashingProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 | using System.Text;
3 | using Bing.Encryption.Core;
4 |
5 | // ReSharper disable once CheckNamespace
6 | namespace Bing.Encryption
7 | {
8 | ///
9 | /// HMAC_SHA256 哈希加密提供程序
10 | ///
11 | public sealed class HMACSHA256HashingProvider : HMACHashingBase
12 | {
13 | ///
14 | /// 初始化一个类型的实例
15 | ///
16 | private HMACSHA256HashingProvider() { }
17 |
18 | ///
19 | /// 获取字符串的 HMAC_SHA256 哈希值,默认编码为
20 | ///
21 | /// 待加密的值
22 | /// 密钥
23 | /// 输出类型,默认为
24 | /// 编码类型,默认为
25 | ///
26 | public static string Signature(string value, string key, OutType outType = OutType.Hex,
27 | Encoding encoding = null) => Encrypt(value, key, encoding, outType);
28 |
29 | ///
30 | /// 验证签名
31 | ///
32 | /// 对比的值
33 | /// 待加密的值
34 | /// 密钥
35 | /// 输出类型,默认为
36 | /// 编码类型,默认为
37 | ///
38 | public static bool Verify(string comparison, string value, string key, OutType outType = OutType.Hex,
39 | Encoding encoding = null) => comparison == Signature(value, key, outType, encoding);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Hash/HMAC/HMACSHA384HashingProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 | using System.Text;
3 | using Bing.Encryption.Core;
4 |
5 | // ReSharper disable once CheckNamespace
6 | namespace Bing.Encryption
7 | {
8 | ///
9 | /// HMAC_SHA384 哈希加密提供程序
10 | ///
11 | public sealed class HMACSHA384HashingProvider : HMACHashingBase
12 | {
13 | ///
14 | /// 初始化一个类型的实例
15 | ///
16 | private HMACSHA384HashingProvider() { }
17 |
18 | ///
19 | /// 获取字符串的 HMAC_SHA384 哈希值,默认编码为
20 | ///
21 | /// 待加密的值
22 | /// 密钥
23 | /// 输出类型,默认为
24 | /// 编码类型,默认为
25 | ///
26 | public static string Signature(string value, string key, OutType outType = OutType.Hex,
27 | Encoding encoding = null) => Encrypt(value, key, encoding, outType);
28 |
29 | ///
30 | /// 验证签名
31 | ///
32 | /// 对比的值
33 | /// 待加密的值
34 | /// 密钥
35 | /// 输出类型,默认为
36 | /// 编码类型,默认为
37 | ///
38 | public static bool Verify(string comparison, string value, string key, OutType outType = OutType.Hex,
39 | Encoding encoding = null) => comparison == Signature(value, key, outType, encoding);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Hash/HMAC/HMACSHA512HashingProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 | using System.Text;
3 | using Bing.Encryption.Core;
4 |
5 | // ReSharper disable once CheckNamespace
6 | namespace Bing.Encryption
7 | {
8 | ///
9 | /// HMAC_SHA512 哈希加密提供程序
10 | ///
11 | public sealed class HMACSHA512HashingProvider : HMACHashingBase
12 | {
13 | ///
14 | /// 初始化一个类型的实例
15 | ///
16 | private HMACSHA512HashingProvider() { }
17 |
18 | ///
19 | /// 获取字符串的 HMAC_SHA512 哈希值,默认编码为
20 | ///
21 | /// 待加密的值
22 | /// 密钥
23 | /// 输出类型,默认为
24 | /// 编码类型,默认为
25 | ///
26 | public static string Signature(string value, string key, OutType outType = OutType.Hex,
27 | Encoding encoding = null) => Encrypt(value, key, encoding, outType);
28 |
29 | ///
30 | /// 验证签名
31 | ///
32 | /// 对比的值
33 | /// 待加密的值
34 | /// 密钥
35 | /// 输出类型,默认为
36 | /// 编码类型,默认为
37 | ///
38 | public static bool Verify(string comparison, string value, string key, OutType outType = OutType.Hex,
39 | Encoding encoding = null) => comparison == Signature(value, key, outType, encoding);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Hash/MD4/MD4CryptoServiceProvider.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Security.Cryptography;
5 |
6 | // ReSharper disable once CheckNamespace
7 | namespace Bing.Encryption
8 | {
9 | ///
10 | /// MD4 加密服务提供程序
11 | /// 参考:https://bitlush.com/blog/md4-hash-algorithm-in-c-sharp
12 | ///
13 | public sealed class MD4CryptoServiceProvider : HashAlgorithm
14 | {
15 | private uint _a;
16 | private uint _b;
17 | private uint _c;
18 | private uint _d;
19 | private readonly uint[] _x;
20 | private int _bytesProcessed;
21 |
22 | ///
23 | /// 初始化一个类型的实例
24 | ///
25 | public MD4CryptoServiceProvider()
26 | {
27 | _x = new uint[16];
28 | Initialize();
29 | }
30 |
31 | ///
32 | /// 初始化
33 | ///
34 | public override void Initialize()
35 | {
36 | _a = 0x67452301;
37 | _b = 0xefcdab89;
38 | _c = 0x98badcfe;
39 | _d = 0x10325476;
40 |
41 | _bytesProcessed = 0;
42 | }
43 |
44 | ///
45 | /// 核心Hash算法
46 | ///
47 | protected override void HashCore(byte[] array, int offset, int length)
48 | {
49 | ProcessMessage(Bytes(array, offset, length));
50 | }
51 |
52 | ///
53 | /// Hash完成
54 | ///
55 | ///
56 | protected override byte[] HashFinal()
57 | {
58 | try
59 | {
60 | ProcessMessage(Padding());
61 | return new[] {_a, _b, _c, _d}.SelectMany(word => Bytes(word)).ToArray();
62 | }
63 | finally
64 | {
65 | Initialize();
66 | }
67 | }
68 |
69 | ///
70 | /// 处理消息
71 | ///
72 | private void ProcessMessage(IEnumerable bytes)
73 | {
74 | foreach (var b in bytes)
75 | {
76 | int c = _bytesProcessed & 63;
77 | int i = c >> 2;
78 | int s = (c & 3) << 3;
79 |
80 | _x[i] = (_x[i] & ~((uint) 255 << s)) | ((uint) b << s);
81 |
82 | if (c == 63)
83 | {
84 | Process16WordBlock();
85 | }
86 |
87 | _bytesProcessed++;
88 | }
89 | }
90 |
91 | ///
92 | /// 获取字节数组
93 | ///
94 | private static IEnumerable Bytes(byte[] bytes, int offset, int length)
95 | {
96 | for (var i = offset; i < length; i++)
97 | {
98 | yield return bytes[i];
99 | }
100 | }
101 |
102 | ///
103 | /// 获取字节数组
104 | ///
105 | private IEnumerable Bytes(uint word)
106 | {
107 | yield return (byte) (word & 255);
108 | yield return (byte) ((word >> 8) & 255);
109 | yield return (byte) ((word >> 16) & 255);
110 | yield return (byte) ((word >> 24) & 255);
111 | }
112 |
113 | ///
114 | /// 重复
115 | ///
116 | private IEnumerable Repeat(byte value, int count)
117 | {
118 | for (var i = 0; i < count; i++)
119 | {
120 | yield return value;
121 | }
122 | }
123 |
124 | ///
125 | /// 填充
126 | ///
127 | ///
128 | private IEnumerable Padding()
129 | {
130 | return Repeat(128, 1)
131 | .Concat(Repeat(0, ((_bytesProcessed + 8) & 0x7fffffc0) + 55 - _bytesProcessed))
132 | .Concat(Bytes((uint) _bytesProcessed << 3))
133 | .Concat(Repeat(0, 4));
134 | }
135 |
136 | ///
137 | /// 处理16个块
138 | ///
139 | private void Process16WordBlock()
140 | {
141 | uint aa = _a;
142 | uint bb = _b;
143 | uint cc = _c;
144 | uint dd = _d;
145 |
146 | foreach (int k in new[] { 0, 4, 8, 12 })
147 | {
148 | aa = Round1Operation(aa, bb, cc, dd, _x[k], 3);
149 | dd = Round1Operation(dd, aa, bb, cc, _x[k + 1], 7);
150 | cc = Round1Operation(cc, dd, aa, bb, _x[k + 2], 11);
151 | bb = Round1Operation(bb, cc, dd, aa, _x[k + 3], 19);
152 | }
153 |
154 | foreach (int k in new[] { 0, 1, 2, 3 })
155 | {
156 | aa = Round2Operation(aa, bb, cc, dd, _x[k], 3);
157 | dd = Round2Operation(dd, aa, bb, cc, _x[k + 4], 5);
158 | cc = Round2Operation(cc, dd, aa, bb, _x[k + 8], 9);
159 | bb = Round2Operation(bb, cc, dd, aa, _x[k + 12], 13);
160 | }
161 |
162 | foreach (int k in new[] { 0, 2, 1, 3 })
163 | {
164 | aa = Round3Operation(aa, bb, cc, dd, _x[k], 3);
165 | dd = Round3Operation(dd, aa, bb, cc, _x[k + 8], 9);
166 | cc = Round3Operation(cc, dd, aa, bb, _x[k + 4], 11);
167 | bb = Round3Operation(bb, cc, dd, aa, _x[k + 12], 15);
168 | }
169 |
170 | unchecked
171 | {
172 | _a += aa;
173 | _b += bb;
174 | _c += cc;
175 | _d += dd;
176 | }
177 | }
178 |
179 | ///
180 | /// 轮操作处理
181 | ///
182 | // ReSharper disable once InconsistentNaming
183 | private static uint ROL(uint value, int numberOfBits)
184 | {
185 | return (value << numberOfBits) | (value >> (32 - numberOfBits));
186 | }
187 |
188 | ///
189 | /// 第1轮操作
190 | ///
191 | private static uint Round1Operation(uint a, uint b, uint c, uint d, uint xk, int s)
192 | {
193 | unchecked
194 | {
195 | return ROL(a + ((b & c) | (~b & d)) + xk, s);
196 | }
197 | }
198 |
199 | ///
200 | /// 第2轮操作
201 | ///
202 | private static uint Round2Operation(uint a, uint b, uint c, uint d, uint xk, int s)
203 | {
204 | unchecked
205 | {
206 | return ROL(a + ((b & c) | (b & d) | (c & d)) + xk + 0x5a827999, s);
207 | }
208 | }
209 |
210 | ///
211 | /// 第3轮操作
212 | ///
213 | private static uint Round3Operation(uint a, uint b, uint c, uint d, uint xk, int s)
214 | {
215 | unchecked
216 | {
217 | return ROL(a + (b ^ c ^ d) + xk + 0x6ed9eba1, s);
218 | }
219 | }
220 | }
221 | }
222 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Hash/MD4/MD4HashingProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Text;
2 | using Bing.Encryption.Core.Internals.Extensions;
3 |
4 | // ReSharper disable once CheckNamespace
5 | namespace Bing.Encryption
6 | {
7 | ///
8 | /// MD4 哈希加密提供程序
9 | ///
10 | // ReSharper disable once InconsistentNaming
11 | public static class MD4HashingProvider
12 | {
13 | ///
14 | /// 获取字符串的 MD4 哈希值,默认编码为
15 | ///
16 | /// 待加密的值
17 | /// 编码类型,默认为
18 | ///
19 | public static string Signature(string value, Encoding encoding = null)
20 | {
21 | return SignatureHash(value, encoding).ToHexString();
22 | }
23 |
24 | ///
25 | /// 获取字符串的 MD4 哈希值
26 | ///
27 | /// 待加密的字节数组
28 | ///
29 | public static string Signature(byte[] value)
30 | {
31 | return Core(value).ToHexString();
32 | }
33 |
34 | ///
35 | /// 获取字节数组的 MD4 哈希值,默认编码为
36 | ///
37 | /// 待加密的值
38 | /// 编码类型,默认为
39 | ///
40 | public static byte[] SignatureHash(string value, Encoding encoding = null)
41 | {
42 | if (encoding == null)
43 | {
44 | encoding = Encoding.UTF8;
45 | }
46 |
47 | return Core(encoding.GetBytes(value));
48 | }
49 |
50 | ///
51 | /// 获取字节数组的 MD4 哈希值
52 | ///
53 | /// 待加密的字节数组
54 | ///
55 | public static byte[] SignatureHash(byte[] value)
56 | {
57 | return Core(value);
58 | }
59 |
60 | ///
61 | /// 核心加密算法
62 | ///
63 | /// 待加密的值
64 | ///
65 | private static byte[] Core(byte[] value)
66 | {
67 | using (var md4 = new MD4CryptoServiceProvider())
68 | {
69 | return md4.ComputeHash(value);
70 | }
71 | }
72 |
73 | ///
74 | /// 验证签名
75 | ///
76 | /// 对比的值
77 | /// 待加密的值
78 | /// 编码类型,默认为
79 | ///
80 | public static bool Verify(string comparison, string value, Encoding encoding = null) =>
81 | comparison == Signature(value, encoding);
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Hash/MD5/MD5BitType.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable once CheckNamespace
2 | namespace Bing.Encryption.Hash
3 | {
4 | ///
5 | /// MD5字节类型
6 | ///
7 | // ReSharper disable once InconsistentNaming
8 | public enum MD5BitType
9 | {
10 | L16,
11 | L32,
12 | L64
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Hash/MD5/MD5HasingProvider.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Security.Cryptography;
3 | using System.Text;
4 | using Bing.Encryption.Core.Internals.Extensions;
5 | using Bing.Encryption.Hash;
6 |
7 | // ReSharper disable once CheckNamespace
8 | namespace Bing.Encryption
9 | {
10 | ///
11 | /// MD5 哈希加密提供程序
12 | ///
13 | // ReSharper disable once InconsistentNaming
14 | public static class MD5HasingProvider
15 | {
16 | ///
17 | /// 获取字符串的 MD5 哈希值,默认编码为
18 | ///
19 | /// 待加密的值
20 | /// MD5加密类型,默认为
21 | /// 编码类型,默认为
22 | ///
23 | public static string Signature(string value, MD5BitType bitType = MD5BitType.L32, Encoding encoding = null)
24 | {
25 | if (value == null)
26 | {
27 | throw new ArgumentNullException(nameof(value));
28 | }
29 |
30 | if (encoding == null)
31 | {
32 | encoding = Encoding.UTF8;
33 | }
34 |
35 | switch (bitType)
36 | {
37 | case MD5BitType.L16:
38 | return Encrypt16Func()(value)(encoding);
39 | case MD5BitType.L32:
40 | return Encrypt32Func()(value)(encoding);
41 | case MD5BitType.L64:
42 | return Encrypt64Func()(value)(encoding);
43 | default:
44 | throw new ArgumentOutOfRangeException(nameof(bitType), bitType, null);
45 | }
46 | }
47 |
48 | ///
49 | /// 预加密
50 | ///
51 | ///
52 | private static Func> PreencryptFunc() => str => encoding =>
53 | {
54 | using (var md5 = MD5.Create())
55 | {
56 | return md5.ComputeHash(encoding.GetBytes(str));
57 | }
58 | };
59 |
60 | ///
61 | /// 16位加密
62 | ///
63 | ///
64 | private static Func> Encrypt16Func() => str =>
65 | encoding => BitConverter.ToString(PreencryptFunc()(str)(encoding), 4, 8).Replace("-", "");
66 |
67 | ///
68 | /// 32位加密
69 | ///
70 | ///
71 | private static Func> Encrypt32Func() => str => encoding =>
72 | {
73 | var bytes = PreencryptFunc()(str)(encoding);
74 | return bytes.ToHexString();
75 | };
76 |
77 | ///
78 | /// 64位加密
79 | ///
80 | ///
81 | private static Func> Encrypt64Func() => str =>
82 | encoding => Convert.ToBase64String(PreencryptFunc()(str)(encoding));
83 |
84 | ///
85 | /// 验证签名
86 | ///
87 | /// 对比的值
88 | /// 待加密的值
89 | /// MD5加密类型,默认为
90 | /// 编码类型,默认为
91 | ///
92 | public static bool Verify(string comparison, string value, MD5BitType bitType = MD5BitType.L32,
93 | Encoding encoding = null) => comparison == Signature(value, bitType, encoding);
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Hash/SHA/SHA1HashingProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 | using System.Text;
3 | using Bing.Encryption.Core;
4 |
5 | // ReSharper disable once CheckNamespace
6 | namespace Bing.Encryption
7 | {
8 | ///
9 | /// SHA1 哈希加密提供程序
10 | ///
11 | public sealed class SHA1HashingProvider:SHAHashingBase
12 | {
13 | ///
14 | /// 初始化一个类型的实例
15 | ///
16 | private SHA1HashingProvider() { }
17 |
18 | ///
19 | /// 获取字符串的 SHA1 哈希值,默认编码为
20 | ///
21 | /// 待加密的值
22 | /// 输出类型,默认为
23 | /// 编码类型,默认为
24 | ///
25 | public static string Signature(string value, OutType outType = OutType.Hex, Encoding encoding = null) =>
26 | Encrypt(value, encoding, outType);
27 |
28 | ///
29 | /// 验证签名
30 | ///
31 | /// 对比的值
32 | /// 待加密的值
33 | /// 输出类型,默认为
34 | /// 编码类型,默认为
35 | ///
36 | public static bool Verify(string comparison, string value, OutType outType = OutType.Hex,
37 | Encoding encoding = null) => comparison == Signature(value, outType, encoding);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Hash/SHA/SHA256HashingProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 | using System.Text;
3 | using Bing.Encryption.Core;
4 |
5 | // ReSharper disable once CheckNamespace
6 | namespace Bing.Encryption
7 | {
8 | ///
9 | /// SHA256 哈希加密提供程序
10 | ///
11 | public sealed class SHA256HashingProvider:SHAHashingBase
12 | {
13 | ///
14 | /// 初始化一个类型的实例
15 | ///
16 | private SHA256HashingProvider() { }
17 |
18 | ///
19 | /// 获取字符串的 SHA256 哈希值,默认编码为
20 | ///
21 | /// 待加密的值
22 | /// 输出类型,默认为
23 | /// 编码类型,默认为
24 | ///
25 | public static string Signature(string value, OutType outType = OutType.Hex, Encoding encoding = null) =>
26 | Encrypt(value, encoding, outType);
27 |
28 | ///
29 | /// 验证签名
30 | ///
31 | /// 对比的值
32 | /// 待加密的值
33 | /// 输出类型,默认为
34 | /// 编码类型,默认为
35 | ///
36 | public static bool Verify(string comparison, string value, OutType outType = OutType.Hex,
37 | Encoding encoding = null) => comparison == Signature(value, outType, encoding);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Hash/SHA/SHA384HashingProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 | using System.Text;
3 | using Bing.Encryption.Core;
4 |
5 | // ReSharper disable once CheckNamespace
6 | namespace Bing.Encryption
7 | {
8 | ///
9 | /// SHA384 哈希加密提供程序
10 | ///
11 | public sealed class SHA384HashingProvider:SHAHashingBase
12 | {
13 | ///
14 | /// 初始化一个类型的实例
15 | ///
16 | private SHA384HashingProvider() { }
17 |
18 | ///
19 | /// 获取字符串的 SHA384 哈希值,默认编码为
20 | ///
21 | /// 待加密的值
22 | /// 输出类型,默认为
23 | /// 编码类型,默认为
24 | ///
25 | public static string Signature(string value, OutType outType = OutType.Hex, Encoding encoding = null) =>
26 | Encrypt(value, encoding, outType);
27 |
28 | ///
29 | /// 验证签名
30 | ///
31 | /// 对比的值
32 | /// 待加密的值
33 | /// 输出类型,默认为
34 | /// 编码类型,默认为
35 | ///
36 | public static bool Verify(string comparison, string value, OutType outType = OutType.Hex,
37 | Encoding encoding = null) => comparison == Signature(value, outType, encoding);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Hash/SHA/SHA512HashingProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 | using System.Text;
3 | using Bing.Encryption.Core;
4 |
5 | // ReSharper disable once CheckNamespace
6 | namespace Bing.Encryption
7 | {
8 | ///
9 | /// SHA512 哈希加密提供程序
10 | ///
11 | public sealed class SHA512HashingProvider : SHAHashingBase
12 | {
13 | ///
14 | /// 初始化一个类型的实例
15 | ///
16 | private SHA512HashingProvider() { }
17 |
18 | ///
19 | /// 获取字符串的 SHA512 哈希值,默认编码为
20 | ///
21 | /// 待加密的值
22 | /// 输出类型,默认为
23 | /// 编码类型,默认为
24 | ///
25 | public static string Signature(string value, OutType outType = OutType.Hex, Encoding encoding = null) =>
26 | Encrypt(value, encoding, outType);
27 |
28 | ///
29 | /// 验证签名
30 | ///
31 | /// 对比的值
32 | /// 待加密的值
33 | /// 输出类型,默认为
34 | /// 编码类型,默认为
35 | ///
36 | public static bool Verify(string comparison, string value, OutType outType = OutType.Hex,
37 | Encoding encoding = null) => comparison == Signature(value, outType, encoding);
38 | }
39 | }
--------------------------------------------------------------------------------
/src/Bing.Encryption/Symmetric/AES/AESEncryptionProvider.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Security.Cryptography;
3 | using System.Text;
4 | using Bing.Encryption.Core;
5 | using Bing.Encryption.Core.Internals.Extensions;
6 |
7 | // ReSharper disable once CheckNamespace
8 | namespace Bing.Encryption
9 | {
10 | ///
11 | /// AES 加密提供程序
12 | ///
13 | public sealed class AESEncryptionProvider:SymmetricEncryptionBase
14 | {
15 | ///
16 | /// 初始化一个类型的实例
17 | ///
18 | private AESEncryptionProvider() { }
19 |
20 | ///
21 | /// 创建 AES 密钥
22 | ///
23 | /// 密钥长度类型,默认为
24 | /// 编码类型,默认为
25 | ///
26 | public static AESKey CreateKey(AESKeySizeType size = AESKeySizeType.L256, Encoding encoding = null)
27 | {
28 | if (encoding == null)
29 | {
30 | encoding = Encoding.UTF8;
31 | }
32 |
33 | using (var provider=new AesCryptoServiceProvider(){KeySize = (int)size})
34 | {
35 | return new AESKey()
36 | {
37 | Key = encoding.GetString(provider.Key),
38 | IV = encoding.GetString(provider.IV),
39 | Size = size
40 | };
41 | }
42 | }
43 |
44 | ///
45 | /// 加密
46 | ///
47 | /// 待加密的值
48 | /// 密钥
49 | /// 加密偏移量
50 | /// 加盐
51 | /// 输出类型,默认为
52 | /// 编码类型,默认为
53 | /// 密钥长度类型,默认为
54 | ///
55 | public static string Encrypt(string value, string key, string iv = null, string salt = null,
56 | OutType outType = OutType.Base64,
57 | Encoding encoding = null, AESKeySizeType keySize = AESKeySizeType.L256)
58 | {
59 | if (string.IsNullOrEmpty(value))
60 | {
61 | throw new ArgumentNullException(nameof(value));
62 | }
63 |
64 | if (string.IsNullOrEmpty(key))
65 | {
66 | throw new ArgumentNullException(nameof(key));
67 | }
68 |
69 | if (encoding == null)
70 | {
71 | encoding = Encoding.UTF8;
72 | }
73 |
74 | var result = EncryptCore(encoding.GetBytes(value),
75 | ComputeRealValueFunc()(key)(salt)(encoding)((int) keySize),
76 | ComputeRealValueFunc()(iv)(salt)(encoding)(128));
77 |
78 | if (outType == OutType.Base64)
79 | {
80 | return Convert.ToBase64String(result);
81 | }
82 |
83 | return result.ToHexString();
84 | }
85 |
86 | ///
87 | /// 加密
88 | ///
89 | /// 待加密的值
90 | /// AES 密钥对象
91 | /// 输出类型,默认为
92 | /// 编码类型,默认为
93 | ///
94 | public static string Encrypt(string value, AESKey key, OutType outType = OutType.Base64,
95 | Encoding encoding = null)
96 | {
97 | if (key == null)
98 | {
99 | throw new ArgumentNullException(nameof(key));
100 | }
101 |
102 | return Encrypt(value, key.Key, key.IV, outType: outType, encoding: encoding, keySize: key.Size);
103 | }
104 |
105 | ///
106 | /// 解密
107 | ///
108 | /// 待解密的值
109 | /// 密钥
110 | /// 加密偏移量
111 | /// 加盐
112 | /// 输出类型,默认为
113 | /// 编码类型,默认为
114 | /// 密钥长度类型,默认为
115 | ///
116 | public static string Decrypt(string value, string key, string iv = null, string salt = null,
117 | OutType outType = OutType.Base64,
118 | Encoding encoding = null, AESKeySizeType keySize = AESKeySizeType.L256)
119 | {
120 | if (string.IsNullOrEmpty(value))
121 | {
122 | throw new ArgumentNullException(nameof(value));
123 | }
124 |
125 | if (string.IsNullOrEmpty(key))
126 | {
127 | throw new ArgumentNullException(nameof(key));
128 | }
129 |
130 | if (encoding == null)
131 | {
132 | encoding = Encoding.UTF8;
133 | }
134 |
135 | var result = DecryptCore(value.GetEncryptBytes(outType),
136 | ComputeRealValueFunc()(key)(salt)(encoding)((int) keySize),
137 | ComputeRealValueFunc()(iv)(salt)(encoding)(128));
138 |
139 | return encoding.GetString(result);
140 | }
141 |
142 | ///
143 | /// 解密
144 | ///
145 | /// 待加密的值
146 | /// AES 密钥对象
147 | /// 输出类型,默认为
148 | /// 编码类型,默认为
149 | ///
150 | public static string Decrypt(string value, AESKey key, OutType outType = OutType.Base64,
151 | Encoding encoding = null)
152 | {
153 | if (key == null)
154 | {
155 | throw new ArgumentNullException(nameof(key));
156 | }
157 |
158 | return Decrypt(value, key.Key, key.IV, outType: outType, encoding: encoding, keySize: key.Size);
159 | }
160 | }
161 | }
162 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Symmetric/AES/AESKey.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable once CheckNamespace
2 | namespace Bing.Encryption
3 | {
4 | ///
5 | /// AES 密钥
6 | ///
7 | public class AESKey
8 | {
9 | ///
10 | /// 密钥
11 | ///
12 | public string Key { get; set; }
13 |
14 | ///
15 | /// 偏移量
16 | ///
17 | public string IV { get; set; }
18 |
19 | ///
20 | /// 密钥长度
21 | ///
22 | public AESKeySizeType Size { get; set; }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Symmetric/AES/AESKeySizeType.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable once CheckNamespace
2 | namespace Bing.Encryption
3 | {
4 | ///
5 | /// AES 密钥长度类型
6 | ///
7 | // ReSharper disable once InconsistentNaming
8 | public enum AESKeySizeType
9 | {
10 | L128=128,
11 | L192=192,
12 | L256=256
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Symmetric/DES/DESEncryptionProvider.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Security.Cryptography;
3 | using System.Text;
4 | using Bing.Encryption.Core;
5 | using Bing.Encryption.Core.Internals;
6 | using Bing.Encryption.Core.Internals.Extensions;
7 |
8 | // ReSharper disable once CheckNamespace
9 | namespace Bing.Encryption
10 | {
11 | ///
12 | /// DES 加密提供程序
13 | ///
14 | public sealed class DESEncryptionProvider : SymmetricEncryptionBase
15 | {
16 | ///
17 | /// 初始化一个类型的实例
18 | ///
19 | private DESEncryptionProvider()
20 | {
21 | }
22 |
23 | ///
24 | /// 创建 DES 密钥
25 | ///
26 | ///
27 | public static DESKey CreateKey()
28 | {
29 | return new DESKey()
30 | {
31 | Key = RandomStringGenerator.Generate(),
32 | IV = RandomStringGenerator.Generate(),
33 | };
34 | }
35 |
36 | ///
37 | /// 加密
38 | ///
39 | /// 待加密的值
40 | /// 密钥
41 | /// 加密偏移量
42 | /// 加盐
43 | /// 输出类型,默认为
44 | /// 编码类型,默认为
45 | ///
46 | public static string Encrypt(string value, string key, string iv, string salt = null,
47 | OutType outType = OutType.Base64,
48 | Encoding encoding = null)
49 | {
50 | if (string.IsNullOrEmpty(value))
51 | {
52 | throw new ArgumentNullException(nameof(value));
53 | }
54 |
55 | if (string.IsNullOrEmpty(key))
56 | {
57 | throw new ArgumentNullException(nameof(key));
58 | }
59 |
60 | if (string.IsNullOrEmpty(iv))
61 | {
62 | throw new ArgumentNullException(nameof(iv));
63 | }
64 |
65 | if (encoding == null)
66 | {
67 | encoding = Encoding.UTF8;
68 | }
69 |
70 | var result = EncryptCore(encoding.GetBytes(value),
71 | ComputeRealValueFunc()(key)(salt)(encoding)(64),
72 | ComputeRealValueFunc()(iv)(salt)(encoding)(64));
73 |
74 | if (outType == OutType.Base64)
75 | {
76 | return Convert.ToBase64String(result);
77 | }
78 |
79 | return result.ToHexString();
80 | }
81 |
82 | ///
83 | /// 加密
84 | ///
85 | /// 待加密的值
86 | /// DES 密钥对象
87 | /// 输出类型,默认为
88 | /// 编码类型,默认为
89 | ///
90 | public static string Encrypt(string value, DESKey key, OutType outType = OutType.Base64,
91 | Encoding encoding = null)
92 | {
93 | if (key == null)
94 | {
95 | throw new ArgumentNullException(nameof(key));
96 | }
97 |
98 | return Encrypt(value, key.Key, key.IV, outType: outType, encoding: encoding);
99 | }
100 |
101 | ///
102 | /// 解密
103 | ///
104 | /// 待解密的值
105 | /// 密钥
106 | /// 加密偏移量
107 | /// 加盐
108 | /// 输出类型,默认为
109 | /// 编码类型,默认为
110 | ///
111 | public static string Decrypt(string value, string key, string iv = null, string salt = null,
112 | OutType outType = OutType.Base64,
113 | Encoding encoding = null)
114 | {
115 | if (string.IsNullOrEmpty(value))
116 | {
117 | throw new ArgumentNullException(nameof(value));
118 | }
119 |
120 | if (string.IsNullOrEmpty(key))
121 | {
122 | throw new ArgumentNullException(nameof(key));
123 | }
124 |
125 | if (encoding == null)
126 | {
127 | encoding = Encoding.UTF8;
128 | }
129 |
130 | var result = DecryptCore(value.GetEncryptBytes(outType),
131 | ComputeRealValueFunc()(key)(salt)(encoding)(64),
132 | ComputeRealValueFunc()(iv)(salt)(encoding)(64));
133 |
134 | return encoding.GetString(result);
135 | }
136 |
137 | ///
138 | /// 解密
139 | ///
140 | /// 待加密的值
141 | /// DES 密钥对象
142 | /// 输出类型,默认为
143 | /// 编码类型,默认为
144 | ///
145 | public static string Decrypt(string value, DESKey key, OutType outType = OutType.Base64,
146 | Encoding encoding = null)
147 | {
148 | if (key == null)
149 | {
150 | throw new ArgumentNullException(nameof(key));
151 | }
152 |
153 | return Decrypt(value, key.Key, key.IV, outType: outType, encoding: encoding);
154 | }
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Symmetric/DES/DESKey.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable once CheckNamespace
2 | namespace Bing.Encryption
3 | {
4 | ///
5 | /// DES 密钥
6 | ///
7 | // ReSharper disable once InconsistentNaming
8 | public class DESKey
9 | {
10 | ///
11 | /// 密钥
12 | ///
13 | public string Key { get; set; }
14 |
15 | ///
16 | /// 偏移量
17 | ///
18 | public string IV { get; set; }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Symmetric/RC4EncryptionProvider.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Text;
4 | using Bing.Encryption.Abstractions;
5 |
6 | // ReSharper disable once CheckNamespace
7 | namespace Bing.Encryption
8 | {
9 | ///
10 | /// RC4 加密提供程序
11 | /// 参考:https://bitlush.com/blog/rc4-encryption-in-c-sharp
12 | ///
13 | public class RC4EncryptionProvider : ISymmetricEncyption
14 | {
15 | ///
16 | /// 初始化一个类型的实例
17 | ///
18 | private RC4EncryptionProvider() { }
19 |
20 | ///
21 | /// 加密
22 | ///
23 | /// 待加密的值
24 | /// 密钥
25 | /// 编码类型,默认Wie
26 | ///
27 | public static string Encrypt(string value, string key, Encoding encoding = null)
28 | {
29 | if (encoding == null)
30 | {
31 | encoding = Encoding.UTF8;
32 | }
33 |
34 | return Convert.ToBase64String(EncryptCore(encoding.GetBytes(value), encoding.GetBytes(key)));
35 | }
36 |
37 | ///
38 | /// 加密
39 | ///
40 | /// 待加密的值
41 | /// 密钥
42 | ///
43 | public static byte[] Encrypt(byte[] value, byte[] key)
44 | {
45 | return EncryptCore(value, key);
46 | }
47 |
48 | ///
49 | /// 解密
50 | ///
51 | /// 待加密的值
52 | /// 密钥
53 | /// 编码类型,默认Wie
54 | ///
55 | public static string Decrypt(string value, string key, Encoding encoding = null)
56 | {
57 | if (encoding == null)
58 | {
59 | encoding = Encoding.UTF8;
60 | }
61 |
62 | return encoding.GetString(EncryptCore(Convert.FromBase64String(value), encoding.GetBytes(key)));
63 | }
64 |
65 | ///
66 | /// 解密
67 | ///
68 | /// 待解密的值
69 | /// 密钥
70 | ///
71 | public static byte[] Decrypt(byte[] value, byte[] key)
72 | {
73 | return EncryptCore(value, key);
74 | }
75 |
76 | ///
77 | /// 核心加密方法
78 | ///
79 | /// 待加密的字节数组
80 | /// 密钥字节数组
81 | ///
82 | private static byte[] EncryptCore(byte[] sourceBytes, byte[] keyBytes)
83 | {
84 | var s = Initialize(keyBytes);
85 | int i = 0, j = 0;
86 |
87 | return sourceBytes.Select(b =>
88 | {
89 | i = (i + 1) & 255;
90 | j = (j + s[i]) & 255;
91 | Swap(s, i, j);
92 | return (byte) (b ^ s[(s[i] + s[j]) & 255]);
93 | }).ToArray();
94 | }
95 |
96 | ///
97 | /// 初始化密钥
98 | ///
99 | /// 密钥字节数组
100 | ///
101 | private static byte[] Initialize(byte[] keyBytes)
102 | {
103 | var s = Enumerable.Range(0, 256).Select(i => (byte) i).ToArray();
104 | for (int i = 0, j = 0; i < 256; i++)
105 | {
106 | j = (j + keyBytes[i % keyBytes.Length] + s[i]) & 255;
107 | Swap(s, i, j);
108 | }
109 |
110 | return s;
111 | }
112 |
113 | ///
114 | /// 交换位置
115 | ///
116 | private static void Swap(byte[] s, int i, int j)
117 | {
118 | var b = s[i];
119 | s[i] = s[j];
120 | s[j] = b;
121 | }
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Symmetric/TripleDES/TripleDESEncryptionProvider.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Security.Cryptography;
3 | using System.Text;
4 | using Bing.Encryption.Core;
5 | using Bing.Encryption.Core.Internals.Extensions;
6 |
7 | // ReSharper disable once CheckNamespace
8 | namespace Bing.Encryption
9 | {
10 | ///
11 | /// TripleDES 加密提供程序
12 | ///
13 | public sealed class TripleDESEncryptionProvider:SymmetricEncryptionBase
14 | {
15 | ///
16 | /// 初始化一个类型的实例
17 | ///
18 | private TripleDESEncryptionProvider() { }
19 |
20 | ///
21 | /// 创建 AES 密钥
22 | ///
23 | /// 密钥长度类型,默认为
24 | /// 编码类型,默认为
25 | ///
26 | public static TripleDESKey CreateKey(TripleDESKeySizeType size = TripleDESKeySizeType.L192, Encoding encoding = null)
27 | {
28 | if (encoding == null)
29 | {
30 | encoding = Encoding.UTF8;
31 | }
32 |
33 | using (var provider = new TripleDESCryptoServiceProvider())
34 | {
35 | return new TripleDESKey()
36 | {
37 | Key = encoding.GetString(provider.Key),
38 | IV = encoding.GetString(provider.IV),
39 | Size = size
40 | };
41 | }
42 | }
43 |
44 | ///
45 | /// 加密
46 | ///
47 | /// 待加密的值
48 | /// 密钥
49 | /// 加密偏移量
50 | /// 加盐
51 | /// 输出类型,默认为
52 | /// 编码类型,默认为
53 | /// 密钥长度类型,默认为
54 | ///
55 | public static string Encrypt(string value, string key, string iv = null, string salt = null,
56 | OutType outType = OutType.Base64,
57 | Encoding encoding = null, TripleDESKeySizeType keySize = TripleDESKeySizeType.L192)
58 | {
59 | if (string.IsNullOrEmpty(value))
60 | {
61 | throw new ArgumentNullException(nameof(value));
62 | }
63 |
64 | if (string.IsNullOrEmpty(key))
65 | {
66 | throw new ArgumentNullException(nameof(key));
67 | }
68 |
69 | if (encoding == null)
70 | {
71 | encoding = Encoding.UTF8;
72 | }
73 |
74 | var result = EncryptCore(encoding.GetBytes(value),
75 | ComputeRealValueFunc()(key)(salt)(encoding)((int)keySize),
76 | ComputeRealValueFunc()(iv)(salt)(encoding)(64));
77 |
78 | if (outType == OutType.Base64)
79 | {
80 | return Convert.ToBase64String(result);
81 | }
82 |
83 | return result.ToHexString();
84 | }
85 |
86 | ///
87 | /// 加密
88 | ///
89 | /// 待加密的值
90 | /// TripleDES 密钥对象
91 | /// 输出类型,默认为
92 | /// 编码类型,默认为
93 | ///
94 | public static string Encrypt(string value, TripleDESKey key, OutType outType = OutType.Base64,
95 | Encoding encoding = null)
96 | {
97 | if (key == null)
98 | {
99 | throw new ArgumentNullException(nameof(key));
100 | }
101 |
102 | return Encrypt(value, key.Key, key.IV, outType: outType, encoding: encoding, keySize: key.Size);
103 | }
104 |
105 | ///
106 | /// 解密
107 | ///
108 | /// 待解密的值
109 | /// 密钥
110 | /// 加密偏移量
111 | /// 加盐
112 | /// 输出类型,默认为
113 | /// 编码类型,默认为
114 | /// 密钥长度类型,默认为
115 | ///
116 | public static string Decrypt(string value, string key, string iv = null, string salt = null,
117 | OutType outType = OutType.Base64,
118 | Encoding encoding = null, TripleDESKeySizeType keySize = TripleDESKeySizeType.L192)
119 | {
120 | if (string.IsNullOrEmpty(value))
121 | {
122 | throw new ArgumentNullException(nameof(value));
123 | }
124 |
125 | if (string.IsNullOrEmpty(key))
126 | {
127 | throw new ArgumentNullException(nameof(key));
128 | }
129 |
130 | if (encoding == null)
131 | {
132 | encoding = Encoding.UTF8;
133 | }
134 |
135 | var result = DecryptCore(value.GetEncryptBytes(outType),
136 | ComputeRealValueFunc()(key)(salt)(encoding)((int)keySize),
137 | ComputeRealValueFunc()(iv)(salt)(encoding)(64));
138 |
139 | return encoding.GetString(result);
140 | }
141 |
142 | ///
143 | /// 解密
144 | ///
145 | /// 待加密的值
146 | /// TripleDES 密钥对象
147 | /// 输出类型,默认为
148 | /// 编码类型,默认为
149 | ///
150 | public static string Decrypt(string value, TripleDESKey key, OutType outType = OutType.Base64,
151 | Encoding encoding = null)
152 | {
153 | if (key == null)
154 | {
155 | throw new ArgumentNullException(nameof(key));
156 | }
157 |
158 | return Decrypt(value, key.Key, key.IV, outType: outType, encoding: encoding, keySize: key.Size);
159 | }
160 | }
161 | }
162 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Symmetric/TripleDES/TripleDESKey.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable once CheckNamespace
2 | namespace Bing.Encryption
3 | {
4 | ///
5 | /// TripleDES 密钥
6 | ///
7 | // ReSharper disable once InconsistentNaming
8 | public class TripleDESKey
9 | {
10 | ///
11 | /// 密钥
12 | ///
13 | public string Key { get; set; }
14 |
15 | ///
16 | /// 偏移量
17 | ///
18 | public string IV { get; set; }
19 |
20 | ///
21 | /// 密钥长度
22 | ///
23 | public TripleDESKeySizeType Size { get; set; }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/Bing.Encryption/Symmetric/TripleDES/TripleDESKeySizeType.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable once CheckNamespace
2 | namespace Bing.Encryption
3 | {
4 | ///
5 | /// TripleDES 密钥长度类型
6 | ///
7 | // ReSharper disable once InconsistentNaming
8 | public enum TripleDESKeySizeType
9 | {
10 | L128=128,
11 | L192=192,
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/tests/Bing.Encryption.Tests/Asymmetric/RsaTest.cs:
--------------------------------------------------------------------------------
1 | using Bing.Encryption.Core;
2 | using Xunit;
3 | using Xunit.Abstractions;
4 |
5 | namespace Bing.Encryption.Tests.Asymmetric
6 | {
7 | public class RsaTest:TestBase
8 | {
9 | public RsaTest(ITestOutputHelper output) : base(output)
10 | {
11 | }
12 |
13 | [Fact]
14 | public void Test_Encrypt()
15 | {
16 | var key = RSAEncryptionProvider.CreateKey();
17 | var source = "装逼打脸2018";
18 | var cliphertext = RSAEncryptionProvider.Encrypt(source, key.PublickKey,outType:OutType.Hex);
19 | var plaintext = RSAEncryptionProvider.Decrypt(cliphertext, key.PrivateKey, outType: OutType.Hex);
20 | var signData = RSAEncryptionProvider.SignData(source, key.PrivateKey);
21 | var verifyData = RSAEncryptionProvider.VerifyData(source, signData, key.PublickKey);
22 | Output.WriteLine("密文:\n"+cliphertext);
23 | Output.WriteLine("明文:\n" + plaintext);
24 | Output.WriteLine("签名:\n" + signData);
25 | Output.WriteLine("验签:\n" + verifyData);
26 | }
27 |
28 | [Fact]
29 | public void Test_Encrypt_1()
30 | {
31 | var privateKey =
32 | "MIIEpQIBAAKCAQEAwye3PozLsZJTAN/roZo16POjfG2jAY8OSXfzAUsxte7desdq1U+CIkEgx50SXeFMqVdnLTmm/x+1i7162F0Cky2EU3dyb859aUmhG3SdY+DOOQ5TK/0Nfjcof+0E+WPQlghsXK/gficCEqbivrYisBVQ9rDrlvxuE2svKkeAP8iy/CEssxWidm8odlZCxIIlCgbvhuwnD06oQUOEZ6iOZid2kyETmZ3WxlGWnhYW+q9XoXynml1/kZ16DHEJqFESUSWL3OyRSxMV74tAmfy0f9OcBDkT1GTDAkznauE2PM1fl/u98YEwTkRupbhYC5tXF9BQh6wRI4jes3NPe2dWuQIDAQABAoIBAQCilkwMSLDLV+TfLa7aC+guFA14dL8BZXW5r708rrDTqhXLXKic3ojEkQ4GP841eKatzque+hEvK/PMYCggahzjEWDVSQaGL7o8JaObhCQ8OeaVkmGonELJjJqpOYaTX50/4fSlo8GcWFNZxr/Rs1xi5t91JyCfwd7TPtEkoD0w5UgBaoNRlungobKES2w4L6CSNIeeq427N1uxGPhphsZMB6qslzpNnENGofab+jxhby/CqQ/iAVubraltd0lat4lXtyEaMmh0bGUI628uAH5wnWQiUdErEkwmzifBCL+0XA54jMHG1ujvUaVJIf/ATj2YBwgHRDuZgwV4e3n7bCQBAoGBAOJaUKmYGfWm1Edlm3qwkd64Hl3LNG1iViecqbqFGrl7bmWiW5WdN3A+0UF4IFLkZ8kdjqK1Ve3yG21YwVbTbBNrCkEgskkVwfaIqo0OEV9C3cOD9KnuJRcsuucc15tpuYNi+YxcLTztf1rTOJCedoLH8/2fwCvRa4geUsaLoWDpAoGBANy3VTwebGlL7lwa1EkOEbEZlVPw0NX2nWXb+trwn6/YPY354JQ0yHH+V9+HetjGXkgaHNGRVz/d9G25MmLQsHa+fqZdKbpkQW/fIUEP1ytynjO5hAzkK2HmBqlTLIW4ba5snpiRDHWUogW0rsYaS6lCcrw9WOvlO2NIHckB5iVRAoGAYfNDRKCVW0A+TEcj6QvPk9mJCn2Mymjrb2jT6er/jZRkSYbgqvXFr8T/OJ2LH1PHtbgcqTxfWwCR7deikrga5KxFW7mSbR4FOXIam7+itN5yqNDJZ1+unUC2AJzykEZICRsjciHRUbRUkDEnIS3xitaMNwySVGPjbJvypgh2ZUECgYEA017XR62zENvgt2ASMKxCkSH4+dxDgsScU7HpeMa7hsFFobPNOOGbnF+Bc9Xg9bxzCgXH14Ki1c0PigyzjiJg/DbOPzA1CAV/DU3YIOC0pS0tCEf/iADy8txBQOMgXicTEtl+wIkYL3pZ97DjN2BzWPMDwfXWNILg7uFfdOJWryECgYEA0ZNb5fgbNh5tXue/wUPr2LJ1nV/j1gf0vx40+D64Zv08OfpoSTwwnmEejz3GZBdJJ/PLhbghGL+PNug2M8sEHtYuz7CNQahknEcPwch/dToK4jjcjMnuAv+pbpYieZV1I/MvWo5MvgSvk+eWl/WsmeBBGfrDuAbAScJxXLMBoWA=";
33 | var publicKey =
34 | "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwye3PozLsZJTAN/roZo16POjfG2jAY8OSXfzAUsxte7desdq1U+CIkEgx50SXeFMqVdnLTmm/x+1i7162F0Cky2EU3dyb859aUmhG3SdY+DOOQ5TK/0Nfjcof+0E+WPQlghsXK/gficCEqbivrYisBVQ9rDrlvxuE2svKkeAP8iy/CEssxWidm8odlZCxIIlCgbvhuwnD06oQUOEZ6iOZid2kyETmZ3WxlGWnhYW+q9XoXynml1/kZ16DHEJqFESUSWL3OyRSxMV74tAmfy0f9OcBDkT1GTDAkznauE2PM1fl/u98YEwTkRupbhYC5tXF9BQh6wRI4jes3NPe2dWuQIDAQAB";
35 | var source= "sign_type=RSA2&t=1024";
36 | var signData =
37 | "FGGaXIw/BEUflRZOhDuKrBqRiSMx7tbhFEzQPWKyCErghs9KoSTVd9IqpINqAfL+wXZTYaaW+2f+/6z08uMQOG3NY9mPNvUkAEY4DCfrOHN7cVC0UcHByP/VQlJ0YHh/sNLhq+vZRI59wOlhbUxoKFA55uLelky07bK84erqFGGNzDNZnYrSghUXMEE+WPKjjk/r0n0cvnBinWF0SgyXZtnisEt9J1vFDWT6Lku01huNp7VGWwMNlL9dRnEtBiZ5vGfp/pBongosYe/ndWjPW+dRtAnNoo1xf66YYipRfYaQBlJ5lQnFGhC2pkFoko6cloc9b8mZ3Cy0EuCoAdNDCA==";
38 | var signResult = RSAEncryptionProvider.SignData(source, privateKey, keyType: RSAKeyType.Base64,rsaType:RSAType.RSA2);
39 | var verifyData = RSAEncryptionProvider.VerifyData(source, signData, publicKey,keyType:RSAKeyType.Base64, rsaType: RSAType.RSA2);
40 | Output.WriteLine("签名:\n" + signResult);
41 | Output.WriteLine("验签:\n" + verifyData);
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/tests/Bing.Encryption.Tests/Base64ConvertProviderTest.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 |
3 | namespace Bing.Encryption.Tests
4 | {
5 | ///
6 | /// Base64 转换提供程序 测试
7 | ///
8 | public class Base64ConvertProviderTest
9 | {
10 | [Fact]
11 | public void Test_Encode_1()
12 | {
13 | var result = Base64ConvertProvider.Encode("you");
14 | Assert.Equal("eW91", result);
15 | }
16 |
17 | [Fact]
18 | public void Test_Encode_2()
19 | {
20 | var result = Base64ConvertProvider.Encode("12345");
21 | Assert.Equal("MTIzNDU=",result);
22 | }
23 |
24 | [Fact]
25 | public void Test_Encode_3()
26 | {
27 | var result = Base64ConvertProvider.Encode("bhavana");
28 | Assert.Equal("YmhhdmFuYQ==",result);
29 | }
30 |
31 | [Fact]
32 | public void Test_Encode_4()
33 | {
34 | var result = Base64ConvertProvider.Encode("中国");
35 | Assert.Equal("5Lit5Zu9", result);
36 | }
37 |
38 | [Fact]
39 | public void Test_Decode_1()
40 | {
41 | var result = Base64ConvertProvider.Decode("eW91");
42 | Assert.Equal("you", result);
43 | }
44 |
45 | [Fact]
46 | public void Test_Decode_2()
47 | {
48 | var result = Base64ConvertProvider.Decode("MTIzNDU=");
49 | Assert.Equal("12345", result);
50 | }
51 |
52 | [Fact]
53 | public void Test_Decode_3()
54 | {
55 | var result = Base64ConvertProvider.Decode("YmhhdmFuYQ==");
56 | Assert.Equal("bhavana", result);
57 | }
58 |
59 | [Fact]
60 | public void Test_Decode_4()
61 | {
62 | var result = Base64ConvertProvider.Decode("5Lit5Zu9");
63 | Assert.Equal("中国", result);
64 | }
65 |
66 |
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/tests/Bing.Encryption.Tests/Bing.Encryption.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp2.2
5 |
6 | false
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/tests/Bing.Encryption.Tests/Hash/HmacTest.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 | using Xunit.Abstractions;
3 |
4 | namespace Bing.Encryption.Tests.Hash
5 | {
6 | public class HmacTest:TestBase
7 | {
8 | public HmacTest(ITestOutputHelper output) : base(output)
9 | {
10 | }
11 |
12 | [Fact]
13 | public void Test_HmacMd5()
14 | {
15 | var signature = HMACMD5HashingProvider.Signature("image", "jianxuanbing");
16 | Output.WriteLine(signature);
17 | Assert.Equal("EC2D786F467FF87934F9C6D4D64469CE", signature);
18 | }
19 |
20 | [Fact]
21 | public void Test_HmacSha1()
22 | {
23 | var signature = HMACSHA1HashingProvider.Signature("image", "jianxuanbing");
24 | Output.WriteLine(signature);
25 | Assert.Equal("8D37923C16B438FC9B29462CB93723ADB46EF14A", signature);
26 | }
27 |
28 | [Fact]
29 | public void Test_HmacSha256()
30 | {
31 | var signature = HMACSHA256HashingProvider.Signature("image", "jianxuanbing");
32 | Output.WriteLine(signature);
33 | Assert.Equal("0786D94B4433473587B2DC8ED9E0813CC714A953B2604CE69EBBA9BCDD62CB2E", signature);
34 | }
35 |
36 | [Fact]
37 | public void Test_HmacSha384()
38 | {
39 | var signature = HMACSHA384HashingProvider.Signature("image", "jianxuanbing");
40 | Output.WriteLine(signature);
41 | Assert.Equal("AE705092BCE33068C49046E5BFD5AF1BBC5E7D5BCC20002D9597638C8E070885164377413EC14D76AD47702B720047B8", signature);
42 | }
43 |
44 | [Fact]
45 | public void Test_HmacSha512()
46 | {
47 | var signature = HMACSHA512HashingProvider.Signature("image", "jianxuanbing");
48 | Output.WriteLine(signature);
49 | Assert.Equal("4CE29097986F619D54F0C7F31BEE2C1667B95781CA42A3D0C97B18DB32FD0EA36EDB1CEB5EE53493A36BA6613C17068918FAFC28B05CBD180D4D5A11CFD30952", signature);
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/tests/Bing.Encryption.Tests/Hash/Md4Test.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 | using Xunit.Abstractions;
3 |
4 | namespace Bing.Encryption.Tests.Hash
5 | {
6 | public class Md4Test:TestBase
7 | {
8 | public Md4Test(ITestOutputHelper output) : base(output)
9 | {
10 | }
11 |
12 | [Fact]
13 | public void Test_Signature()
14 | {
15 | var signature = MD4HashingProvider.Signature("image");
16 | Output.WriteLine(signature);
17 | Assert.Equal("0849E54FDE86FE2091E1B8FB5713BE65", signature);
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/tests/Bing.Encryption.Tests/Hash/Md5Test.cs:
--------------------------------------------------------------------------------
1 | using Bing.Encryption.Hash;
2 | using Xunit;
3 | using Xunit.Abstractions;
4 |
5 | namespace Bing.Encryption.Tests.Hash
6 | {
7 | public class Md5Test:TestBase
8 | {
9 | public Md5Test(ITestOutputHelper output) : base(output)
10 | {
11 | }
12 |
13 | [Fact]
14 | public void Test_Bit16()
15 | {
16 | var signature = MD5HasingProvider.Signature("image", MD5BitType.L16);
17 | Assert.Equal("1A988E79EF3F42D7", signature);
18 | }
19 |
20 | [Fact]
21 | public void Test_Bit32()
22 | {
23 | var signature = MD5HasingProvider.Signature("image", MD5BitType.L32);
24 | Assert.Equal("78805A221A988E79EF3F42D7C5BFD418", signature);
25 | }
26 |
27 | [Fact]
28 | public void Test_Bit64()
29 | {
30 | var signature = MD5HasingProvider.Signature("image", MD5BitType.L64);
31 | Assert.Equal("eIBaIhqYjnnvP0LXxb/UGA==", signature);
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/tests/Bing.Encryption.Tests/Hash/ShaTest.cs:
--------------------------------------------------------------------------------
1 | using Bing.Encryption.Core;
2 | using Xunit;
3 | using Xunit.Abstractions;
4 |
5 | namespace Bing.Encryption.Tests.Hash
6 | {
7 | public class ShaTest:TestBase
8 | {
9 | public ShaTest(ITestOutputHelper output) : base(output)
10 | {
11 | }
12 |
13 | [Fact]
14 | public void Test_Sha1_Hex()
15 | {
16 | var signature = SHA1HashingProvider.Signature("image");
17 | Assert.Equal("0E76292794888D4F1FA75FB3AFF4CA27C58F56A6", signature);
18 | }
19 |
20 | [Fact]
21 | public void Test_Sha1_Base64()
22 | {
23 | var signature = SHA1HashingProvider.Signature("image", OutType.Base64);
24 | Assert.Equal("DnYpJ5SIjU8fp1+zr/TKJ8WPVqY=", signature);
25 | }
26 |
27 | [Fact]
28 | public void Test_Sha256_Hex()
29 | {
30 | var signature = SHA256HashingProvider.Signature("image");
31 | Assert.Equal("6105D6CC76AF400325E94D588CE511BE5BFDBB73B437DC51ECA43917D7A43E3D", signature);
32 | }
33 |
34 | [Fact]
35 | public void Test_Sha256_Base64()
36 | {
37 | var signature = SHA256HashingProvider.Signature("image", OutType.Base64);
38 | Output.WriteLine(signature);
39 | Assert.Equal("YQXWzHavQAMl6U1YjOURvlv9u3O0N9xR7KQ5F9ekPj0=", signature);
40 | }
41 |
42 | [Fact]
43 | public void Test_Sha384_Hex()
44 | {
45 | var signature = SHA384HashingProvider.Signature("image");
46 | Assert.Equal("7158862BE7FF7D2AE0A585B872F415CF09B7FE8C6CE170EF944061E7788D73C1F5835652D8AFE9939B01905D5AA7C48C", signature);
47 | }
48 |
49 | [Fact]
50 | public void Test_Sha384_Base64()
51 | {
52 | var signature = SHA384HashingProvider.Signature("image", OutType.Base64);
53 | Output.WriteLine(signature);
54 | Assert.Equal("cViGK+f/fSrgpYW4cvQVzwm3/oxs4XDvlEBh53iNc8H1g1ZS2K/pk5sBkF1ap8SM", signature);
55 | }
56 |
57 | [Fact]
58 | public void Test_Sha512_Hex()
59 | {
60 | var signature = SHA512HashingProvider.Signature("image");
61 | Assert.Equal("EB31D04DA633DC9F49DFBD66CDB92FBB9B4F9C9BE67914C0209B5DD31CC65A136E1CDCE7D0DB88112E3A759131B9D970CFAAC7EE77CCD620C3DD49043F88958E", signature);
62 | }
63 |
64 | [Fact]
65 | public void Test_Sha512_Base64()
66 | {
67 | var signature = SHA512HashingProvider.Signature("image", OutType.Base64);
68 | Output.WriteLine(signature);
69 | Assert.Equal("6zHQTaYz3J9J371mzbkvu5tPnJvmeRTAIJtd0xzGWhNuHNzn0NuIES46dZExudlwz6rH7nfM1iDD3UkEP4iVjg==", signature);
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/tests/Bing.Encryption.Tests/Symmetric/AesTest.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 | using Xunit.Abstractions;
3 |
4 | namespace Bing.Encryption.Tests.Symmetric
5 | {
6 | public class AesTest:TestBase
7 | {
8 | public AesTest(ITestOutputHelper output) : base(output)
9 | {
10 | }
11 |
12 | [Fact]
13 | public void Test_Encrypt_L128()
14 | {
15 | var key = AESEncryptionProvider.CreateKey(AESKeySizeType.L128);
16 | var s1 = AESEncryptionProvider.Encrypt("仙剑蜀山", key.Key, key.IV, keySize: AESKeySizeType.L128);
17 | var o1 = AESEncryptionProvider.Decrypt(s1, key.Key, key.IV, keySize: AESKeySizeType.L128);
18 | Assert.Equal("仙剑蜀山", o1);
19 | }
20 |
21 | [Fact]
22 | public void Test_Encrypt_L192()
23 | {
24 | var key = AESEncryptionProvider.CreateKey(AESKeySizeType.L192);
25 | var s1 = AESEncryptionProvider.Encrypt("仙剑蜀山", key.Key, key.IV, keySize: AESKeySizeType.L192);
26 | var o1 = AESEncryptionProvider.Decrypt(s1, key.Key, key.IV, keySize: AESKeySizeType.L192);
27 | Assert.Equal("仙剑蜀山", o1);
28 | }
29 |
30 | [Fact]
31 | public void Test_Encrypt_L256()
32 | {
33 | var key = AESEncryptionProvider.CreateKey(AESKeySizeType.L256);
34 | var s1 = AESEncryptionProvider.Encrypt("仙剑蜀山", key.Key, key.IV, keySize: AESKeySizeType.L256);
35 | var o1 = AESEncryptionProvider.Decrypt(s1, key.Key, key.IV, keySize: AESKeySizeType.L256);
36 | Assert.Equal("仙剑蜀山", o1);
37 | }
38 |
39 | [Fact]
40 | public void Test_Encrypt_L128_WithSalt()
41 | {
42 | var key = AESEncryptionProvider.CreateKey(AESKeySizeType.L128);
43 | var s1 = AESEncryptionProvider.Encrypt("仙剑蜀山", key.Key, key.IV,"12345678", keySize: AESKeySizeType.L128);
44 | var o1 = AESEncryptionProvider.Decrypt(s1, key.Key, key.IV, "12345678", keySize: AESKeySizeType.L128);
45 | Assert.Equal("仙剑蜀山", o1);
46 | }
47 |
48 | [Fact]
49 | public void Test_Encrypt_L192_WithSalt()
50 | {
51 | var key = AESEncryptionProvider.CreateKey(AESKeySizeType.L192);
52 | var s1 = AESEncryptionProvider.Encrypt("仙剑蜀山", key.Key, key.IV, "12345678", keySize: AESKeySizeType.L192);
53 | var o1 = AESEncryptionProvider.Decrypt(s1, key.Key, key.IV, "12345678", keySize: AESKeySizeType.L192);
54 | Assert.Equal("仙剑蜀山", o1);
55 | }
56 |
57 | [Fact]
58 | public void Test_Encrypt_L256_WithSalt()
59 | {
60 | var key = AESEncryptionProvider.CreateKey(AESKeySizeType.L256);
61 | var s1 = AESEncryptionProvider.Encrypt("仙剑蜀山", key.Key, key.IV, "12345678", keySize: AESKeySizeType.L256);
62 | var o1 = AESEncryptionProvider.Decrypt(s1, key.Key, key.IV, "12345678", keySize: AESKeySizeType.L256);
63 | Assert.Equal("仙剑蜀山", o1);
64 | }
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/tests/Bing.Encryption.Tests/Symmetric/DesTest.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 | using Xunit.Abstractions;
3 |
4 | namespace Bing.Encryption.Tests.Symmetric
5 | {
6 | public class DesTest:TestBase
7 | {
8 | public DesTest(ITestOutputHelper output) : base(output)
9 | {
10 | }
11 |
12 | [Fact]
13 | public void Test_Encrypt_Decrypt()
14 | {
15 | var s = DESEncryptionProvider.Encrypt("image", "jianxuanbing", "123456");
16 | Output.WriteLine(s);
17 | Assert.Equal("W1qT5HubZGo=", s);
18 |
19 | var o = DESEncryptionProvider.Decrypt(s, "jianxuanbing", "123456");
20 | Assert.Equal("image", o);
21 | }
22 |
23 | [Fact]
24 | public void Test_Encrypt_Decrypt_WithSalt()
25 | {
26 | var s = DESEncryptionProvider.Encrypt("image", "jianxuanbing", "123456", "66666666");
27 | Output.WriteLine(s);
28 | Assert.Equal("mhYoC9zYD14=", s);
29 |
30 | var o = DESEncryptionProvider.Decrypt(s, "jianxuanbing", "123456", "66666666");
31 | Assert.Equal("image", o);
32 | }
33 |
34 | [Fact]
35 | public void Test_Encrypt_Decrypt_AutoCreateKey()
36 | {
37 | var key = DESEncryptionProvider.CreateKey();
38 | var s = DESEncryptionProvider.Encrypt("image", key.Key, key.IV);
39 | var o = DESEncryptionProvider.Decrypt(s, key.Key, key.IV);
40 | Assert.Equal("image", o);
41 | }
42 |
43 | [Fact]
44 | public void Test_Encrypt_Decrypt_AutoCreateKey_WithSalt()
45 | {
46 | var key = DESEncryptionProvider.CreateKey();
47 | var s = DESEncryptionProvider.Encrypt("image", key.Key, key.IV, "88888888");
48 | var o = DESEncryptionProvider.Decrypt(s, key.Key, key.IV, "88888888");
49 | Assert.Equal("image", o);
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/tests/Bing.Encryption.Tests/Symmetric/Rc4Test.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 | using Xunit.Abstractions;
3 |
4 | namespace Bing.Encryption.Tests.Symmetric
5 | {
6 | public class Rc4Test:TestBase
7 | {
8 | public Rc4Test(ITestOutputHelper output) : base(output)
9 | {
10 | }
11 |
12 | [Fact]
13 | public void Test_Encrypt_Decrypt()
14 | {
15 | var s = RC4EncryptionProvider.Encrypt("image", "jianxuanbing");
16 | Assert.Equal("cHNk+Ck=", s);
17 |
18 | var o = RC4EncryptionProvider.Decrypt(s, "jianxuanbing");
19 | Assert.Equal("image", o);
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/tests/Bing.Encryption.Tests/Symmetric/TripleDesTest.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 | using Xunit.Abstractions;
3 |
4 | namespace Bing.Encryption.Tests.Symmetric
5 | {
6 | public class TripleDesTest:TestBase
7 | {
8 | public TripleDesTest(ITestOutputHelper output) : base(output)
9 | {
10 | }
11 |
12 | [Fact]
13 | public void Test_Encrypt_Decrypt_L128()
14 | {
15 | var s1 = TripleDESEncryptionProvider.Encrypt("仙剑蜀山", "jianxuanbing", "12345678", keySize: TripleDESKeySizeType.L128);
16 | var o1 = TripleDESEncryptionProvider.Decrypt(s1, "jianxuanbing", "12345678", keySize: TripleDESKeySizeType.L128);
17 | Assert.Equal("仙剑蜀山", o1);
18 | }
19 |
20 | [Fact]
21 | public void Test_Encrypt_Decrypt_L128_WithSalt()
22 | {
23 | var s1 = TripleDESEncryptionProvider.Encrypt("仙剑蜀山", "jianxuanbing", "12345678", "66666666",
24 | keySize: TripleDESKeySizeType.L128);
25 | var o1 = TripleDESEncryptionProvider.Decrypt(s1, "jianxuanbing", "12345678", "66666666", keySize: TripleDESKeySizeType.L128);
26 | Assert.Equal("仙剑蜀山", o1);
27 | }
28 |
29 | [Fact]
30 | public void Test_Encrypt_Decrypt_L192()
31 | {
32 | var s1 = TripleDESEncryptionProvider.Encrypt("仙剑蜀山", "jianxuanbing", "12345678", keySize: TripleDESKeySizeType.L192);
33 | var o1 = TripleDESEncryptionProvider.Decrypt(s1, "jianxuanbing", "12345678", keySize: TripleDESKeySizeType.L192);
34 | Assert.Equal("仙剑蜀山", o1);
35 | }
36 |
37 | [Fact]
38 | public void Test_Encrypt_Decrypt_L192_WithSalt()
39 | {
40 | var s1 = TripleDESEncryptionProvider.Encrypt("仙剑蜀山", "jianxuanbing", "12345678", "66666666",
41 | keySize: TripleDESKeySizeType.L192);
42 | var o1 = TripleDESEncryptionProvider.Decrypt(s1, "jianxuanbing", "12345678", "66666666", keySize: TripleDESKeySizeType.L192);
43 | Assert.Equal("仙剑蜀山", o1);
44 | }
45 |
46 | [Fact]
47 | public void Test_Encrypt_Decrypt_AutoCreateKey_L128()
48 | {
49 | var key = TripleDESEncryptionProvider.CreateKey(TripleDESKeySizeType.L128);
50 | var s1 = TripleDESEncryptionProvider.Encrypt("仙剑蜀山", key.Key, key.IV, keySize: TripleDESKeySizeType.L128);
51 | var o1 = TripleDESEncryptionProvider.Decrypt(s1, key.Key, key.IV, keySize: TripleDESKeySizeType.L128);
52 | Assert.Equal("仙剑蜀山", o1);
53 | }
54 |
55 | [Fact]
56 | public void Test_Encrypt_Decrypt_AutoCreateKey_L128_WithSalt()
57 | {
58 | var key = TripleDESEncryptionProvider.CreateKey(TripleDESKeySizeType.L128);
59 | var s1 = TripleDESEncryptionProvider.Encrypt("仙剑蜀山", key.Key, key.IV, "66666666",
60 | keySize: TripleDESKeySizeType.L128);
61 | var o1 = TripleDESEncryptionProvider.Decrypt(s1, key.Key, key.IV, "66666666", keySize: TripleDESKeySizeType.L128);
62 | Assert.Equal("仙剑蜀山", o1);
63 | }
64 |
65 | [Fact]
66 | public void Test_Encrypt_Decrypt_AutoCreateKey_L192()
67 | {
68 | var key = TripleDESEncryptionProvider.CreateKey(TripleDESKeySizeType.L128);
69 | var s1 = TripleDESEncryptionProvider.Encrypt("仙剑蜀山", key.Key, key.IV, keySize: TripleDESKeySizeType.L128);
70 | var o1 = TripleDESEncryptionProvider.Decrypt(s1, key.Key, key.IV, keySize: TripleDESKeySizeType.L128);
71 | Assert.Equal("仙剑蜀山", o1);
72 | }
73 |
74 | [Fact]
75 | public void Test_Encrypt_Decrypt_AutoCreateKey_L192_WithSalt()
76 | {
77 | var key = TripleDESEncryptionProvider.CreateKey(TripleDESKeySizeType.L192);
78 | var s1 = TripleDESEncryptionProvider.Encrypt("仙剑蜀山", key.Key, key.IV, "66666666",
79 | keySize: TripleDESKeySizeType.L192);
80 | var o1 = TripleDESEncryptionProvider.Decrypt(s1, key.Key, key.IV, "66666666", keySize: TripleDESKeySizeType.L192);
81 | Assert.Equal("仙剑蜀山", o1);
82 | }
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/tests/Bing.Encryption.Tests/TestBase.cs:
--------------------------------------------------------------------------------
1 | using Xunit.Abstractions;
2 |
3 | namespace Bing.Encryption.Tests
4 | {
5 | public class TestBase
6 | {
7 | protected ITestOutputHelper Output;
8 |
9 | public TestBase(ITestOutputHelper output)
10 | {
11 | Output = output;
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------