sharee.bike-App/LockIt.BusinessLogic/Services/BluetoothLock/Crypto/AuthCryptoHelper.cs
2024-04-09 12:53:23 +02:00

82 lines
2.3 KiB
C#

using Serilog;
using ShareeBike.Model.Device;
namespace ShareeBike.Services.BluetoothLock.Crypto
{
public class AuthCryptoHelper
{
private ICipher Cipher { get; }
/// <summary> Encrypted seed (random number) created inside ILOCKIT and passd to app.</summary>
private byte[] SeedLockEncrypted { get; }
/// <summary> Contstructs a auth crypto helper object.</summary>
/// <param name="seedLockEncrypted">Encrypted seed to deocode using <see cref="KeyCopri"/>.</param>
/// <param name="keyCopri">Key used to to decrypt <see cref="SeedLockEncrypted"/>.</param>
public AuthCryptoHelper(
byte[] seedLockEncrypted,
byte[] keyCopri,
ICipher cipher)
{
KeyCopri = keyCopri;
SeedLockEncrypted = seedLockEncrypted;
Cipher = cipher ?? new Cipher();
}
/// <summary> Public for testing purposes only.</summary>
public byte[] GetSeedLock()
{
byte[] seedLockDecrypted;
var seedLockEncrypted = SeedLockEncrypted;
var keyCopri = KeyCopri;
try
{
seedLockDecrypted = Cipher.Decrypt(
keyCopri,
seedLockEncrypted);
}
catch (System.Exception exception)
{
Log.ForContext<AuthCryptoHelper>().Error("Decrypting seed from lock failed. {Exception}", exception);
throw;
}
Log.ForContext<AuthCryptoHelper>().Verbose($"Lock random number decrypted from {string.Join(",", seedLockEncrypted)} to {string.Join(",", seedLockDecrypted)} using {string.Join(", ", keyCopri)}.");
return seedLockDecrypted;
}
public byte[] GetAccessKeyEncrypted()
{
var accessKey = GetSeedLock();
if (accessKey == null || accessKey.Length <= 0)
{
Log.ForContext<AuthCryptoHelper>().Error("Creating access key failed, Key must not be null or empty.");
throw new System.Exception();
}
accessKey[accessKey.Length - 1] += 1;
var keyCopri = KeyCopri;
byte[] acccessKeyEncrypted;
try
{
acccessKeyEncrypted = Cipher.Encrypt(
keyCopri,
accessKey);
}
catch (System.Exception exception)
{
Log.ForContext<AuthCryptoHelper>().Error("Encrypting access key failed. {Exception}", exception);
throw;
}
Log.ForContext<AuthCryptoHelper>().Verbose($"Access key encrypted from {string.Join(",", accessKey)} to {string.Join(",", acccessKeyEncrypted)} using {string.Join(", ", keyCopri)}.");
return acccessKeyEncrypted;
}
public byte[] KeyCopri { get; }
}
}