Skip to content

Commit de108db

Browse files
committed
Code Cleanup
1 parent c6aa308 commit de108db

File tree

13 files changed

+104
-184
lines changed

13 files changed

+104
-184
lines changed

src/EasySign.Cli/BundleCommandProvider.cs

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,4 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.CommandLine;
4-
using System.Linq;
5-
using System.Text;
6-
using System.Threading.Tasks;
1+
using System.CommandLine;
72

83
using Microsoft.Extensions.Logging;
94

@@ -13,7 +8,7 @@ namespace SAPTeam.EasySign.Cli
138
{
149
internal class BundleCommandProvider : CommandProvider<Bundle>
1510
{
16-
ILogger _bundleLogger;
11+
private readonly ILogger _bundleLogger;
1712

1813
public BundleCommandProvider(ILogger logger, ILogger bundleLogger)
1914
{
@@ -29,7 +24,7 @@ public override void InitializeBundle(string bundlePath)
2924

3025
public override RootCommand GetRootCommand()
3126
{
32-
var root = new RootCommand("Easy Digital Signing Tool")
27+
RootCommand root = new RootCommand("Easy Digital Signing Tool")
3328
{
3429
Add,
3530
Sign,

src/EasySign.Cli/Program.cs

Lines changed: 8 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,13 @@
1-
using System.Collections.Concurrent;
2-
using System.CommandLine;
3-
using System.IO;
4-
using System.Security.Cryptography;
5-
using System.Security.Cryptography.X509Certificates;
6-
using System.Text;
7-
8-
using Microsoft.Extensions.DependencyInjection;
9-
using Microsoft.Extensions.Logging;
1+
using System.CommandLine;
102

113
using Serilog;
124
using Serilog.Extensions.Logging;
135

14-
using Spectre.Console;
15-
166
namespace SAPTeam.EasySign.Cli
177
{
188
internal class Program
199
{
20-
static int Main(string[] args)
10+
private static int Main(string[] args)
2111
{
2212
Log.Logger = new LoggerConfiguration()
2313
.Enrich.WithThreadId()
@@ -29,23 +19,22 @@ static int Main(string[] args)
2919
.MinimumLevel.Debug() // Minimum log level
3020
.CreateLogger();
3121

32-
var appLogger = Log.Logger.ForContext("Context", "Main");
22+
Serilog.ILogger appLogger = Log.Logger.ForContext("Context", "Main");
3323
appLogger.Information("Starting EasySign CLI at {DateTime}", DateTime.Now);
3424

35-
var bundleLogger = new SerilogLoggerFactory(Log.Logger.ForContext("Context", "Bundle"))
25+
Microsoft.Extensions.Logging.ILogger bundleLogger = new SerilogLoggerFactory(Log.Logger.ForContext("Context", "Bundle"))
3626
.CreateLogger("CommandProvider");
37-
38-
var commandProviderLogger = new SerilogLoggerFactory(Log.Logger.ForContext("Context", "CommandProvider"))
27+
28+
Microsoft.Extensions.Logging.ILogger commandProviderLogger = new SerilogLoggerFactory(Log.Logger.ForContext("Context", "CommandProvider"))
3929
.CreateLogger("CommandProvider");
4030

41-
var root = new BundleCommandProvider(commandProviderLogger, bundleLogger).GetRootCommand();
42-
var exitCode = root.Invoke(args);
31+
RootCommand root = new BundleCommandProvider(commandProviderLogger, bundleLogger).GetRootCommand();
32+
int exitCode = root.Invoke(args);
4333

4434
appLogger.Information("Shutting down EasySign CLI at {DateTime} with exit code {ExitCode}", DateTime.Now, exitCode);
4535

4636
Log.CloseAndFlush();
4737
return exitCode;
4838
}
49-
5039
}
5140
}

src/EasySign.CommandLine/BundleWorker.cs

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Security.Cryptography.X509Certificates;
4-
using System.Text;
1+
using System.Security.Cryptography.X509Certificates;
52

63
using Microsoft.Extensions.Logging;
74

@@ -54,15 +51,15 @@ protected virtual void RunAdd(StatusContext statusContext, bool replace, bool co
5451
statusContext.Status("[yellow]Adding Files[/]");
5552

5653
Logger.LogDebug("Discovering files in the directory: {RootPath}", Bundle.RootPath);
57-
var foundFiles = Utilities.SafeEnumerateFiles(Bundle.RootPath, "*").ToArray();
54+
string[] foundFiles = Utilities.SafeEnumerateFiles(Bundle.RootPath, "*").ToArray();
5855
Logger.LogInformation("Discovered {FileCount} files", foundFiles.Count());
5956

6057
Logger.LogInformation("Starting file adder multi-thread task");
6158
bool errorOccurred = false;
6259
_ = Parallel.ForEach(foundFiles, (file, state) =>
6360
{
6461
if (file == Bundle.BundlePath) return;
65-
var entryName = Manifest.GetNormalizedEntryName(Path.GetRelativePath(Bundle.RootPath, file));
62+
string entryName = Manifest.GetNormalizedEntryName(Path.GetRelativePath(Bundle.RootPath, file));
6663

6764
Logger.LogInformation("Processing file: {EntryName}", entryName);
6865

@@ -88,7 +85,7 @@ protected virtual void RunAdd(StatusContext statusContext, bool replace, bool co
8885
else
8986
{
9087
Logger.LogDebug("Adding entry: {EntryName}", entryName);
91-
88+
9289
Bundle.AddEntry(file);
9390

9491
Logger.LogInformation("Entry: {EntryName} Added", entryName);
@@ -159,14 +156,14 @@ protected virtual void RunSign(StatusContext statusContext, X509Certificate2Coll
159156
int divider = 0;
160157
int signs = 0;
161158

162-
foreach (var cert in certificates)
159+
foreach (X509Certificate2 cert in certificates)
163160
{
164161
if (divider++ > 0) AnsiConsole.WriteLine();
165162

166163
Logger.LogDebug("Loading certificate information for {Cert}", cert);
167164
statusContext.Status("[yellow]Loading certificate informations[/]");
168165

169-
var grid = new Grid();
166+
Grid grid = new Grid();
170167
grid.AddColumn(new GridColumn().NoWrap());
171168
grid.AddColumn(new GridColumn().PadLeft(2));
172169
grid.AddRow("Certificate Info:");
@@ -193,7 +190,7 @@ protected virtual void RunSign(StatusContext statusContext, X509Certificate2Coll
193190
Logger.LogDebug("Acquiring RSA private key for {cert}", cert);
194191
statusContext.Status("[yellow]Preparing for signing[/]");
195192

196-
var prvKey = cert.GetRSAPrivateKey();
193+
System.Security.Cryptography.RSA? prvKey = cert.GetRSAPrivateKey();
197194
if (prvKey == null)
198195
{
199196
Logger.LogError("Failed to acquire RSA private key for {cert}", cert);
@@ -239,7 +236,7 @@ protected virtual void RunVerify(StatusContext statusContext)
239236
throw new ApplicationException("Bundle is not initialized");
240237
}
241238

242-
var colorDict = new Dictionary<string, Color>()
239+
Dictionary<string, Color> colorDict = new Dictionary<string, Color>()
243240
{
244241
["file_verified"] = Color.MediumSpringGreen,
245242
["file_failed"] = Color.OrangeRed1,
@@ -257,24 +254,24 @@ protected virtual void RunVerify(StatusContext statusContext)
257254
int verifiedCerts = 0;
258255
int divider = 0;
259256

260-
foreach (var certificateHash in Bundle.Signatures.Entries.Keys)
257+
foreach (string certificateHash in Bundle.Signatures.Entries.Keys)
261258
{
262259
if (divider++ > 0) AnsiConsole.WriteLine();
263260

264-
var certificate = Bundle.GetCertificate(certificateHash);
261+
X509Certificate2 certificate = Bundle.GetCertificate(certificateHash);
265262

266263
Logger.LogDebug("Verifying certificate {cert}", certificate);
267264
AnsiConsole.MarkupLine($"Verifying Certificate [{Color.Teal}]{certificate.GetNameInfo(X509NameType.SimpleName, false)}[/] Issued by [{Color.Aqua}]{certificate.GetNameInfo(X509NameType.SimpleName, true)}[/]");
268265

269-
var verifyCert = VerifyCertificate(certificate);
266+
bool verifyCert = VerifyCertificate(certificate);
270267
if (!verifyCert)
271268
{
272269
Logger.LogWarning("Skipping signature verification for {cert}", certificate);
273270
continue;
274271
}
275272

276273
Logger.LogDebug("Verifying signature for certificate {cert}", certificate);
277-
var verifySign = Bundle.VerifySignature(certificateHash);
274+
bool verifySign = Bundle.VerifySignature(certificateHash);
278275
AnsiConsole.MarkupLine($"[{(verifySign ? Color.Green : Color.Red)}] Signature Verification {(verifySign ? "Successful" : "Failed")}[/]");
279276
if (!verifySign)
280277
{
@@ -326,7 +323,7 @@ protected virtual void RunVerify(StatusContext statusContext)
326323

327324
_ = Parallel.ForEach(Bundle.Manifest.Entries, (entry) =>
328325
{
329-
var verifyFile = false;
326+
bool verifyFile = false;
330327

331328
Logger.LogDebug("Verifying file {file}", entry.Key);
332329

@@ -399,10 +396,10 @@ protected bool VerifyCertificate(X509Certificate2 certificate)
399396
throw new ApplicationException("Bundle is not initialized");
400397
}
401398

402-
List<bool> verifyResults = new();
399+
List<bool> verifyResults = [];
403400

404401
Logger.LogDebug("Verifying certificate {cert} with default verification policy", certificate);
405-
var defaultVerification = Bundle.VerifyCertificate(certificate, out X509ChainStatus[] statuses);
402+
bool defaultVerification = Bundle.VerifyCertificate(certificate, out X509ChainStatus[] statuses);
406403
verifyResults.Add(defaultVerification);
407404

408405
Logger.LogInformation("Certificate verification with default policy for {cert}: {result}", certificate, defaultVerification);
@@ -418,10 +415,10 @@ protected bool VerifyCertificate(X509Certificate2 certificate)
418415
{
419416
Logger.LogWarning("Certificate has time validity issues, retrying verification with time check disabled");
420417

421-
var policy = new X509ChainPolicy();
418+
X509ChainPolicy policy = new X509ChainPolicy();
422419
policy.VerificationFlags |= X509VerificationFlags.IgnoreNotTimeValid;
423420

424-
var noTimeVerification = Bundle.VerifyCertificate(certificate, out X509ChainStatus[] noTimeStatuses, policy: policy);
421+
bool noTimeVerification = Bundle.VerifyCertificate(certificate, out X509ChainStatus[] noTimeStatuses, policy: policy);
425422
verifyResults.Add(noTimeVerification);
426423

427424
Logger.LogInformation("Certificate verification without time checking for {cert}: {result}", certificate, noTimeVerification);

src/EasySign.CommandLine/CommandProvider.cs

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,9 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.CommandLine;
1+
using System.CommandLine;
42
using System.Security.Cryptography.X509Certificates;
5-
using System.Text;
63

74
using Microsoft.Extensions.Logging;
85
using Microsoft.Extensions.Logging.Abstractions;
96

10-
using Spectre.Console;
11-
127
namespace SAPTeam.EasySign.CommandLine
138
{
149
/// <summary>
@@ -41,13 +36,13 @@ public Command Add
4136
{
4237
get
4338
{
44-
var replaceOpt = new Option<bool>("--replace", "Replace existing entries");
39+
Option<bool> replaceOpt = new Option<bool>("--replace", "Replace existing entries");
4540
replaceOpt.AddAlias("-r");
4641

47-
var continueOpt = new Option<bool>("--continue", "Continue adding files if an error occurs");
42+
Option<bool> continueOpt = new Option<bool>("--continue", "Continue adding files if an error occurs");
4843
continueOpt.AddAlias("-c");
4944

50-
var command = new Command("add", "Create new bundle or update an existing one")
45+
Command command = new Command("add", "Create new bundle or update an existing one")
5146
{
5247
BundlePath,
5348
replaceOpt,
@@ -71,11 +66,11 @@ public Command Sign
7166
{
7267
get
7368
{
74-
var pfxOpt = new Option<string>("--pfx", "PFX File contains certificate and private key");
75-
var pfxPassOpt = new Option<string>("--pfx-password", "PFX File password");
76-
var pfxNoPassOpt = new Option<bool>("--no-password", "Ignore PFX File password prompt");
69+
Option<string> pfxOpt = new Option<string>("--pfx", "PFX File contains certificate and private key");
70+
Option<string> pfxPassOpt = new Option<string>("--pfx-password", "PFX File password");
71+
Option<bool> pfxNoPassOpt = new Option<bool>("--no-password", "Ignore PFX File password prompt");
7772

78-
var command = new Command("sign", "Sign bundle with certificate")
73+
Command command = new Command("sign", "Sign bundle with certificate")
7974
{
8075
BundlePath,
8176
pfxOpt,
@@ -102,7 +97,7 @@ public Command Verify
10297
{
10398
get
10499
{
105-
var command = new Command("verify", "Verify bundle")
100+
Command command = new Command("verify", "Verify bundle")
106101
{
107102
BundlePath,
108103
};

src/EasySign.CommandLine/Utilities.cs

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
1-
using System;
2-
using System.Linq;
3-
using System.Collections.Concurrent;
4-
using System.Collections.Generic;
1+
using System.Collections.Concurrent;
52
using System.Security.Cryptography.X509Certificates;
6-
using System.Text;
73

84
using Spectre.Console;
95

@@ -80,22 +76,24 @@ public static IEnumerable<string> SafeEnumerateFiles(string path, string searchP
8076
/// <returns>A collection of certificates.</returns>
8177
public static X509Certificate2Collection GetCertificates(string pfxFilePath, string pfxFilePassword, bool pfxNoPasswordPrompt)
8278
{
83-
X509Certificate2Collection collection = new();
79+
X509Certificate2Collection collection = [];
8480

8581
if (!string.IsNullOrEmpty(pfxFilePath))
8682
{
8783
string pfpass = !string.IsNullOrEmpty(pfxFilePassword) ? pfxFilePassword : !pfxNoPasswordPrompt ? SecurePrompt("Enter PFX File password (if needed): ") : "";
8884

8985
#if NET9_0_OR_GREATER
90-
var tempCollection = X509CertificateLoader.LoadPkcs12CollectionFromFile(pfxFilePath, pfpass, X509KeyStorageFlags.EphemeralKeySet);
86+
X509Certificate2Collection tempCollection = X509CertificateLoader.LoadPkcs12CollectionFromFile(pfxFilePath, pfpass, X509KeyStorageFlags.EphemeralKeySet);
9187
#else
92-
var tempCollection = new X509Certificate2Collection();
88+
X509Certificate2Collection tempCollection = [];
9389
tempCollection.Import(pfxFilePath, pfpass, X509KeyStorageFlags.EphemeralKeySet);
9490
#endif
9591

96-
var cond = tempCollection.Where(x => x.HasPrivateKey);
92+
IEnumerable<X509Certificate2> cond = tempCollection.Where(x => x.HasPrivateKey);
9793
if (cond.Any())
94+
{
9895
collection.AddRange(cond.ToArray());
96+
}
9997
else
10098
{
10199
collection.AddRange(tempCollection);
@@ -106,13 +104,13 @@ public static X509Certificate2Collection GetCertificates(string pfxFilePath, str
106104
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
107105
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
108106

109-
var mapping = new Dictionary<string, X509Certificate2>();
110-
foreach (var cert in store.Certificates)
107+
Dictionary<string, X509Certificate2> mapping = [];
108+
foreach (X509Certificate2 cert in store.Certificates)
111109
{
112110
mapping[$"{cert.GetNameInfo(X509NameType.SimpleName, false)},{cert.GetNameInfo(X509NameType.SimpleName, true)},{cert.Thumbprint}"] = cert;
113111
}
114112

115-
var selection = AnsiConsole.Prompt(
113+
List<string> selection = AnsiConsole.Prompt(
116114
new MultiSelectionPrompt<string>()
117115
.PageSize(10)
118116
.Title("Select Signing Certificates")
@@ -146,7 +144,7 @@ public static string SecurePrompt(string prompt)
146144
/// <param name="statuses">The array of X509 chain statuses.</param>
147145
public static void EnumerateStatuses(X509ChainStatus[] statuses)
148146
{
149-
foreach (var status in statuses)
147+
foreach (X509ChainStatus status in statuses)
150148
{
151149
AnsiConsole.MarkupLine($"[{Color.IndianRed}] {status.StatusInformation}[/]");
152150
}

0 commit comments

Comments
 (0)