Skip to content

Commit 98c0b8b

Browse files
committed
Scaled back Trace. Code cleanup.
1 parent 958bb47 commit 98c0b8b

File tree

3 files changed

+13
-72
lines changed

3 files changed

+13
-72
lines changed

src/Org.Security.Cryptography.X509Extensions/MyTrace.cs

Lines changed: 3 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,16 @@
11

22
using System;
33
using System.Diagnostics;
4-
using System.Runtime.CompilerServices;
54
using System.Text;
65

76
namespace Org.Security.Cryptography
87
{
98
internal static class MyTrace
109
{
11-
// Trace switch name: Org.Security.Cryptography
12-
static readonly string MyName = typeof(MyTrace).Namespace;
13-
14-
// Making TraceSwitch update-able, because of the .Net core MESS (I meant, one of the .Net core messes)
15-
// .Net core applications WILL NOT honor TraceSwitch in config files.
16-
// Use X509Extensions.TraceLevel property
17-
internal static TraceSwitch MyTraceSwitch { get; set; } = new TraceSwitch(MyName, MyName, $"{TraceLevel.Warning}");
18-
19-
[Conditional("DEBUG")]
20-
[MethodImpl(MethodImplOptions.AggressiveInlining)]
21-
internal static void Entering([CallerMemberName] string memberName = "") => WriteIf(MyTraceSwitch.TraceVerbose, () => $"--> {memberName}()");
10+
static readonly string ME = typeof(MyTrace).Namespace;
2211

2312
[Conditional("DEBUG")]
24-
[MethodImpl(MethodImplOptions.AggressiveInlining)]
25-
internal static void Verbose(Func<string> fxMessage) => WriteIf(MyTraceSwitch.TraceVerbose, fxMessage);
26-
27-
[MethodImpl(MethodImplOptions.AggressiveInlining)]
28-
internal static void Info(Func<string> fxMessage) => WriteIf(MyTraceSwitch.TraceInfo, fxMessage);
29-
30-
[MethodImpl(MethodImplOptions.AggressiveInlining)]
31-
internal static void Warn(Func<string> fxMessage) => WriteIf(MyTraceSwitch.TraceWarning, fxMessage);
32-
33-
[MethodImpl(MethodImplOptions.AggressiveInlining)]
34-
internal static void Error(Func<string> fxMessage) => Write(fxMessage);
35-
36-
[MethodImpl(MethodImplOptions.AggressiveInlining)]
37-
static void WriteIf(bool condition, Func<string> fxMessage)
38-
{
39-
if (condition) Trace.WriteLine($"{MyName}: {fxMessage()}");
40-
}
41-
42-
[MethodImpl(MethodImplOptions.AggressiveInlining)]
43-
static void Write(Func<string> fxMessage)
44-
{
45-
Trace.WriteLine($"{MyName}: {fxMessage()}");
46-
}
13+
internal static void Info(Func<string> fxMessage) => Trace.WriteLine($"{ME}: {fxMessage()}");
4714

4815
internal static void Error(Exception err)
4916
{
@@ -57,7 +24,7 @@ internal static void Error(Exception err)
5724
var buffer = new StringBuilder();
5825

5926
// The exception chain...
60-
buffer.AppendLine($"{MyName}: An error occured at {DateTime.UtcNow} UTC");
27+
buffer.AppendLine($"ERROR: {ME} / {DateTime.UtcNow} UTC");
6128
while (null != err)
6229
{
6330
buffer.AppendLine(err.Message);

src/Org.Security.Cryptography.X509Extensions/X509Extensions.cs

Lines changed: 10 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11

22
using System;
3-
using System.Diagnostics;
43
using System.IO;
54
using System.Security.Cryptography;
65
using System.Security.Cryptography.X509Certificates;
@@ -48,12 +47,10 @@ public static void EncryptUsingPublicKey(this X509Certificate2 x509WithPublicKey
4847
if (null == outputStream) throw new ArgumentNullException(nameof(outputStream));
4948
if (null == dataEncryptionAlgorithmName) throw new ArgumentNullException(nameof(dataEncryptionAlgorithmName));
5049

51-
MyTrace.Entering();
52-
5350
try
5451
{
55-
if (null == x509WithPublicKey.PublicKey) throw new ArgumentException("X509Certificate2.PublicKey was NULL.");
56-
if (null == x509WithPublicKey.PublicKey.Key) throw new ArgumentException("X509Certificate2.PublicKey.Key was NULL.");
52+
if (null == x509WithPublicKey.PublicKey) throw new Exception($"X509Certificate2.PublicKey was NULL. Cert: {x509WithPublicKey.Thumbprint}");
53+
if (null == x509WithPublicKey.PublicKey.Key) throw new Exception($"X509Certificate2.PublicKey.Key was NULL. Cert: {x509WithPublicKey.Thumbprint}");
5754

5855
// IMP: We didn't create the Cert. DO NOT DISPOSE.
5956
// IMP: Disposing the AsymmetricAlgorithm will render the X509Certificate2 useless for subsequent use.
@@ -63,26 +60,28 @@ public static void EncryptUsingPublicKey(this X509Certificate2 x509WithPublicKey
6360
{
6461
if (null == dataEncryptionAlgorithm) throw new Exception($"SymmetricAlgorithm.Create('{dataEncryptionAlgorithmName}') returned NULL.");
6562

63+
// Set desired key and block size.
64+
// This may throw an excepion on invalid key/block sizes.
6665
dataEncryptionAlgorithm.KeySize = keySize;
6766
dataEncryptionAlgorithm.BlockSize = blockSize;
6867

6968
// The DataEncryptionKey and IV.
70-
byte[] dataEncryptionKey = dataEncryptionAlgorithm.Key;
71-
byte[] dataEncryptionIV = dataEncryptionAlgorithm.IV;
69+
byte[] dataEncryptionKey = dataEncryptionAlgorithm.Key ?? throw new Exception("dataEncryptionAlgorithm.Key was NULL.");
70+
byte[] dataEncryptionIV = dataEncryptionAlgorithm.IV ?? throw new Exception("dataEncryptionAlgorithm.IV was NULL.");
7271

7372
// Encrypt the DEK using the X509 public key (KEK).
7473
var keyFormatter = new RSAPKCS1KeyExchangeFormatter(keyEncryptionAlgorithm);
7574
byte[] encryptedDataEncryptionKey = keyFormatter.CreateKeyExchange(dataEncryptionKey);
7675

77-
// Debug information (Set Trace to warning or above for PRD)
76+
// Essential debug information...
7877
MyTrace.Info(() => $"KEK: {keyEncryptionAlgorithm.GetType().Name} / {keyEncryptionAlgorithm.KeySize} bits / {x509WithPublicKey.Thumbprint}");
7978
MyTrace.Info(() => $"DEK: {dataEncryptionAlgorithm.GetType().Name} / {dataEncryptionAlgorithm.KeySize} bits. / BlockSize: {dataEncryptionAlgorithm.BlockSize} bits.");
8079

81-
// Write the length & bytes of encrypted DEK and IV
80+
// Write the EncryptedDEK and the IV (length & bytes)
8281
outputStream.WriteLengthAndBytes(encryptedDataEncryptionKey);
8382
outputStream.WriteLengthAndBytes(dataEncryptionIV);
8483

85-
// Write Data
84+
// Write encrypted data
8685
using (var transform = dataEncryptionAlgorithm.CreateEncryptor())
8786
using (var cryptoStream = new CryptoStream(outputStream, transform, CryptoStreamMode.Write))
8887
{
@@ -110,16 +109,9 @@ public static void DecryptUsingPrivateKey(this X509Certificate2 x509WithPrivateK
110109
if (null == x509WithPrivateKey) throw new ArgumentNullException(nameof(x509WithPrivateKey));
111110
if (null == dataEncryptionAlgorithmName) throw new ArgumentNullException(nameof(dataEncryptionAlgorithmName));
112111

113-
MyTrace.Entering();
114-
115-
// Data Encryption key (DEK) is read from the stream.
116-
// DEK itself comes encrypted using the Key encryption key (KEK)
117-
// Use X509 cert private key to decrypt the DEK
118-
// Use the DEK to decrypt the data
119-
120112
try
121113
{
122-
if (null == x509WithPrivateKey.PrivateKey) throw new ArgumentException("X509Certificate2.PrivateKey was NULL.");
114+
if (null == x509WithPrivateKey.PrivateKey) throw new Exception($"X509Certificate2.PrivateKey was NULL. Cert: {x509WithPrivateKey.Thumbprint}");
123115

124116
// IMP: We didn't create the Cert. DO NOT DISPOSE.
125117
// IMP: Disposing the AsymmetricAlgorithm will render the X509Certificate2 useless for subsequent use.
@@ -234,18 +226,6 @@ static Int32 ReadInt32(this Stream inputStream)
234226

235227
return BitConverter.ToInt32(fourBytes, startIndex: 0);
236228
}
237-
238-
/// <summary>
239-
/// Because, .Net core doesn't honor TraceSwitches from the config files.
240-
/// Try TraceSwitch "Org.Security.Cryptography" in config files.
241-
/// If it doesn't work, update me.
242-
/// </summary>
243-
public static TraceLevel TraceLevel
244-
{
245-
set {
246-
MyTrace.MyTraceSwitch = new TraceSwitch("", "", value.ToString());
247-
}
248-
}
249229
}
250230
}
251231

src/UnitTests/X509Tests.cs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,6 @@ public class X509Tests
2020

2121
const string CertThumbPrint = "2E3257EE8FC8A72DB3778DFB3F9EDC7D0A9D66C7";
2222

23-
[TestInitialize]
24-
public void TestInitialize()
25-
{
26-
X509Extensions.TraceLevel = TraceLevel.Info;
27-
}
28-
2923

3024
[TestMethod]
3125
public void FindCertificateTest()

0 commit comments

Comments
 (0)