├── .gitattributes
├── .gitignore
├── App.config
├── LICENSE
├── Loader.cs
├── Program.cs
├── Properties
└── AssemblyInfo.cs
├── README.md
├── Rewriter.cs
├── SimpleSourceProtector.csproj
├── SimpleSourceProtector.sln
├── UsingRewriter.cs
├── Utils.cs
├── Watcher.cs
└── packages.config
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # MSTest test Results
33 | [Tt]est[Rr]esult*/
34 | [Bb]uild[Ll]og.*
35 |
36 | # NUNIT
37 | *.VisualState.xml
38 | TestResult.xml
39 |
40 | # Build Results of an ATL Project
41 | [Dd]ebugPS/
42 | [Rr]eleasePS/
43 | dlldata.c
44 |
45 | # Benchmark Results
46 | BenchmarkDotNet.Artifacts/
47 |
48 | # .NET Core
49 | project.lock.json
50 | project.fragment.lock.json
51 | artifacts/
52 | **/Properties/launchSettings.json
53 |
54 | *_i.c
55 | *_p.c
56 | *_i.h
57 | *.ilk
58 | *.meta
59 | *.obj
60 | *.pch
61 | *.pdb
62 | *.pgc
63 | *.pgd
64 | *.rsp
65 | *.sbr
66 | *.tlb
67 | *.tli
68 | *.tlh
69 | *.tmp
70 | *.tmp_proj
71 | *.log
72 | *.vspscc
73 | *.vssscc
74 | .builds
75 | *.pidb
76 | *.svclog
77 | *.scc
78 |
79 | # Chutzpah Test files
80 | _Chutzpah*
81 |
82 | # Visual C++ cache files
83 | ipch/
84 | *.aps
85 | *.ncb
86 | *.opendb
87 | *.opensdf
88 | *.sdf
89 | *.cachefile
90 | *.VC.db
91 | *.VC.VC.opendb
92 |
93 | # Visual Studio profiler
94 | *.psess
95 | *.vsp
96 | *.vspx
97 | *.sap
98 |
99 | # TFS 2012 Local Workspace
100 | $tf/
101 |
102 | # Guidance Automation Toolkit
103 | *.gpState
104 |
105 | # ReSharper is a .NET coding add-in
106 | _ReSharper*/
107 | *.[Rr]e[Ss]harper
108 | *.DotSettings.user
109 |
110 | # JustCode is a .NET coding add-in
111 | .JustCode
112 |
113 | # TeamCity is a build add-in
114 | _TeamCity*
115 |
116 | # DotCover is a Code Coverage Tool
117 | *.dotCover
118 |
119 | # AxoCover is a Code Coverage Tool
120 | .axoCover/*
121 | !.axoCover/settings.json
122 |
123 | # Visual Studio code coverage results
124 | *.coverage
125 | *.coveragexml
126 |
127 | # NCrunch
128 | _NCrunch_*
129 | .*crunch*.local.xml
130 | nCrunchTemp_*
131 |
132 | # MightyMoose
133 | *.mm.*
134 | AutoTest.Net/
135 |
136 | # Web workbench (sass)
137 | .sass-cache/
138 |
139 | # Installshield output folder
140 | [Ee]xpress/
141 |
142 | # DocProject is a documentation generator add-in
143 | DocProject/buildhelp/
144 | DocProject/Help/*.HxT
145 | DocProject/Help/*.HxC
146 | DocProject/Help/*.hhc
147 | DocProject/Help/*.hhk
148 | DocProject/Help/*.hhp
149 | DocProject/Help/Html2
150 | DocProject/Help/html
151 |
152 | # Click-Once directory
153 | publish/
154 |
155 | # Publish Web Output
156 | *.[Pp]ublish.xml
157 | *.azurePubxml
158 | # Note: Comment the next line if you want to checkin your web deploy settings,
159 | # but database connection strings (with potential passwords) will be unencrypted
160 | *.pubxml
161 | *.publishproj
162 |
163 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
164 | # checkin your Azure Web App publish settings, but sensitive information contained
165 | # in these scripts will be unencrypted
166 | PublishScripts/
167 |
168 | # NuGet Packages
169 | *.nupkg
170 | # The packages folder can be ignored because of Package Restore
171 | **/packages/*
172 | # except build/, which is used as an MSBuild target.
173 | !**/packages/build/
174 | # Uncomment if necessary however generally it will be regenerated when needed
175 | #!**/packages/repositories.config
176 | # NuGet v3's project.json files produces more ignorable files
177 | *.nuget.props
178 | *.nuget.targets
179 |
180 | # Microsoft Azure Build Output
181 | csx/
182 | *.build.csdef
183 |
184 | # Microsoft Azure Emulator
185 | ecf/
186 | rcf/
187 |
188 | # Windows Store app package directories and files
189 | AppPackages/
190 | BundleArtifacts/
191 | Package.StoreAssociation.xml
192 | _pkginfo.txt
193 | *.appx
194 |
195 | # Visual Studio cache files
196 | # files ending in .cache can be ignored
197 | *.[Cc]ache
198 | # but keep track of directories ending in .cache
199 | !*.[Cc]ache/
200 |
201 | # Others
202 | ClientBin/
203 | ~$*
204 | *~
205 | *.dbmdl
206 | *.dbproj.schemaview
207 | *.jfm
208 | *.pfx
209 | *.publishsettings
210 | orleans.codegen.cs
211 |
212 | # Since there are multiple workflows, uncomment next line to ignore bower_components
213 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
214 | #bower_components/
215 |
216 | # RIA/Silverlight projects
217 | Generated_Code/
218 |
219 | # Backup & report files from converting an old project file
220 | # to a newer Visual Studio version. Backup files are not needed,
221 | # because we have git ;-)
222 | _UpgradeReport_Files/
223 | Backup*/
224 | UpgradeLog*.XML
225 | UpgradeLog*.htm
226 |
227 | # SQL Server files
228 | *.mdf
229 | *.ldf
230 | *.ndf
231 |
232 | # Business Intelligence projects
233 | *.rdl.data
234 | *.bim.layout
235 | *.bim_*.settings
236 |
237 | # Microsoft Fakes
238 | FakesAssemblies/
239 |
240 | # GhostDoc plugin setting file
241 | *.GhostDoc.xml
242 |
243 | # Node.js Tools for Visual Studio
244 | .ntvs_analysis.dat
245 | node_modules/
246 |
247 | # Typescript v1 declaration files
248 | typings/
249 |
250 | # Visual Studio 6 build log
251 | *.plg
252 |
253 | # Visual Studio 6 workspace options file
254 | *.opt
255 |
256 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
257 | *.vbw
258 |
259 | # Visual Studio LightSwitch build output
260 | **/*.HTMLClient/GeneratedArtifacts
261 | **/*.DesktopClient/GeneratedArtifacts
262 | **/*.DesktopClient/ModelManifest.xml
263 | **/*.Server/GeneratedArtifacts
264 | **/*.Server/ModelManifest.xml
265 | _Pvt_Extensions
266 |
267 | # Paket dependency manager
268 | .paket/paket.exe
269 | paket-files/
270 |
271 | # FAKE - F# Make
272 | .fake/
273 |
274 | # JetBrains Rider
275 | .idea/
276 | *.sln.iml
277 |
278 | # CodeRush
279 | .cr/
280 |
281 | # Python Tools for Visual Studio (PTVS)
282 | __pycache__/
283 | *.pyc
284 |
285 | # Cake - Uncomment if you are using it
286 | # tools/**
287 | # !tools/packages.config
288 |
289 | # Tabs Studio
290 | *.tss
291 |
292 | # Telerik's JustMock configuration file
293 | *.jmconfig
294 |
295 | # BizTalk build output
296 | *.btp.cs
297 | *.btm.cs
298 | *.odx.cs
299 | *.xsd.cs
300 |
--------------------------------------------------------------------------------
/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/Loader.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis;
2 | using Microsoft.CodeAnalysis.CSharp;
3 | using Microsoft.CodeAnalysis.CSharp.Syntax;
4 | using Microsoft.CodeAnalysis.FindSymbols;
5 | using Microsoft.CodeAnalysis.MSBuild;
6 | using Microsoft.CodeAnalysis.Rename;
7 | using System;
8 | using System.Collections.Generic;
9 | using System.IO;
10 | using System.Linq;
11 | using System.Text;
12 | using static SimpleSourceProtector.Program;
13 |
14 | namespace SimpleSourceProtector
15 | {
16 | class Loader
17 | {
18 | public int Process(string projectPath, string outputPath, bool compileBefore = false, ObfuscationOptions obfuscationOptions = ObfuscationOptions.ALL, bool single = true, bool minify = true)
19 | {
20 | #region Creating new project from exist
21 | MSBuildWorkspace workspace = MSBuildWorkspace.Create();
22 | string projName = "ObfuscatedProject";
23 | var projectId = ProjectId.CreateNewId();
24 | var versionStamp = VersionStamp.Create();
25 | var projectInfo = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp);
26 | var solution = workspace.CurrentSolution.AddProject(projectInfo);
27 |
28 | using (Watcher.Start(ts => Console.WriteLine("Creating project took: " + ts.ToString() + "\n")))
29 | {
30 | MSBuildWorkspace wspLoading = MSBuildWorkspace.Create();
31 | var prjLoading = wspLoading.OpenProjectAsync(projectPath).Result;
32 | Solution slnLoading = wspLoading.CurrentSolution;
33 |
34 | solution = solution.WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
35 | foreach (var prjId in slnLoading.GetProjectDependencyGraph().GetTopologicallySortedProjects())
36 | {
37 | var prj = slnLoading.GetProject(prjId);
38 |
39 | foreach (var doc in prj.Documents)
40 | solution = solution.AddDocument(DocumentId.CreateNewId(projectId), doc.Name, doc.GetTextAsync().Result);
41 | solution = solution.AddMetadataReferences(projectId, prj.MetadataReferences);
42 | }
43 |
44 | Console.WriteLine("Solution structure: ");
45 | foreach (var prj in solution.Projects)
46 | {
47 | Console.WriteLine($" Project: {prj.Id} Docs: {prj.Documents.Count()}");
48 | foreach (var doc in prj.Documents)
49 | {
50 | Console.WriteLine($" Document: {doc.Id} name: {doc.Name}");
51 | }
52 | }
53 | }
54 | #endregion
55 |
56 | #region Check compiling test
57 | using (Watcher.Start(ts => Console.WriteLine("Check compilling took: " + ts.ToString() + "\n")))
58 | {
59 | if (compileBefore)
60 | {
61 | using (var stream = new MemoryStream())
62 | {
63 | Console.WriteLine("--------------------------------CHECK COMPILING----------------------------------");
64 | var result = solution.GetProject(projectId).GetCompilationAsync().Result.Emit(stream);
65 | Console.WriteLine("Diagnostic: " + string.Join("\n", result.Diagnostics.Where(x => x.IsWarningAsError || x.Severity == DiagnosticSeverity.Error).Select(x => x.Id + " " + x.GetMessage() + " " + x.Location.GetLineSpan())));
66 | Console.WriteLine("Compiling Result: " + result.Success);
67 | Console.WriteLine("--------------------------------------------------------------------------");
68 | if (!result.Success)
69 | return 2;
70 | }
71 |
72 |
73 | }
74 | }
75 | #endregion
76 |
77 | #region Renaming
78 | var documents = solution.Projects.SelectMany(x => x.Documents).Select(x => x.Id).ToList();
79 | if (obfuscationOptions != ObfuscationOptions.NONE)
80 | using (Watcher.Start(ts => Console.WriteLine("Renaming took: " + ts.ToString() + "\n")))
81 | solution = ObfuscateNames(solution, documents, obfuscationOptions);
82 | #endregion
83 |
84 | #region Second comiling test
85 |
86 | var outWorkspace = workspace;
87 | var outSolution = solution;
88 |
89 | if (single)
90 | {
91 | outWorkspace = MSBuildWorkspace.Create();
92 |
93 | projName = "ObfuscatedSingleProject";
94 | projectId = ProjectId.CreateNewId();
95 | versionStamp = VersionStamp.Create();
96 | projectInfo = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp);
97 | outSolution = workspace.CurrentSolution.AddProject(projectInfo);
98 | outSolution = outSolution.WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
99 | List docs = new List();
100 | foreach (var prjId in solution.GetProjectDependencyGraph().GetTopologicallySortedProjects())
101 | {
102 | var prj = solution.GetProject(prjId);
103 | docs.AddRange(prj.Documents);
104 | outSolution = outSolution.AddMetadataReferences(projectId, prj.MetadataReferences);
105 | }
106 | outSolution = outSolution.AddDocument(DocumentId.CreateNewId(projectId), Path.GetFileNameWithoutExtension(projectPath), ToSingleDoc(docs, outputPath));
107 | documents = outSolution.Projects.SelectMany(x => x.Documents).Select(x => x.Id).ToList();
108 |
109 | }
110 |
111 | using (Watcher.Start(ts => Console.WriteLine("Post compilling took: " + ts.ToString() + "\n")))
112 | {
113 | using (var stream = new MemoryStream())
114 | {
115 | Console.WriteLine("--------------------------------POST COMPILING----------------------------------");
116 | var res = outSolution.GetProject(projectId).GetCompilationAsync().Result.Emit(stream);
117 | Console.WriteLine("Diagnostic: " + string.Join("\n", res.Diagnostics.Where(x => x.IsWarningAsError || x.Severity == DiagnosticSeverity.Error).Select(x => x.Id + " " + x.GetMessage() + " " + x.Location.GetLineSpan())));
118 | Console.WriteLine("Compiling Result: " + res.Success);
119 | Console.WriteLine("--------------------------------END COMPILING--------------------------------");
120 |
121 | if (!res.Success)
122 | return 3;
123 | }
124 | }
125 | #endregion
126 |
127 | #region Writing to output new project with deformating
128 |
129 | using (Watcher.Start(ts => Console.WriteLine("Writing to disk took: " + ts.ToString() + "\n")))
130 | {
131 | if (Directory.Exists(outputPath))
132 | {
133 | Console.WriteLine($"Cleaning output dir: {outputPath}");
134 | foreach (string file in Directory.GetFiles(outputPath, "*.cs"))
135 | File.Delete(file);
136 | }
137 | else
138 | {
139 | Console.WriteLine($"Creating output dir: {outputPath}");
140 | Directory.CreateDirectory(outputPath);
141 | }
142 |
143 | foreach (var documentId in documents)
144 | {
145 | var document = outSolution.GetDocument(documentId);
146 | if (document.Name.Contains(".NETFramework")) continue;
147 |
148 | var model = document.GetSemanticModelAsync().Result;
149 | var syntax = document.GetSyntaxRootAsync().Result;
150 |
151 | Rewriter rewriter = new Rewriter(model);
152 | SyntaxNode newSource = (minify) ? rewriter.Visit(syntax) : syntax;
153 |
154 | var newPath = Path.Combine(outputPath, (((obfuscationOptions & ObfuscationOptions.FILENAMES) == 0) ? document.Name : Utils.RandomString()) + ".cs");
155 | Console.WriteLine("WRITING: " + document.Name + " as " + newPath);
156 | File.WriteAllText(newPath, (minify) ? Utils.Unformat(newSource.ToFullString()) : newSource.ToFullString());
157 | }
158 | }
159 |
160 | #endregion
161 |
162 | return 0;
163 | }
164 |
165 | private static Solution ObfuscateNames(Solution solution, List documents, ObfuscationOptions obfuscationOptions)
166 | {
167 | #region RENAMER
168 |
169 | #region Rename classes
170 | if ((obfuscationOptions & ObfuscationOptions.CLASS) != 0)
171 | {
172 | Console.WriteLine("----------------------------------CLASSES----------------------------------");
173 | using (Watcher.Start(ts => Console.WriteLine("Timed: " + ts.ToString())))
174 | {
175 |
176 | foreach (var documentId in documents)
177 | {
178 | while (true)
179 | {
180 | var doc = solution.GetDocument(documentId);
181 | var model = doc.GetSemanticModelAsync().Result;
182 | var syntax = doc.GetSyntaxRootAsync().Result;
183 | var classes = syntax.DescendantNodes()
184 | .OfType()
185 | .Where(x => !x.Identifier.ValueText.StartsWith("_") && x.Identifier.ValueText.IndexOf("ignore", StringComparison.OrdinalIgnoreCase) < 0)
186 | .ToList();
187 |
188 | var cl = classes.FirstOrDefault();
189 | if (cl == null)
190 | break;
191 | var symbol = model.GetDeclaredSymbol(cl);
192 | var newName = "_" + Utils.RandomString();
193 | Console.WriteLine("Renaming class: " + cl.Identifier.ValueText + " to " + newName);
194 | solution = Renamer.RenameSymbolAsync(solution, symbol, newName, null).Result;
195 | }
196 |
197 | }
198 | }
199 | }
200 | #endregion
201 |
202 | #region Rename methods
203 | if ((obfuscationOptions & ObfuscationOptions.METHODS) != 0)
204 | {
205 | Console.WriteLine("----------------------------------METHODS----------------------------------");
206 | using (Watcher.Start(ts => Console.WriteLine("Timed: " + ts.ToString())))
207 | {
208 | foreach (var documentId in documents)
209 | {
210 | List methods;
211 | int i;
212 | do
213 | {
214 | var doc = solution.GetDocument(documentId);
215 | var model = doc.GetSemanticModelAsync().Result;
216 | var syntax = doc.GetSyntaxRootAsync().Result;
217 | methods = syntax.DescendantNodes()
218 | .OfType()
219 | .Where(x => !x.Identifier.ValueText.StartsWith("_") && !x.Identifier.ToString().Equals("dispose", StringComparison.OrdinalIgnoreCase) && x.Modifiers.Count(z => z.IsKind(SyntaxKind.ProtectedKeyword) || z.IsKind(SyntaxKind.OverrideKeyword)) == 0)
220 | .ToList();
221 |
222 | for (i = 0; i < methods.Count; i++)
223 | {
224 | var ms = methods[i];
225 | var symbol = model.GetDeclaredSymbol(ms);
226 |
227 | if (ms.GetLeadingTrivia().ToString().IndexOf("ignore", StringComparison.OrdinalIgnoreCase) >= 0)
228 | continue;
229 |
230 | var refcount = 0;
231 | foreach (var rf in SymbolFinder.FindReferencesAsync(symbol, doc.Project.Solution).Result)
232 | refcount += rf.Locations.Count();
233 | if (refcount <= 0) continue;
234 |
235 | var newName = "_" + Utils.RandomString();
236 | Console.WriteLine("Renaming method (" + refcount + "): " + ms.Identifier.ValueText + " to " + newName + $" {ms.Kind()} {string.Join(",", ms.Modifiers)}");
237 | solution = Renamer.RenameSymbolAsync(solution, symbol, newName, null).Result;
238 | break;
239 | }
240 | } while (i < methods.Count);
241 | }
242 | }
243 | }
244 | #endregion
245 |
246 | #region Rename variables
247 | if ((obfuscationOptions & ObfuscationOptions.VARS) != 0)
248 | {
249 | Console.WriteLine("----------------------------------VARS&FIELDS----------------------------------");
250 | using (Watcher.Start(ts => Console.WriteLine("Timed: " + ts.ToString())))
251 | {
252 | foreach (var documentId in documents)
253 | {
254 | List vars;
255 | int i;
256 | do
257 | {
258 | var doc = solution.GetDocument(documentId);
259 | var model = doc.GetSemanticModelAsync().Result;
260 | var syntax = doc.GetSyntaxRootAsync().Result;
261 | vars = syntax.DescendantNodes()
262 | .OfType()
263 | .Where(x => x.Variables.Count(z => !z.Identifier.ValueText.StartsWith("_")) > 0)
264 | .ToList();
265 |
266 | for (i = 0; i < vars.Count; i++)
267 | {
268 | bool end = true;
269 | foreach (var vr in vars[i].Variables)
270 | {
271 | if (vr.Identifier.ValueText.StartsWith("_")) continue;
272 |
273 | var symbol = model.GetDeclaredSymbol(vr);
274 |
275 | if (vr.GetLeadingTrivia().ToString().IndexOf("ignore", StringComparison.OrdinalIgnoreCase) >= 0)
276 | continue;
277 |
278 | var newName = "_" + Utils.RandomString();
279 | Console.WriteLine("Renaming variable: " + vr.Identifier.ValueText + " to " + newName + $" {vr.Kind()}");
280 | solution = Renamer.RenameSymbolAsync(solution, symbol, newName, null).Result;
281 | end = true;
282 | break;
283 | }
284 | if (end) break;
285 | }
286 | } while (i < vars.Count);
287 | }
288 | }
289 | }
290 | #endregion
291 |
292 | if ((obfuscationOptions & ObfuscationOptions.OTHERS) != 0)
293 | {
294 | #region Rename Enums
295 | Console.WriteLine("----------------------------------ENUMS----------------------------------");
296 | using (Watcher.Start(ts => Console.WriteLine("Timed: " + ts.ToString())))
297 | {
298 | foreach (var documentId in documents)
299 | {
300 | List vars;
301 | int i;
302 | do
303 | {
304 | var doc = solution.GetDocument(documentId);
305 | var model = doc.GetSemanticModelAsync().Result;
306 | var syntax = doc.GetSyntaxRootAsync().Result;
307 | vars = syntax.DescendantNodes()
308 | .OfType()
309 | .Where(x => !x.Identifier.ValueText.StartsWith("_"))
310 | .ToList();
311 |
312 | for (i = 0; i < vars.Count; i++)
313 | {
314 | var vr = vars[i];
315 | if (vr.Identifier.ValueText.StartsWith("_")) continue;
316 |
317 | var symbol = model.GetDeclaredSymbol(vr);
318 |
319 | if (vr.GetLeadingTrivia().ToString().IndexOf("ignore", StringComparison.OrdinalIgnoreCase) >= 0)
320 | continue;
321 |
322 | var newName = "_" + Utils.RandomString();
323 | Console.WriteLine("Renaming ENUM: " + vr.Identifier.ValueText + " to " + newName + $" {vr.Kind()}");
324 | solution = Renamer.RenameSymbolAsync(solution, symbol, newName, null).Result;
325 | break;
326 | }
327 | } while (i < vars.Count);
328 | }
329 | }
330 |
331 | Console.WriteLine("----------------------------------ENUM MEMBERS----------------------------------");
332 | using (Watcher.Start(ts => Console.WriteLine("Timed: " + ts.ToString())))
333 | {
334 | foreach (var documentId in documents)
335 | {
336 | List vars;
337 | int i;
338 | do
339 | {
340 | var doc = solution.GetDocument(documentId);
341 | var model = doc.GetSemanticModelAsync().Result;
342 | var syntax = doc.GetSyntaxRootAsync().Result;
343 | vars = syntax.DescendantNodes()
344 | .OfType()
345 | .Where(x => !x.Identifier.ValueText.StartsWith("_"))
346 | .ToList();
347 |
348 | for (i = 0; i < vars.Count; i++)
349 | {
350 | var vr = vars[i];
351 | if (vr.Identifier.ValueText.StartsWith("_")) continue;
352 |
353 | var symbol = model.GetDeclaredSymbol(vr);
354 |
355 | if (vr.GetLeadingTrivia().ToString().IndexOf("ignore", StringComparison.OrdinalIgnoreCase) >= 0)
356 | continue;
357 |
358 | var newName = "_" + Utils.RandomString();
359 | Console.WriteLine("Renaming ENUM member: " + vr.Identifier.ValueText + " to " + newName + $" {vr.Kind()}");
360 | solution = Renamer.RenameSymbolAsync(solution, symbol, newName, null).Result;
361 | break;
362 | }
363 | } while (i < vars.Count);
364 | }
365 | }
366 |
367 | #endregion
368 |
369 | #region Rename Structs
370 | Console.WriteLine("----------------------------------STRUCTS----------------------------------");
371 | using (Watcher.Start(ts => Console.WriteLine("Timed: " + ts.ToString())))
372 | {
373 | foreach (var documentId in documents)
374 | {
375 | List vars;
376 | int i;
377 | do
378 | {
379 | var doc = solution.GetDocument(documentId);
380 | var model = doc.GetSemanticModelAsync().Result;
381 | var syntax = doc.GetSyntaxRootAsync().Result;
382 | vars = syntax.DescendantNodes()
383 | .OfType()
384 | .Where(x => !x.Identifier.ValueText.StartsWith("_"))
385 | .ToList();
386 |
387 | for (i = 0; i < vars.Count; i++)
388 | {
389 | var vr = vars[i];
390 | if (vr.Identifier.ValueText.StartsWith("_")) continue;
391 |
392 | var symbol = model.GetDeclaredSymbol(vr);
393 |
394 | if (vr.GetLeadingTrivia().ToString().IndexOf("ignore", StringComparison.OrdinalIgnoreCase) >= 0)
395 | continue;
396 |
397 | var newName = "_" + Utils.RandomString();
398 | Console.WriteLine("Renaming STRUCTS: " + vr.Identifier.ValueText + " to " + newName + $" {vr.Kind()}");
399 | solution = Renamer.RenameSymbolAsync(solution, symbol, newName, null).Result;
400 | break;
401 | }
402 | } while (i < vars.Count);
403 | }
404 | }
405 | #endregion
406 | }
407 |
408 | return solution;
409 | #endregion
410 | }
411 |
412 |
413 | private string ToSingleDoc(IEnumerable documents, string outputPath)
414 | {
415 | List sources = new List();
416 | foreach (var document in documents)
417 | {
418 | if (document.Name.Contains(".NETFramework")) continue;
419 |
420 | var model = document.GetSemanticModelAsync().Result;
421 | var syntax = document.GetSyntaxRootAsync().Result;
422 |
423 | UsingRewriter rewriter = new UsingRewriter(model);
424 | SyntaxNode newSource = rewriter.Visit(syntax);
425 |
426 | sources.Add(newSource.ToFullString());
427 | }
428 |
429 | StringBuilder result = new StringBuilder();
430 |
431 | var list = sources.ToList();
432 | list.Shuffle();
433 | foreach (var src in list)
434 | result.AppendLine(src);
435 |
436 | return result.ToString();
437 | }
438 | }
439 | }
440 |
--------------------------------------------------------------------------------
/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 |
5 | namespace SimpleSourceProtector
6 | {
7 | internal static class Program
8 | {
9 | [Flags]
10 | public enum ObfuscationOptions
11 | {
12 | NONE = 0,
13 | CLASS = 1,
14 | METHODS = 1 << 1,
15 | VARS = 1 << 2,
16 | OTHERS = 1 << 3,
17 | FILENAMES = 1 << 4,
18 | ALL = CLASS | METHODS | VARS | OTHERS | FILENAMES
19 | };
20 |
21 | static void Main(string[] args)
22 | {
23 | HashSet m_allowed = new HashSet { "h", "c", "n", "m", "dm", "rc", "rm", "rv", "ro", "rf" };
24 | Dictionary arguments = new Dictionary();
25 | int i = 0;
26 | int a = 0;
27 | while (i < args.Length)
28 | {
29 | if (args[i].StartsWith("-"))
30 | {
31 | var option = args[i].Substring(1);
32 | if (m_allowed.Contains(option))
33 | arguments.Add(option, "true");
34 | else
35 |
36 | HelpMsg("Option '" + args[i] + "' not recognized.");
37 | }
38 | else
39 | arguments.Add("arg" + a++, args[i]);
40 | i++;
41 | }
42 |
43 | if (arguments.Count <= 0 || !arguments.ContainsKey("arg0"))
44 | HelpMsg("The required parameter is missing: project");
45 | if (!File.Exists(arguments["arg0"]))
46 | HelpMsg("Project file not found...");
47 |
48 |
49 | string projectPath = arguments["arg0"];
50 | string outputPath = (arguments.ContainsKey("arg1")) ? arguments["arg1"] : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output");
51 |
52 | bool checkCompilation = (arguments.ContainsKey("c")) ? true : false;
53 | bool single = (arguments.ContainsKey("m")) ? false : true;
54 | bool minify = (arguments.ContainsKey("dm")) ? false : true;
55 |
56 | ObfuscationOptions obfuscationOptions = (arguments.ContainsKey("n")) ? ObfuscationOptions.NONE : ObfuscationOptions.ALL;
57 | if (!arguments.ContainsKey("n") && (arguments.ContainsKey("rc") || arguments.ContainsKey("rm") || arguments.ContainsKey("rv") || arguments.ContainsKey("ro") || arguments.ContainsKey("rf")))
58 | {
59 | obfuscationOptions = ObfuscationOptions.NONE;
60 | if (arguments.ContainsKey("rc"))
61 | obfuscationOptions |= ObfuscationOptions.CLASS;
62 | if (arguments.ContainsKey("rm"))
63 | obfuscationOptions |= ObfuscationOptions.METHODS;
64 | if (arguments.ContainsKey("rv"))
65 | obfuscationOptions |= ObfuscationOptions.VARS;
66 | if (arguments.ContainsKey("ro"))
67 | obfuscationOptions |= ObfuscationOptions.OTHERS;
68 | if (arguments.ContainsKey("rf"))
69 | obfuscationOptions |= ObfuscationOptions.FILENAMES;
70 | }
71 |
72 | Console.WriteLine($"Start processing project: {projectPath}");
73 | Console.WriteLine($"Output: {outputPath}");
74 | Console.WriteLine($"Options: check compilation = {checkCompilation}, do multiple = {!single}, minify = {minify}, obfuscate options = {obfuscationOptions.ToString()}");
75 |
76 | int resCode = 0;
77 | using (Watcher.Start(ts => Console.WriteLine("All Timed: " + ts.ToString())))
78 | {
79 | var loader = new Loader();
80 | resCode = loader.Process(projectPath, outputPath, checkCompilation, obfuscationOptions, single, minify);
81 | }
82 | Environment.Exit(resCode);
83 | }
84 |
85 | static void HelpMsg(string arg = "")
86 | {
87 | Console.WriteLine(@"Usage: SimpleSourceProtector [Options] ""FullFilePath\Project.cproj"" [output]
88 | * if the output parameter is not specified, a ""output"" folder will be created inside the program directory
89 | Options:
90 | -h show this page
91 | -c do a check compilation before renaming
92 | -m make multiple files, not a single
93 | -dm do not minify
94 | -n do not rename class, methods, vars and etc.
95 | * if -n is not used, then the flags below can be combined:
96 | -rc rename classes
97 | -rm rename methods
98 | -rv rename vars
99 | -ro rename others
100 | -rf remame filenames");
101 | if (!string.IsNullOrEmpty(arg))
102 | Console.WriteLine("\n" + arg);
103 |
104 | Environment.Exit(1);
105 | }
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | [assembly: AssemblyTitle("SimpleSourceProtector")]
5 | [assembly: AssemblyDescription("")]
6 | [assembly: AssemblyConfiguration("")]
7 | [assembly: AssemblyCompany("")]
8 | [assembly: AssemblyProduct("SimpleSourceProtector")]
9 | [assembly: AssemblyCopyright("Copyright © Xariman 2018")]
10 | [assembly: AssemblyTrademark("")]
11 | [assembly: AssemblyCulture("")]
12 |
13 | [assembly: ComVisible(false)]
14 |
15 | [assembly: Guid("4b1dcef4-5a4c-4045-b70e-d26fc6e1c429")]
16 |
17 | [assembly: AssemblyVersion("1.0.0.0")]
18 | [assembly: AssemblyFileVersion("1.0.0.0")]
19 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # SimpleSourceProtector
3 |
4 |
5 | ## About
6 |
7 | The program is designed for simple protection of source codes in C#(not assemblies). A well-compiled project is required for correct operation. In the first stage,
8 | all projects that are in dependence are merged. The next step is renaming the classes, methods, variables, etc. At the final stage, the all documents is merged into
9 | one large document and compression is performed by removing the spaces.
10 |
11 | The project uses Roslyn libraries.
12 |
13 | ## Usage
14 | ```
15 | Usage: SimpleSourceProtector [Options] ""FullFilePath\Project.cproj"" [output]
16 | * if the output parameter is not specified, a ""output"" folder will be created inside the program directory
17 | Options:
18 | -h show this page
19 | -c do a check compilation before renaming
20 | -m make multiple files, not a single
21 | -dm do not minify
22 | -n do not rename class, methods, vars and etc.
23 | * if -n is not used, then the flags below can be combined:
24 | -rc rename classes
25 | -rm rename methods
26 | -rv rename vars
27 | -ro rename others
28 | -rf remame filenames
29 | ```
30 |
31 | © 2018 by Xariman
32 |
--------------------------------------------------------------------------------
/Rewriter.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis;
2 | using Microsoft.CodeAnalysis.CSharp;
3 | using Microsoft.CodeAnalysis.CSharp.Syntax;
4 | using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
5 |
6 | namespace SimpleSourceProtector
7 | {
8 | public class Rewriter : CSharpSyntaxRewriter
9 | {
10 | private readonly SemanticModel SemanticModel;
11 |
12 | public Rewriter(SemanticModel semanticModel) : base(true)
13 | {
14 | this.SemanticModel = semanticModel;
15 | }
16 |
17 | public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
18 | {
19 | if (node.Declaration.Variables.Count > 1)
20 | {
21 | return node;
22 | }
23 | if (node.Declaration.Variables[0].Initializer == null)
24 | {
25 | return node;
26 | }
27 |
28 | VariableDeclaratorSyntax declarator = node.Declaration.Variables.First();
29 | TypeSyntax variableTypeName = node.Declaration.Type;
30 |
31 | ITypeSymbol variableType = (ITypeSymbol)SemanticModel.GetSymbolInfo(variableTypeName).Symbol;
32 |
33 | TypeInfo initializerInfo = SemanticModel.GetTypeInfo(declarator.Initializer.Value);
34 |
35 |
36 | if (variableType == initializerInfo.Type)
37 | {
38 | TypeSyntax varTypeName = IdentifierName("var").WithLeadingTrivia(variableTypeName.GetLeadingTrivia()).WithTrailingTrivia(variableTypeName.GetTrailingTrivia());
39 |
40 | return node.ReplaceNode(variableTypeName, varTypeName);
41 | }
42 | else
43 | {
44 | return node;
45 | }
46 | }
47 |
48 | public override SyntaxNode Visit(SyntaxNode node) => RemoveTriviaSpaces(base.Visit(node));
49 | public override SyntaxNode VisitBlock(BlockSyntax node) => RemoveTriviaSpaces(base.VisitBlock(node));
50 | public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node) => RemoveTriviaSpaces(base.VisitExpressionStatement(node));
51 | public override SyntaxNode VisitEmptyStatement(EmptyStatementSyntax node) => SyntaxFactory.EmptyStatement();
52 |
53 | public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia)
54 | {
55 | if (trivia.IsKind(SyntaxKind.MultiLineCommentTrivia)
56 | || trivia.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia)
57 | || trivia.IsKind(SyntaxKind.SingleLineCommentTrivia)
58 | || trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)
59 | || trivia.IsKind(SyntaxKind.DocumentationCommentExteriorTrivia)
60 | || trivia.IsKind(SyntaxKind.EndOfDocumentationCommentToken)
61 | || trivia.IsKind(SyntaxKind.RegionDirectiveTrivia)
62 | || trivia.IsKind(SyntaxKind.EndRegionDirectiveTrivia)
63 | || trivia.IsKind(SyntaxKind.RegionKeyword)
64 | || trivia.IsKind(SyntaxKind.EndRegionKeyword)
65 | || trivia.IsKind(SyntaxKind.IfDirectiveTrivia)
66 | || trivia.IsKind(SyntaxKind.EndIfDirectiveTrivia)
67 | || trivia.IsKind(SyntaxKind.XmlCommentStartToken)
68 | || trivia.IsKind(SyntaxKind.XmlComment)
69 | || trivia.IsKind(SyntaxKind.XmlCommentEndToken)
70 | || trivia.IsKind(SyntaxKind.DisabledTextTrivia)
71 | )
72 | {
73 | return SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "");
74 | }
75 |
76 | if (trivia.IsKind(SyntaxKind.EndOfLineTrivia))
77 | return SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "");
78 |
79 | if (trivia.IsKind(SyntaxKind.WhitespaceTrivia))
80 | return SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " ");
81 |
82 | return base.VisitTrivia(trivia);
83 | }
84 |
85 | private static SyntaxNode RemoveTriviaSpaces(SyntaxNode node)
86 | {
87 | if (node == null) return node;
88 |
89 | if (node.HasLeadingTrivia)
90 | {
91 | var triviaList = node.GetLeadingTrivia();
92 |
93 | foreach (var trivia in triviaList)
94 | {
95 | if (trivia.IsKind(SyntaxKind.MultiLineCommentTrivia)
96 | || trivia.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia)
97 | || trivia.IsKind(SyntaxKind.SingleLineCommentTrivia)
98 | || trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)
99 | || trivia.IsKind(SyntaxKind.DocumentationCommentExteriorTrivia)
100 | || trivia.IsKind(SyntaxKind.EndOfDocumentationCommentToken)
101 | || trivia.IsKind(SyntaxKind.RegionDirectiveTrivia)
102 | || trivia.IsKind(SyntaxKind.EndRegionDirectiveTrivia)
103 | || trivia.IsKind(SyntaxKind.RegionKeyword)
104 | || trivia.IsKind(SyntaxKind.EndRegionKeyword)
105 | || trivia.IsKind(SyntaxKind.IfDirectiveTrivia)
106 | || trivia.IsKind(SyntaxKind.EndIfDirectiveTrivia)
107 | || trivia.IsKind(SyntaxKind.XmlCommentStartToken)
108 | || trivia.IsKind(SyntaxKind.XmlComment)
109 | || trivia.IsKind(SyntaxKind.XmlCommentEndToken)
110 | || trivia.IsKind(SyntaxKind.DisabledTextTrivia)
111 | )
112 | {
113 | node = node.WithoutLeadingTrivia();
114 | }
115 | if (trivia.IsKind(SyntaxKind.EndOfLineTrivia))
116 | node = node.ReplaceTrivia(trivia, SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, ""));
117 |
118 | if (trivia.IsKind(SyntaxKind.WhitespaceTrivia))
119 | node = node.ReplaceTrivia(trivia, SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "));
120 | }
121 | }
122 | if (node.HasTrailingTrivia)
123 | {
124 | var triviaList = node.GetTrailingTrivia();
125 |
126 | foreach (var trivia in triviaList)
127 | {
128 | if (trivia.IsKind(SyntaxKind.MultiLineCommentTrivia)
129 | || trivia.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia)
130 | || trivia.IsKind(SyntaxKind.SingleLineCommentTrivia)
131 | || trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)
132 | || trivia.IsKind(SyntaxKind.DocumentationCommentExteriorTrivia)
133 | || trivia.IsKind(SyntaxKind.EndOfDocumentationCommentToken)
134 | || trivia.IsKind(SyntaxKind.RegionDirectiveTrivia)
135 | || trivia.IsKind(SyntaxKind.EndRegionDirectiveTrivia)
136 | || trivia.IsKind(SyntaxKind.RegionKeyword)
137 | || trivia.IsKind(SyntaxKind.EndRegionKeyword)
138 | || trivia.IsKind(SyntaxKind.IfDirectiveTrivia)
139 | || trivia.IsKind(SyntaxKind.EndIfDirectiveTrivia)
140 | || trivia.IsKind(SyntaxKind.XmlCommentStartToken)
141 | || trivia.IsKind(SyntaxKind.XmlComment)
142 | || trivia.IsKind(SyntaxKind.XmlCommentEndToken)
143 | || trivia.IsKind(SyntaxKind.DisabledTextTrivia)
144 | )
145 | {
146 | node = node.WithoutTrailingTrivia();
147 | }
148 | if (trivia.IsKind(SyntaxKind.EndOfLineTrivia))
149 | node = node.ReplaceTrivia(trivia, SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, ""));
150 |
151 | if (trivia.IsKind(SyntaxKind.WhitespaceTrivia))
152 | node = node.ReplaceTrivia(trivia, SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "));
153 | }
154 | }
155 | return node;
156 | }
157 |
158 | }
159 | }
--------------------------------------------------------------------------------
/SimpleSourceProtector.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {4B1DCEF4-5A4C-4045-B70E-D26FC6E1C429}
8 | Exe
9 | SimpleSourceProtector
10 | SimpleSourceProtector
11 | v4.6.1
12 | 512
13 | true
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 | SimpleSourceProtector.Program
36 |
37 |
38 |
39 | packages\Microsoft.CodeAnalysis.Common.2.8.0\lib\netstandard1.3\Microsoft.CodeAnalysis.dll
40 |
41 |
42 | packages\Microsoft.CodeAnalysis.CSharp.2.8.0\lib\netstandard1.3\Microsoft.CodeAnalysis.CSharp.dll
43 |
44 |
45 | packages\Microsoft.CodeAnalysis.CSharp.Workspaces.2.8.0\lib\netstandard1.3\Microsoft.CodeAnalysis.CSharp.Workspaces.dll
46 |
47 |
48 | packages\Microsoft.CodeAnalysis.Workspaces.Common.2.8.0\lib\net46\Microsoft.CodeAnalysis.Workspaces.dll
49 |
50 |
51 | packages\Microsoft.CodeAnalysis.Workspaces.Common.2.8.0\lib\net46\Microsoft.CodeAnalysis.Workspaces.Desktop.dll
52 |
53 |
54 |
55 | packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll
56 |
57 |
58 | packages\System.Collections.Immutable.1.3.1\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll
59 | True
60 |
61 |
62 |
63 | packages\System.Composition.AttributedModel.1.0.31\lib\portable-net45+win8+wp8+wpa81\System.Composition.AttributedModel.dll
64 |
65 |
66 | packages\System.Composition.Convention.1.0.31\lib\portable-net45+win8+wp8+wpa81\System.Composition.Convention.dll
67 |
68 |
69 | packages\System.Composition.Hosting.1.0.31\lib\portable-net45+win8+wp8+wpa81\System.Composition.Hosting.dll
70 |
71 |
72 | packages\System.Composition.Runtime.1.0.31\lib\portable-net45+win8+wp8+wpa81\System.Composition.Runtime.dll
73 |
74 |
75 | packages\System.Composition.TypedParts.1.0.31\lib\portable-net45+win8+wp8+wpa81\System.Composition.TypedParts.dll
76 |
77 |
78 | packages\System.Console.4.3.0\lib\net46\System.Console.dll
79 |
80 |
81 |
82 | packages\System.Diagnostics.FileVersionInfo.4.3.0\lib\net46\System.Diagnostics.FileVersionInfo.dll
83 |
84 |
85 | packages\System.Diagnostics.StackTrace.4.3.0\lib\net46\System.Diagnostics.StackTrace.dll
86 |
87 |
88 | packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll
89 | True
90 |
91 |
92 | packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll
93 |
94 |
95 | packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll
96 |
97 |
98 |
99 | packages\System.Reflection.Metadata.1.4.2\lib\portable-net45+win8\System.Reflection.Metadata.dll
100 |
101 |
102 | packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll
103 |
104 |
105 | packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll
106 |
107 |
108 | packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll
109 |
110 |
111 | packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll
112 |
113 |
114 | packages\System.Text.Encoding.CodePages.4.3.0\lib\net46\System.Text.Encoding.CodePages.dll
115 |
116 |
117 | packages\System.Threading.Thread.4.3.0\lib\net46\System.Threading.Thread.dll
118 |
119 |
120 | packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 | packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll
130 |
131 |
132 | packages\System.Xml.XmlDocument.4.3.0\lib\net46\System.Xml.XmlDocument.dll
133 |
134 |
135 | packages\System.Xml.XPath.4.3.0\lib\net46\System.Xml.XPath.dll
136 |
137 |
138 | packages\System.Xml.XPath.XDocument.4.3.0\lib\net46\System.Xml.XPath.XDocument.dll
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
--------------------------------------------------------------------------------
/SimpleSourceProtector.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.27130.2003
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleSourceProtector", "SimpleSourceProtector.csproj", "{4B1DCEF4-5A4C-4045-B70E-D26FC6E1C429}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {4B1DCEF4-5A4C-4045-B70E-D26FC6E1C429}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {4B1DCEF4-5A4C-4045-B70E-D26FC6E1C429}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {4B1DCEF4-5A4C-4045-B70E-D26FC6E1C429}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {4B1DCEF4-5A4C-4045-B70E-D26FC6E1C429}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {AE5EFAE0-9A0D-4EB8-9324-84C61A67C511}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/UsingRewriter.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis;
2 | using Microsoft.CodeAnalysis.CSharp;
3 | using Microsoft.CodeAnalysis.CSharp.Syntax;
4 | using System.Collections.Generic;
5 |
6 | namespace SimpleSourceProtector
7 | {
8 | public class UsingRewriter : CSharpSyntaxRewriter
9 | {
10 | private readonly SemanticModel SemanticModel;
11 |
12 | private List m_temp = new List();
13 | public UsingRewriter(SemanticModel semanticModel) : base(true)
14 | {
15 | this.SemanticModel = semanticModel;
16 | }
17 |
18 | public override SyntaxNode VisitUsingDirective(UsingDirectiveSyntax node)
19 | {
20 | m_temp.Add(node);
21 | return null;
22 | }
23 |
24 | public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
25 | {
26 | SyntaxList list = new SyntaxList();
27 | list = list.AddRange(m_temp);
28 | return node.WithUsings(list);
29 | }
30 | }
31 | }
--------------------------------------------------------------------------------
/Utils.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text.RegularExpressions;
4 |
5 | namespace SimpleSourceProtector
6 | {
7 | public static class Utils
8 | {
9 | private static Random m_rand = new Random((int)DateTime.Now.Ticks);
10 | public static Random Random { get { return m_rand; } }
11 | private const string m_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
12 | private static HashSet m_generatedList = new HashSet();
13 |
14 | public static string RandomString(int minSize = 1, int maxSize = 8, int minAddNums = 0, int maxAddNums = 5)
15 | {
16 | var size = m_rand.Next(minSize, maxSize);
17 | var nums = m_rand.Next(minAddNums, maxAddNums);
18 |
19 | char[] buffer = new char[size + nums];
20 |
21 | string str;
22 | do
23 | {
24 | for (int i = 0; i < size + nums; i++)
25 | buffer[i] = (i < size) ? m_chars[m_rand.Next(m_chars.Length)] : (char)m_rand.Next('0', '9' + 1);
26 | str = new string(buffer);
27 | } while (m_generatedList.Contains(str));
28 |
29 | m_generatedList.Add(str);
30 |
31 | return str;
32 | }
33 |
34 | public static string Unformat(string str)
35 | {
36 | var list = str.Replace(@"\""", "&pqute;").Split('"');
37 | for (int i = 0; i < list.Length; i++)
38 | {
39 | if (i % 2 != 0)
40 | continue;
41 | list[i] = Regex.Replace(list[i], @"\s+", " ", RegexOptions.Compiled);
42 | list[i] = Regex.Replace(list[i], @"\s*([\+\-\=\*\/\|\&\!\%\,\<\>\{\}\;\[\]\(\)]+)\s*", (Match match) => match.Groups[1].Value, RegexOptions.Compiled);
43 | }
44 |
45 | return string.Join("\"", list).Replace("&pqute;", @"\""");
46 | }
47 |
48 | }
49 |
50 | public static class IListExtensions
51 | {
52 | public static void Shuffle(this IList ts)
53 | {
54 | var count = ts.Count;
55 | var last = count - 1;
56 | for (var i = 0; i < last; ++i)
57 | {
58 | var r = Utils.Random.Next(i, count);
59 | var tmp = ts[i];
60 | ts[i] = ts[r];
61 | ts[r] = tmp;
62 | }
63 | }
64 | }
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/Watcher.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Diagnostics;
3 |
4 | namespace SimpleSourceProtector
5 | {
6 | public class Watcher : IDisposable
7 | {
8 | private Stopwatch _stopwatch = new Stopwatch();
9 | private Action _callback;
10 |
11 | public Watcher()
12 | {
13 | _stopwatch.Start();
14 | }
15 |
16 | public Watcher(Action callback) : this()
17 | {
18 | _callback = callback;
19 | }
20 |
21 | public static Watcher Start(Action callback)
22 | {
23 | return new Watcher(callback);
24 | }
25 |
26 | public void Dispose()
27 | {
28 | _stopwatch.Stop();
29 | if (_callback != null)
30 | _callback(Result);
31 | }
32 |
33 | public TimeSpan Result
34 | {
35 | get { return _stopwatch.Elapsed; }
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------