private void NotificationHandler(string notificationInJson) { Notification notification = JsonSerializer.Deserialize <Notification>(notificationInJson); aesEncryption.SetKey(chatKey); string decryptedMessage = coding.Decode(aesEncryption.Decrypt(notification.EncryptedMessage)); Console.WriteLine($"{notification.Sender}: {decryptedMessage}"); }
public void GivenEncryptedContent_WhenDecrypt_WithCorrectKey_ThenContentIsDecrypted() { var content = Encoding.UTF8.GetBytes("This is some text"); const string password = "******"; var encrypted = _encryptionAlgorithm.Encrypt(content, password); var decrypted = _encryptionAlgorithm.Decrypt(encrypted, password); decrypted.Should().Equal(content); }
/// <summary> /// Read page bytes from disk /// </summary> public virtual byte[] ReadPage(uint pageID) { var buffer = new byte[BasePage.PAGE_SIZE]; var position = BasePage.GetSizeOfPages(pageID); // position cursor if (_stream.Position != position) { _stream.Seek(position, SeekOrigin.Begin); } // read bytes from data file _stream.Read(buffer, 0, BasePage.PAGE_SIZE); // when reading the header, check the password if (pageID == 0 && _crypto != null) { // I know, header page will be double read (it's the price for isolated concerns) var header = (HeaderPage)BasePage.ReadPage(buffer); if (BinaryExtensions.BinaryCompareTo(_password, header.Password) != 0) { throw LiteException.DatabaseWrongPassword(); } } else if (_crypto != null) { buffer = _crypto.Decrypt(buffer); } return(buffer); }
public ObsWebsocketSettingDataModel Load() { if (loaded) { return(cache); } var data = FileIOUtility.Read <ObsWebsocketSettingDataModel>("ObsWebsocket"); try { data.ServerAddress = AesEncryption.Decrypt(data.ServerAddress); data.Password = AesEncryption.Decrypt(data.Password); } catch (Exception e) { Debug.LogError("Encryption info is updated. please re-enter address and password."); data.ServerAddress = ""; data.Password = ""; } loaded = true; cache = data; return(data); }
private string ParseMessageToJson(byte[] rawMessage, byte[] aesKey) { aesEncryption.SetKey(aesKey); byte[] decryptedConnectionMessage = aesEncryption.Decrypt(rawMessage); return(coding.Decode(decryptedConnectionMessage)); }
public byte[] DecryptData(EncryptedPacket encryptedPacket, RSAWithRSAParameterKey rsaParams) { // Decrypt AES Key with RSA var decryptedSessionKey = rsaParams.DecryptData(encryptedPacket.EncryptedSessionKey); // Decrypt our data with AES using the decryptedSessionKey return(_aes.Decrypt(encryptedPacket.EncryptedData, decryptedSessionKey, encryptedPacket.IV)); }
public void TestDecryption() { var aes = new AesEncryption(_correctVector, _correctKey); const string plaintext = "Dies ist ein Test"; var encrypted = aes.Encrypt((plaintext)); var decrypted = aes.Decrypt(encrypted); Assert.AreEqual(plaintext, decrypted); }
public static string DecryptData(EncryptedPacket encryptedPacket, RSAWithRSAParameterKey rsaParams) { var aes = new AesEncryption(); // Decrypt AES key with RSA and then decrypt data with AES. var decryptedSessionKey = rsaParams.DecryptData(encryptedPacket.EncryptedSessionKey); var decryptedData = aes.Decrypt(encryptedPacket.EncryptedData, decryptedSessionKey, encryptedPacket.Iv); return(Encoding.UTF8.GetString(decryptedData)); }
public void EncryptionIsSymmetrical() { var passphrase = "PurpleMonkeyDishwasher"; var text = "Put It In H!"; var encryptor = new AesEncryption(passphrase); Assert.AreEqual(text, encryptor.Decrypt(encryptor.Encrypt(text))); }
public void AesEncryptionTest() { var aes = new AesEncryption(32, 16); var data = Encoding.UTF8.GetBytes(testMessage); var encryptedData = aes.Encrypt(data); var decryptedData = aes.Decrypt(encryptedData); Assert.Equal(data, decryptedData); }
public byte[] DecryptData(EncryptedPacket encryptedPacket, RsaWithRsaParameterKey rsaParams) { // Decrypt AES Key with RSA. var decryptedSessionKey = rsaParams.DecryptData(encryptedPacket.EncryptedSessionKey); // Decrypt our data with AES using the decrypted session key. var decryptedData = _aes.Decrypt(encryptedPacket.EncryptedData, decryptedSessionKey, encryptedPacket.Iv); return(decryptedData); }
public void decrypt_return_original_value_for_bad_data() { // given string encryptedValue = "f"; var encryption = new AesEncryption("password"); // when string actualValue = encryption.Decrypt(encryptedValue); // then Assert.That(actualValue, Is.EqualTo("f")); }
public void decrypt_should_return_value_when_password_is_empty() { // given string plainText = "touch my what?!"; var encryption = new AesEncryption(""); // when string actualValue = encryption.Decrypt(plainText); // then Assert.That(actualValue, Is.EqualTo(plainText)); }
public static string Decrypt(this string input) { try { string secretKey = Environment.GetEnvironmentVariable("ASPNETCORE_SECRETKEY") ?? "AtlasX"; return(AesEncryption.Decrypt(input, secretKey)); } catch (Exception e) { Console.WriteLine(e); return(input); } }
public void decrypt_should_decrypt_base64_string() { // given string expectedValue = "trap the Zapdos"; string encryptedValue = "fHFAc4zPBd3+pAE6Rf69IQ=="; var encryption = new AesEncryption("password"); // when string actualValue = encryption.Decrypt(encryptedValue); // then Assert.That(actualValue, Is.EqualTo(expectedValue)); }
public static string LoadJsonData(string direction) { var dirToRead = $"{Application.persistentDataPath}/{direction}.txt"; using (StreamReader stream = new StreamReader(dirToRead)) { var stringRecovered = stream.ReadToEnd(); stream.Close(); var jsonToRecover = JsonUtility.FromJson <AesEncryption.AESEncryptedText>(stringRecovered); return(AesEncryption.Decrypt(jsonToRecover, "galletita")); } }
/// <summary> /// function decrypts the given file /// </summary> /// <param name="readLocation"> file to read</param> /// <param name="saveLocation">file to write to</param> /// <param name="keys">the holder of decryption key and seed</param> public void Decrypt(string readLocation, string saveLocation, KeyHolder keys) { AesEncryption aes = new AesEncryption(); aes.Key = keys.Key; aes.Seed = keys.Seed; using (FileStream inputStream = File.Open(readLocation, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (FileStream outputStream = File.Open(saveLocation, FileMode.Create, FileAccess.Write, FileShare.None)) { aes.Decrypt(inputStream, outputStream); } } }
public static SubsonicSettings ReadSettingsFromFile(string settingsFilename) { var settings = new SubsonicSettings(); try { if (!File.Exists(settingsFilename)) { return(Subsonic.GetCurrentSettings()); } using (var reader = new StreamReader(settingsFilename)) { var protocolText = AesEncryption.Decrypt(reader.ReadLine(), Passphrase); settings.Protocol = protocolText.Equals("HTTP") ? SubsonicSettings.ConnectionProtocol.Http : SubsonicSettings.ConnectionProtocol.Https; settings.Host = AesEncryption.Decrypt(reader.ReadLine(), Passphrase); settings.Port = AesEncryption.Decrypt(reader.ReadLine(), Passphrase); settings.BasePath = AesEncryption.Decrypt(reader.ReadLine(), Passphrase); settings.Username = AesEncryption.Decrypt(reader.ReadLine(), Passphrase); settings.Password = AesEncryption.Decrypt(reader.ReadLine(), Passphrase); settings.Transcode = AesEncryption.Decrypt(reader.ReadLine(), Passphrase) == "Y"; settings.Auth = AesEncryption.Decrypt(reader.ReadLine(), Passphrase) == "HexPass" ? SubsonicSettings.AuthMethod.HexPass : SubsonicSettings.AuthMethod.Token; settings.BitRate = AesEncryption.Decrypt(reader.ReadLine(), Passphrase); if (string.IsNullOrEmpty(settings.BitRate)) { settings.BitRate = "Unlimited"; } settings.UseIndexCache = AesEncryption.Decrypt(reader.ReadLine(), Passphrase) == "Y"; return(settings); } } catch (Exception ex) { const string caption = "Error while trying to load settings"; MessageBox.Show($@"An error occurred while trying to load the settings file! Reverting to defaults... Exception: {ex}", caption, MessageBoxButtons.OK, MessageBoxIcon.Error); return(Subsonic.GetCurrentSettings()); } }
public byte[] DecryptData(EncryptedPacket encryptedPacket, RSAWithRSAParameterKey rsaParams) { // Decrypt AES Key with RSA var decryptedSessionKey = rsaParams.DecryptData(encryptedPacket.EncryptedSessionKey); // Integrity Check var hmacToCheck = HMac.ComputeHMACSha256(encryptedPacket.EncryptedData, decryptedSessionKey); if (!Compare(encryptedPacket.HMAC, hmacToCheck)) { throw new CryptographicException("HMAC for decryption does not match encrypted package HMAC code received. This means the message has been tampered with."); } // Decrypt our data with AES using the decryptedSessionKey return(_aes.Decrypt(encryptedPacket.EncryptedData, decryptedSessionKey, encryptedPacket.IV)); }
/// <summary> /// Function decrypts the given string /// <para> Returns a decrypted string</para> /// </summary> /// <param name="encryptedString"> the obj to decrypt</param> /// <param name="keys"> Obj to store key and seed</param> /// <returns>returns a decrypted string or the name of the decrypted file name</returns> public string Decrypt(string encryptedString, KeyHolder keys) { string decryptedObj = ""; if (!CheckFile.checkHasExtention(encryptedString)) { AesEncryption aes = new AesEncryption(); aes.Key = keys.Key; aes.Seed = keys.Seed; decryptedObj = aes.Decrypt(encryptedString); } else { Decrypt(encryptedString, encryptedString, keys); } return(decryptedObj); }
private static void TestAES() { var aes = new AesEncryption(); var key = aes.GenerateRandomNumber(32); var iv = aes.GenerateRandomNumber(16); const string originalText = "Text to encrypt"; var encrypted = aes.Encrypt(Encoding.UTF8.GetBytes(originalText), key, iv); var decrypted = aes.Decrypt(encrypted, key, iv); var decryptedMessage = Encoding.UTF8.GetString(decrypted); Console.WriteLine($"Original Text: {originalText}"); Console.WriteLine($"Encrypted value: {Convert.ToBase64String(encrypted)}"); Console.WriteLine($"Decrypted Value: {Convert.ToBase64String(decrypted)}"); Console.WriteLine($"Decrypted Text: {decryptedMessage}"); }
public static string DecryptData(EncryptedPacket encryptedPacket, RSAWithRSAParameterKey rsaParams) { var aes = new AesEncryption(); // Decrypt AES key with RSA and then decrypt data with AES. var decryptedSessionKey = rsaParams.DecryptData(encryptedPacket.EncryptedSessionKey); using (var hmac = new HMACSHA256(decryptedSessionKey)) { var hmacToCheck = hmac.ComputeHash(encryptedPacket.EncryptedData); if (!CompareArrays.Compare(encryptedPacket.Hmac, hmacToCheck)) { throw new CryptographicException("HMAC for decryption does not match encrypted packet."); } } var decryptedData = aes.Decrypt(encryptedPacket.EncryptedData, decryptedSessionKey, encryptedPacket.Iv); return(Encoding.UTF8.GetString(decryptedData)); }
private Statistics GetStatistics() { AesEncryption aes = new AesEncryption(); byte[] key = aes.GenerateRandomNumber(32); byte[] iv = aes.GenerateRandomNumber(16); // Gets the statistics encrypted byte[] encryptedData = StatisticsRepository.GetStatistics(key, iv, _carwashId); // Decrypts the data byte[] decryptedData = aes.Decrypt(encryptedData, key, iv); // Makes the byte array into a string string decryptedJson = Encoding.UTF8.GetString(decryptedData); // Deserializes the json string Statistics statistics = JsonHelper.DeserializeJson <Statistics>(decryptedJson); return(statistics); }
/// <summary> /// Gets decrypted data from a wire message. /// </summary> /// <param name="message">Wire message</param> /// <param name="serializer">Serializer used to deserialized the signed content</param> /// <param name="sharedSecret">Shared secret (null, if the wire message is not encrypted)</param> /// <param name="sendersPublicKeyBlob">Public key of the sender used for RSA signature verification</param> /// <param name="sendersPublicKeySize">Sender's public key size</param> /// <returns>Decrypted raw data</returns> public byte[] GetDecryptedMessageData( WireMessage message, ISerializerAdapter serializer, byte[] sharedSecret = null, byte[] sendersPublicKeyBlob = null, int sendersPublicKeySize = 0) { if (message.Iv.Length > 0 && sharedSecret != null) { var decryptedRawData = AesEncryption.Decrypt( encryptedData: message.Data, sharedSecret: sharedSecret, iv: message.Iv); var signedMessageData = serializer.Deserialize <SignedMessageData>(decryptedRawData); if (sendersPublicKeyBlob != null && signedMessageData.Signature != null) { if (RsaSignature.VerifySignature( keySize: sendersPublicKeySize, sendersPublicKeyBlob: sendersPublicKeyBlob, rawData: signedMessageData.MessageRawData, signature: signedMessageData.Signature)) { return(signedMessageData.MessageRawData); } else { throw new SecurityException("Verification of message signature failed."); } } else { return(decryptedRawData); } } else { return(message.Data); } }
private void TestEncryptDecrypt(uint keySize) { using (var cr = new CryptoRandom()) { for (int i = 0; i < 5; i++) { byte[] key = cr.NextBytes(keySize); byte[] iv = cr.NextBytes(16); byte[] plainText = cr.NextBytes((uint)cr.NextInt(1, 2455)); byte[] encrypted = AesEncryption.Encrypt(plainText, key, iv); byte[] decrypted = AesEncryption.Decrypt(encrypted, key, iv); string plainString = Convert.ToBase64String(plainText); string decryptedString = Convert.ToBase64String(decrypted); Assert.Equal(plainString, decryptedString); } } }
public byte[] Decrypt(EncryptedPacket packet, RsaWithRsaParameterKey rsaParams) { var decriptedSessionKey = rsaParams.Decrypt(packet.EncryptedSessionKey); using (var hmac = new HMACSHA256(decriptedSessionKey)) { var hmacToCheck = hmac.ComputeHash(packet.EncryptedData); if (!Compare(packet.Hmac, hmacToCheck)) { throw new CryptographicException("HMAC for decription doesn't match"); } if (!_digitalSignature.VerifySignature(packet.Hmac, packet.Signature)) { throw new CryptographicException("Digital signature cannot be verified."); } } return(_aes.Decrypt(packet.EncryptedData, decriptedSessionKey, packet.Iv)); }
public void TestEncryption() { AesEncryption aesEncryption = new AesEncryption(); string dataToEncrypt = ALL_CHARS; string encrypted = aesEncryption.Encrypt(dataToEncrypt, "SomeT3st P@55w0rd"); if (String.IsNullOrEmpty(encrypted)) { encrypted = null; } Assert.IsNotNull(encrypted, "Encryption returned null"); string decrypted = aesEncryption.Decrypt(encrypted, "SomeT3st P@55w0rd"); if (String.IsNullOrEmpty(decrypted)) { decrypted = null; } Assert.IsNotNull(decrypted, "Decryption returned null"); Assert.AreEqual(dataToEncrypt, decrypted, "Initial encryption string and decrypted value do not match"); }
internal static string Unarchive(string text) { var data = Convert.FromBase64String(text); byte[] unarchivedData = null; var dataWithEncryptionInfo = DataWithArchivingInfo.FromProcessedData(data); var mode = dataWithEncryptionInfo.Mode; switch (mode) { case StorageModes.CompressAndEncrypt: unarchivedData = DeflateCompression.Decompress(AesEncryption.Decrypt(dataWithEncryptionInfo.Data)); break; case StorageModes.Compress: unarchivedData = DeflateCompression.Decompress(dataWithEncryptionInfo.Data); break; case StorageModes.Store: unarchivedData = dataWithEncryptionInfo.Data; break; } return(Encoding.UTF8.GetString(unarchivedData)); }
public override byte[] Decode(ref byte[] data, ref uint offset, ref uint length, ref PacketHeader packetHeader) { byte[] decrypted = aes.Decrypt(data, ref offset, ref length); offset = 0; return(decrypted); }
/// <summary> /// Read all database pages from v7 structure into a flexible BsonDocument - only read what really needs /// </summary> private BsonDocument ReadPage(uint pageID) { if (pageID * V7_PAGE_SIZE > _stream.Length) { return(null); } _stream.Position = pageID * V7_PAGE_SIZE; // v7 uses 4k page size _stream.Read(_buffer, 0, V7_PAGE_SIZE); // decrypt encrypted page (except header page - header are plain data) if (_aes != null && pageID > 0) { _buffer = _aes.Decrypt(_buffer); } var reader = new ByteReader(_buffer); // reading page header var page = new BsonDocument { ["pageID"] = (int)reader.ReadUInt32(), ["pageType"] = (int)reader.ReadByte(), ["prevPageID"] = (int)reader.ReadUInt32(), ["nextPageID"] = (int)reader.ReadUInt32(), ["itemCount"] = (int)reader.ReadUInt16() }; // skip freeByte + reserved reader.ReadBytes(2 + 8); #region Header (1) // read header if (page["pageType"] == 1) { var info = reader.ReadString(27); var ver = reader.ReadByte(); if (string.CompareOrdinal(info, HeaderPage.HEADER_INFO) != 0 || ver != 7) { throw LiteException.InvalidDatabase(); } // skip ChangeID + FreeEmptyPageID + LastPageID reader.ReadBytes(2 + 4 + 4); page["userVersion"] = (int)reader.ReadUInt16(); page["password"] = reader.ReadBytes(20); page["salt"] = reader.ReadBytes(16); page["collections"] = new BsonDocument(); var cols = reader.ReadByte(); for (var i = 0; i < cols; i++) { var name = reader.ReadString(); var colPageID = reader.ReadUInt32(); page["collections"][name] = (int)colPageID; } } #endregion #region Collection (2) // collection page else if (page["pageType"] == 2) { page["collectionName"] = reader.ReadString(); page["indexes"] = new BsonArray(); reader.ReadBytes(12); for (var i = 0; i < 16; i++) { var index = new BsonDocument(); var field = reader.ReadString(); var eq = field.IndexOf('='); if (eq > 0) { index["name"] = field.Substring(0, eq); index["expression"] = field.Substring(eq + 1); } else { index["name"] = field; index["expression"] = "$." + field; } index["unique"] = reader.ReadBoolean(); index["headPageID"] = (int)reader.ReadUInt32(); // skip HeadNode (index) + TailNode + FreeIndexPageID reader.ReadBytes(2 + 6 + 4); if (field.Length > 0) { page["indexes"].AsArray.Add(index); } } } #endregion #region Index (3) else if (page["pageType"] == 3) { page["nodes"] = new BsonArray(); for (var i = 0; i < page["itemCount"].AsInt32; i++) { var node = new BsonDocument { ["index"] = (int)reader.ReadUInt16() }; var levels = reader.ReadByte(); // skip Slot + PrevNode + NextNode reader.ReadBytes(1 + 6 + 6); var length = reader.ReadUInt16(); // skip DataType + KeyValue reader.ReadBytes(1 + length); node["dataBlock"] = new BsonDocument { ["pageID"] = (int)reader.ReadUInt32(), ["index"] = (int)reader.ReadUInt16() }; // reading Prev[0] node["prev"] = new BsonDocument { ["pageID"] = (int)reader.ReadUInt32(), ["index"] = (int)reader.ReadUInt16() }; // reading Next[0] node["next"] = new BsonDocument { ["pageID"] = (int)reader.ReadUInt32(), ["index"] = (int)reader.ReadUInt16() }; // skip Prev/Next[1..N] reader.ReadBytes((levels - 1) * (6 + 6)); page["nodes"].AsArray.Add(node); } } #endregion #region Data (4) else if (page["pageType"] == 4) { page["blocks"] = new BsonArray(); for (var i = 0; i < page["itemCount"].AsInt32; i++) { var block = new BsonDocument { ["index"] = (int)reader.ReadUInt16(), ["extendPageID"] = (int)reader.ReadUInt32() }; var length = reader.ReadUInt16(); block["data"] = reader.ReadBytes(length); page["blocks"].AsArray.Add(block); } } #endregion #region Extend (5) else if (page["pageType"] == 5) { page["data"] = reader.ReadBytes(page["itemCount"].AsInt32); } #endregion return(page); }
/* Opens a workbook handle based on a request */ public SpreadsheetGear.IWorkbook GetWorkBook(EIA.Repository.CModelRequest Request) { /* Shared */ Guid mGuid = Guid.Parse(Request.Model.Guid); Byte[] WbData, WbDataCopy; /* Sanitize the cache before we decrypt */ if (lDecryptedCache.ContainsKey(mGuid)) { WbData = lDecryptedCache[mGuid]; } else { /* Create a new instance of encryptor */ AesEncryption Decryptor = new AesEncryption(Key, Vector); /* Calculate Path */ String ModelPath = Environment.GetFolderPath( Environment.SpecialFolder.CommonDocuments) + "\\EIA\\Models\\" + Request.Model.Name + " - " + Request.Model.Country + " - " + Request.Model.Type + ".xlsm"; /* Read in model */ Byte[] EncryptedWbData = File.ReadAllBytes(ModelPath); WbData = Decryptor.StrToByteArray(Decryptor.Decrypt(EncryptedWbData)); /* Store */ lDecryptedCache.Add(mGuid, WbData); } /* Create a copy of the data */ WbDataCopy = new Byte[WbData.Length]; WbData.CopyTo(WbDataCopy, 0); /* Create the memory stream */ MemoryStream mStream = new MemoryStream(WbDataCopy); /* Open Workbook */ return SpreadsheetGear.Factory.GetWorkbookSet().Workbooks.OpenFromStream(mStream); }