Skip to content

Commit

Permalink
Refactor Aggregrated Value and add related unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Maxhy committed Oct 18, 2023
1 parent 44dbdd0 commit 44f3c74
Show file tree
Hide file tree
Showing 18 changed files with 244 additions and 144 deletions.
4 changes: 2 additions & 2 deletions KeyManager.Library.KeyStore.HSM_PKCS11/PKCS11KeyStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public override async Task Create(IChangeKeyEntry change)
{
foreach (var material in entry.Variant.KeyContainers[0].Key.Materials)
{
var rawkey = material.GetFormattedValue<byte[]>(KeyValueFormat.Binary);
var rawkey = material.GetValueBinary();
if (rawkey != null)
{
var attributes = GetKeyEntryAttributes(entry, true);
Expand Down Expand Up @@ -586,7 +586,7 @@ public override async Task Update(IChangeKeyEntry change, bool ignoreIfMissing)
var attributes = GetKeyEntryAttributes(entry);
if (entry.Variant?.KeyContainers.Count == 1)
{
var rawkey = entry.Variant.KeyContainers[0].Key.GetAggregatedValue<byte[]>(KeyValueFormat.Binary);
var rawkey = entry.Variant.KeyContainers[0].Key.GetAggregatedValueBinary();
if (rawkey != null)
{
// We should already have only one key material during an update
Expand Down
4 changes: 2 additions & 2 deletions KeyManager.Library.KeyStore.LCP/LCPKeyStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ public override async Task Delete(KeyEntryId identifier, KeyEntryClass keClass,
var kc = ke.Variant.KeyContainers[0];
if (!string.IsNullOrEmpty(key.Value))
{
kc.Key.SetAggregatedValue(key.Value);
kc.Key.SetAggregatedValueString(key.Value);
}
if (kc is KeyVersion kv && key.Version != null)
{
Expand Down Expand Up @@ -280,7 +280,7 @@ private static CredentialKey CreateCredentialKey(KeyEntryId identifier, KeyConta
}
if (kc != null)
{
var rawkey = kc.Key.GetAggregatedValue<byte[]>(KeyValueFormat.Binary);
var rawkey = kc.Key.GetAggregatedValueBinary();
key.Value = (rawkey != null) ? Convert.ToHexString(rawkey) : null;
}
if (!string.IsNullOrEmpty(kc?.Key.Link?.KeyStoreFavorite))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ private void SAMAuthenticate()
key.setKeyType(LibLogicalAccess.Card.DESFireKeyType.DF_KEY_3K3DES);
}

key.fromString(SAMAuthKey.Key.GetAggregatedValue<string>(KeyValueFormat.HexStringWithSpace));
key.fromString(SAMAuthKey.Key.GetAggregatedValueString(KeyValueStringFormat.HexStringWithSpace));
key.setKeyVersion(SAMAuthKey.Version);
var cmd = (KeyStore as SAMKeyStore)?.Chip?.getCommands();
if (cmd is SAMAV1ISO7816Commands samav1cmd)
Expand Down Expand Up @@ -231,7 +231,7 @@ private void SAMLockUnlock()

var key = new LibLogicalAccess.Card.DESFireKey();
key.setKeyType(LibLogicalAccess.Card.DESFireKeyType.DF_KEY_AES);
key.fromString(SAMUnlockKey.Key.GetAggregatedValue<string>(KeyValueFormat.HexStringWithSpace));
key.fromString(SAMUnlockKey.Key.GetAggregatedValueString(KeyValueStringFormat.HexStringWithSpace));
key.setKeyVersion(SAMUnlockKey.Version);

if (cmd is SAMAV1ISO7816Commands samav1cmd)
Expand Down
12 changes: 5 additions & 7 deletions KeyManager.Library.KeyStore.NXP_SAM/ISLOG/ISLOGKeyStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,28 +128,26 @@ public override async Task Open()
var versionEl = keEl.Element("KeyVersion");
if (versionEl != null && keyEl != null)
{
var keya = ke.Variant.KeyContainers[0] as KeyVersion;
var keyb = ke.Variant.KeyContainers[1] as KeyVersion;
KeyVersion? keyc = null;
if (ke.Variant.KeyContainers.Count > 2)
{
keyc = ke.Variant.KeyContainers[2] as KeyVersion;
}

if (keya != null)
if (ke.Variant.KeyContainers[0] is KeyVersion keya)
{
keya.Version = byte.Parse(versionEl.Attribute("vera")?.Value ?? "0");
keya.Key.SetAggregatedValue(keyEl.Attribute("keya")?.Value ?? string.Empty);
keya.Key.SetAggregatedValueString(keyEl.Attribute("keya")?.Value ?? string.Empty);
}
if (keyb != null)
if (ke.Variant.KeyContainers[1] is KeyVersion keyb)
{
keyb.Version = byte.Parse(versionEl.Attribute("verb")?.Value ?? "0");
keyb.Key.SetAggregatedValue(keyEl.Attribute("keyb")?.Value ?? string.Empty);
keyb.Key.SetAggregatedValueString(keyEl.Attribute("keyb")?.Value ?? string.Empty);
}
if (keyc != null)
{
keyc.Version = byte.Parse(versionEl.Attribute("verc")?.Value ?? "0");
keyc.Key.SetAggregatedValue(keyEl.Attribute("keyc")?.Value ?? string.Empty);
keyc.Key.SetAggregatedValueString(keyEl.Attribute("keyc")?.Value ?? string.Empty);
}
}
}
Expand Down
20 changes: 10 additions & 10 deletions KeyManager.Library.KeyStore.NXP_SAM/SAMKeyStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -250,14 +250,14 @@ public override Task MoveUp(KeyEntryId identifier, KeyEntryClass keClass)
throw new KeyStoreException("Unexpected number of keys on the SAM Key Entry.");
}

keyVersions[0].Key.SetAggregatedValue(Convert.ToHexString(keysdata[0].ToArray()));
keyVersions[0].Key.SetAggregatedValueString(Convert.ToHexString(keysdata[0].ToArray()));
keyVersions[0].Version = infoav2.vera;
keyVersions[1].Key.SetAggregatedValue(Convert.ToHexString(keysdata[1].ToArray()));
keyVersions[1].Key.SetAggregatedValueString(Convert.ToHexString(keysdata[1].ToArray()));
keyVersions[1].Version = infoav2.verb;

if (keyEntry.Variant.KeyContainers.Count >= 3)
{
keyVersions[2].Key.SetAggregatedValue(Convert.ToHexString(keysdata[2].ToArray()));
keyVersions[2].Key.SetAggregatedValueString(Convert.ToHexString(keysdata[2].ToArray()));
keyVersions[2].Version = infoav2.verc;
}
}
Expand Down Expand Up @@ -393,7 +393,7 @@ public override Task Update(IChangeKeyEntry change, bool ignoreIfMissing)
key.setKeyVersion(GetSAMProperties().AuthenticateKeyVersion);
if (!string.IsNullOrEmpty(Properties?.Secret))
{
key.fromString(KeyMaterial.GetFormattedValue<string>(Properties.Secret, KeyValueFormat.HexStringWithSpace));
key.fromString(KeyMaterial.GetValueString(Properties.Secret, KeyValueStringFormat.HexStringWithSpace));
}
else
{
Expand Down Expand Up @@ -428,13 +428,13 @@ public override Task Update(IChangeKeyEntry change, bool ignoreIfMissing)
var keys = new LibLogicalAccess.UCharCollectionCollection(keyVersions.Length);
foreach (var keyversion in samkey.Variant.KeyContainers)
{
if (string.IsNullOrEmpty(keyversion.Key.GetAggregatedValue<string>()))
if (string.IsNullOrEmpty(keyversion.Key.GetAggregatedValueString()))
{
keys.Add(new LibLogicalAccess.ByteVector(new byte[keyversion.Key.KeySize]));
}
else
{
keys.Add(new LibLogicalAccess.ByteVector(keyversion.Key.GetAggregatedValue<byte[]>(KeyValueFormat.Binary)));
keys.Add(new LibLogicalAccess.ByteVector(keyversion.Key.GetAggregatedValueBinary()));
}
}

Expand Down Expand Up @@ -532,7 +532,7 @@ public static void SwitchSAMToAV2(LibLogicalAccess.Reader.SAMAV1ISO7816Commands
var key = CreateDESFireKey(keyType, keyVersion, keyValue);
if (keyType != LibLogicalAccess.Card.DESFireKeyType.DF_KEY_AES)
{
var kb = KeyMaterial.GetFormattedValue<byte[]>(keyValue, KeyValueFormat.Binary);
var kb = Convert.FromHexString(keyValue);
var keys = new LibLogicalAccess.UCharCollectionCollection(3)
{
new LibLogicalAccess.ByteVector(kb),
Expand Down Expand Up @@ -568,7 +568,7 @@ public static LibLogicalAccess.Card.DESFireKey CreateDESFireKey(LibLogicalAccess
key.setKeyType(keyType);
if (!string.IsNullOrEmpty(keyValue))
{
key.fromString(KeyMaterial.GetFormattedValue<string>(keyValue, KeyValueFormat.HexStringWithSpace));
key.fromString(KeyMaterial.GetValueString(keyValue, KeyValueStringFormat.HexStringWithSpace));
}
return key;
}
Expand Down Expand Up @@ -653,7 +653,7 @@ public void UpdateCounter(SAMKeyUsageCounter counter)
key.setKeyVersion(GetSAMProperties().AuthenticateKeyVersion);
if (!string.IsNullOrEmpty(Properties?.Secret))
{
key.fromString(KeyMaterial.GetFormattedValue<string>(Properties.Secret, KeyValueFormat.HexStringWithSpace));
key.fromString(KeyMaterial.GetValueString(Properties.Secret, KeyValueStringFormat.HexStringWithSpace));
}
else
{
Expand Down Expand Up @@ -714,7 +714,7 @@ public void UpdateCounter(SAMKeyUsageCounter counter)
{
if (!string.IsNullOrEmpty(GetSAMProperties().Secret) && !_unlocked)
{
UnlockSAM(av2cmd, GetSAMProperties().AuthenticateKeyEntryIdentifier, GetSAMProperties().AuthenticateKeyVersion, KeyMaterial.GetFormattedValue<string>(Properties?.Secret, KeyValueFormat.HexStringWithSpace));
UnlockSAM(av2cmd, GetSAMProperties().AuthenticateKeyEntryIdentifier, GetSAMProperties().AuthenticateKeyVersion, KeyMaterial.GetValueString(Properties?.Secret, KeyValueStringFormat.HexStringWithSpace));
_unlocked = true;
}

Expand Down
30 changes: 30 additions & 0 deletions KeyManager.Library.Tests/KeyGenerationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
namespace Leosac.KeyManager.Library.Tests
{
[TestClass]
public class KeyGenerationTests
{
[TestMethod]
[DataRow(8)]
[DataRow(16)]
[DataRow(32)]
public void Test_Random(int keySize)
{
var key1 = KeyGeneration.Random(keySize);
Assert.AreEqual(keySize * 2, key1.Length);

var key2 = KeyGeneration.Random(keySize);
Assert.AreNotEqual(key1, key2);
}

[TestMethod]
[DataRow(8)]
[DataRow(16)]
[DataRow(32)]
public void Test_FromPassword(int keySize)
{
var key = KeyGeneration.FromPassword("test", "Security Freedom", keySize);
var rkey = "E088566240571EAD486818BE1199F53EB407411014BA1E36101C242FC34DEBAF"[..(keySize * 2)];
Assert.AreEqual(rkey, key, true);
}
}
}
73 changes: 73 additions & 0 deletions KeyManager.Library.Tests/KeyTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
namespace Leosac.KeyManager.Library.Tests
{
[TestClass]
public class KeyTests
{
[TestMethod]
public void OneMaterial_GetAggregatedValue_HexString()
{
var key = new Key(null, "00112233445566778899AABBCCDDEEFF");
var v = key.GetAggregatedValueString();
Assert.AreEqual("00112233445566778899AABBCCDDEEFF", v, true);
}

[TestMethod]
public void OneMaterial_SetAggregatedValue_HexString()
{
var key = new Key();
key.SetAggregatedValueString("00112233445566778899AABBCCDDEEFF");
Assert.AreEqual("00112233445566778899AABBCCDDEEFF", key.Materials[0].Value, true);
}

[TestMethod]
public void OneMaterial_GetAggregatedValue_Binary()
{
var key = new Key(null, "00112233445566778899AABBCCDDEEFF");
var v = key.GetAggregatedValueBinary();
Assert.IsNotNull(v);
Assert.AreEqual("00112233445566778899AABBCCDDEEFF", Convert.ToHexString(v), true);
}

[TestMethod]
public void OneMaterial_GetAggregatedValue_HexStringWithSpace()
{
var key = new Key(null, "00112233445566778899AABBCCDDEEFF");
var v = key.GetAggregatedValueString(KeyValueStringFormat.HexStringWithSpace);
Assert.AreEqual("00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF", v, true);
}

[TestMethod]
public void OneMaterial_SetAggregatedValue_HexStringWithSpace()
{
var key = new Key();
key.SetAggregatedValueString("00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF", KeyValueStringFormat.HexStringWithSpace);
Assert.AreEqual("00112233445566778899AABBCCDDEEFF", key.Materials[0].Value, true);
}

[TestMethod]
public void TwoMaterials_GetAggregatedValue_HexString()
{
var key = new Key(null, 8, new KeyMaterial("0011223344556677"), new KeyMaterial("8899AABBCCDDEEFF"));
var v = key.GetAggregatedValueString();
Assert.AreEqual("00112233445566778899AABBCCDDEEFF", v, true);
}

[TestMethod]
public void TwoMaterials_SetAggregatedValue_HexString()
{
var key = new Key(null, 8, 2);
key.SetAggregatedValueString("00112233445566778899AABBCCDDEEFF");
Assert.AreEqual("0011223344556677", key.Materials[0].Value, true);
Assert.AreEqual("8899AABBCCDDEEFF", key.Materials[1].Value, true);
}

[TestMethod]
public void TwoMaterials_GetAggregatedValue_Binary()
{
var key = new Key(null, 8, new KeyMaterial("0011223344556677"), new KeyMaterial("8899AABBCCDDEEFF"));
var v = key.GetAggregatedValueBinary();
Assert.IsNotNull(v);
Assert.AreEqual("00112233445566778899AABBCCDDEEFF", Convert.ToHexString(v), true);
}
}
}
2 changes: 1 addition & 1 deletion KeyManager.Library.UI/Domain/KeyChecksumConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public object Convert(object[] values, Type targetType, object parameter, Cultur
return Binding.DoNothing;
}

if (string.IsNullOrEmpty(value2.GetAggregatedValue<string>()))
if (string.IsNullOrEmpty(value2.GetAggregatedValueString()))
{
return Binding.DoNothing;
}
Expand Down
8 changes: 4 additions & 4 deletions KeyManager.Library.UI/KeyActionButtonsControl.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public KeyEntryClass KClass

private void BtnCopy_Click(object sender, RoutedEventArgs e)
{
Clipboard.SetText(Key?.GetAggregatedValue<string>());
Clipboard.SetText(Key?.GetAggregatedValueString());
}

private async void BtnKeyStoreLink_Click(object sender, RoutedEventArgs e)
Expand Down Expand Up @@ -90,7 +90,7 @@ private void BtnImport_Click(object sender, RoutedEventArgs e)
if (ofd.ShowDialog() == true)
{
var key = System.IO.File.ReadAllBytes(ofd.FileName);
Key.SetAggregatedValue(Convert.ToHexString(key));
Key.SetAggregatedValueString(Convert.ToHexString(key));
}
}

Expand All @@ -99,7 +99,7 @@ private void BtnExport_Click(object sender, RoutedEventArgs e)
var sfd = new SaveFileDialog();
if (sfd.ShowDialog() == true)
{
System.IO.File.WriteAllBytes(sfd.FileName, Convert.FromHexString(Key.GetAggregatedValue<string>() ?? ""));
System.IO.File.WriteAllBytes(sfd.FileName, Convert.FromHexString(Key.GetAggregatedValueString() ?? ""));
}
}

Expand All @@ -115,7 +115,7 @@ private void BtnPrint_Click(object sender, RoutedEventArgs e)
if (KClass == KeyEntryClass.Symmetric)
{
var kcv = new KCV();
control.KeyChecksum = kcv.ComputeKCV(Key.Tags, Key.GetAggregatedValue<string>() ?? "", null);
control.KeyChecksum = kcv.ComputeKCV(Key.Tags, Key.GetAggregatedValueString() ?? "", null);
}
printDialog.PrintVisual(control, "Leosac Key Manager - Key Printing");
}
Expand Down
2 changes: 1 addition & 1 deletion KeyManager.Library/CRC32Checksum.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public class CRC32Checksum : KeyChecksum

public override byte[] ComputeKCV(Key key, byte[]? iv)
{
var rawkey = key.GetAggregatedValue<byte[]>(KeyValueFormat.Binary) ?? throw new Exception("Key value is null");
var rawkey = key.GetAggregatedValueBinary() ?? throw new Exception("Key value is null");

// Use the IV as a Salt
byte[] data;
Expand Down
25 changes: 9 additions & 16 deletions KeyManager.Library/EncryptJsonConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,7 @@ public EncryptJsonConverter(string? encryptionKey)
{
encryptionKey = MasterKey;
}
using (var sha = SHA256.Create())
{
_encryptionKeyBytes = sha.ComputeHash(Encoding.UTF8.GetBytes(encryptionKey));
}
_encryptionKeyBytes = SHA256.HashData(Encoding.UTF8.GetBytes(encryptionKey));
}

public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
Expand All @@ -35,12 +32,10 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer
writer.WriteNull();
return;
}
using (var aes = Aes.Create())
{
aes.Key = _encryptionKeyBytes;
var data = aes.EncryptCbc(Encoding.UTF8.GetBytes(stringValue), new byte[16], System.Security.Cryptography.PaddingMode.PKCS7);
writer.WriteValue(Convert.ToBase64String(data));
}
using var aes = Aes.Create();
aes.Key = _encryptionKeyBytes;
var data = aes.EncryptCbc(Encoding.UTF8.GetBytes(stringValue), new byte[16], System.Security.Cryptography.PaddingMode.PKCS7);
writer.WriteValue(Convert.ToBase64String(data));
}

public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
Expand All @@ -54,12 +49,10 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer
try
{
var buffer = Convert.FromBase64String(value);
using (var aes = Aes.Create())
{
aes.Key = _encryptionKeyBytes;
var data = aes.DecryptCbc(buffer, new byte[16], System.Security.Cryptography.PaddingMode.PKCS7);
return Encoding.UTF8.GetString(data);
}
using var aes = Aes.Create();
aes.Key = _encryptionKeyBytes;
var data = aes.DecryptCbc(buffer, new byte[16], System.Security.Cryptography.PaddingMode.PKCS7);
return Encoding.UTF8.GetString(data);
}
catch
{
Expand Down
Loading

0 comments on commit 44f3c74

Please sign in to comment.