using System; using System.IO; using System.Security.Cryptography; using TINK.Model.Device; namespace TINK.Services.BluetoothLock.Crypto { public class Cipher : ICipher { /// Decrypt data. /// /// Further info see: /// https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.aes?view=netcore-3.1 for further info // https://docs.microsoft.com/en-us/dotnet/standard/security/cryptographic-services // https://stackoverflow.com/questions/24903575/how-to-return-byte-when-decrypt-using-cryptostream-descryptoserviceprovider/24903689 /// /// Key to decrypt data with. /// Encrpyted data to decrypt. /// Decrypted data. public byte[] Decrypt(byte[] key, byte[] encrypted) { // Check arguments. if (encrypted == null || encrypted.Length <= 0) throw new ArgumentNullException(nameof(encrypted)); if (key == null || key.Length <= 0) throw new ArgumentNullException(nameof(key)); using (Aes aesAlg = Aes.Create()) { aesAlg.KeySize = 192; aesAlg.Mode = CipherMode.ECB; aesAlg.Padding = PaddingMode.None; aesAlg.Key = key; // Create a decryptor to perform the stream transform. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption. using (var msDecrypt = new MemoryStream()) { using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write)) { csDecrypt.Write(encrypted, 0, encrypted.Length); csDecrypt.FlushFinalBlock(); return msDecrypt.ToArray(); } } } } public byte[] Encrypt(byte[] key, byte[] clear) { // Check arguments. if (clear == null || clear.Length <= 0) throw new ArgumentNullException("plainText"); if (key == null || key.Length <= 0) throw new ArgumentNullException("Key"); // Create an AesCryptoServiceProvider object // with the specified key and IV. using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.KeySize = 192; aesAlg.Mode = CipherMode.ECB; aesAlg.Padding = PaddingMode.None; aesAlg.Key = key; // Create an encryptor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. using (var msEncrypt = new MemoryStream()) { using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { csEncrypt.Write(clear, 0, clear.Length); csEncrypt.FlushFinalBlock(); return msEncrypt.ToArray(); } } } } } }