/// <inheritdoc/> protected override void UpdateSettingsFrom1To2(XElement root) { base.UpdateSettingsFrom1To2(root); // Handle protected password XElement oldPasswortElement = root.Element("cloud_storage")?.Element("cloud_password"); XElement cloudStorageAccount = root.Element("cloud_storage_account"); if ((oldPasswortElement != null) && (cloudStorageAccount != null)) { // Deobfuscate old password EncryptorDecryptor decryptor = new EncryptorDecryptor("snps"); byte[] binaryCipher = CryptoUtils.Base64StringToBytes(oldPasswortElement.Value); byte[] unprotectedBinaryPassword = decryptor.Decrypt(binaryCipher, snpsk); // Protect with new data protection service and add to XML char[] unprotectedChars = Encoding.UTF8.GetChars(unprotectedBinaryPassword); byte[] unprotectedUnicodePassword = Encoding.Unicode.GetBytes(unprotectedChars); string protectedPassword = _dataProtectionService.Protect(unprotectedUnicodePassword); cloudStorageAccount.Add(new XElement("protected_password", protectedPassword)); CryptoUtils.CleanArray(unprotectedBinaryPassword); CryptoUtils.CleanArray(unprotectedChars); CryptoUtils.CleanArray(unprotectedUnicodePassword); } }
void PasswordEncryptorDecryptor() { Console.WriteLine("Please enter a passphrase to use:"); string password = Console.ReadLine(); Console.WriteLine("Please enter your string to encrypt:"); string plaintext = Console.ReadLine(); Console.WriteLine(""); Console.WriteLine("Your encrypted string is:"); string encryptedstring = EncryptorDecryptor.Encrypt(plaintext, password); Console.WriteLine(encryptedstring); Console.WriteLine(""); Console.WriteLine("Your decrypted string is:"); string decryptedstring = EncryptorDecryptor.Decrypt(encryptedstring, password); Console.WriteLine(decryptedstring); Console.WriteLine(""); Console.WriteLine("Press any key to exit..."); Console.ReadLine(); }
public void OkEncodeDecodeReplace() { // arrange var encryptorDecryptor = new EncryptorDecryptor(); var inputFilePath = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName, "CustomXdtTransforms.Tests", "TestAppConfigs", "TestApp.config"); var transformFilePath = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName, "CustomXdtTransforms.Tests", "TestAppConfigs", "TestApp.Debug.config"); string result; // act using (var input = new XmlTransformableDocument()) using (var transformer = new XmlTransformation(transformFilePath)) { input.Load(inputFilePath); transformer.Apply(input); using (var stringWriter = new StringWriter()) using (var xmlWriter = XmlWriter.Create(stringWriter)) { input.WriteContentTo(xmlWriter); xmlWriter.Flush(); result = stringWriter.ToString(); var xmlDoc = XDocument.Parse(result); var root = xmlDoc.Root; // assert var ecnrypteNode2 = root.Descendants("setting").Single(x => x.Attribute("name").Value == "ExpectedEncrypted2"); var ecnrypteNode2Attrubute = ecnrypteNode2.Attribute("serializeAs").Value; encryptorDecryptor.Decrypt(ecnrypteNode2Attrubute).Should().Be("String"); var encryptedNode2Value = ecnrypteNode2.Value; encryptorDecryptor.Decrypt(encryptedNode2Value).Should().Be("SomeNewEncryptedValue2"); } } }
public AuthenticationAuthorizationController(ICustomTokenManager customTokenManager, EncryptorDecryptor encryptorDecryptor, IAsyncContactRepository <SuperAdmin> superAdmin, IAsyncContactRepository <Tenant> tenantRepository, IAsyncContactRepository <User> userRepository) { _customTokenManager = customTokenManager; _encryptorDecryptor = encryptorDecryptor; _superAdmin = superAdmin; _tenantRepository = tenantRepository; _userRepository = userRepository; }
public void TestEncryptionOfString() { string testSample = "this text is decrypted ok"; string result = EncryptorDecryptor.Encrypt(testSample); result = EncryptorDecryptor.Decrypt(result); Assert.True(result.Equals(testSample), "encryption/decryption failed"); }
internal static byte[] EncryptRepository(NoteRepositoryModel repository, string transferCode, ICryptoRandomService randomService, string encryptionAlgorithm) { byte[] binaryRepository = XmlUtils.SerializeToXmlBytes(repository); EncryptorDecryptor encryptor = new EncryptorDecryptor("SilentNotes"); // The key derivation cost is set to low, because we can be sure that the transferCode // is a very strong password, and to not overload slow mobile devices. return(encryptor.Encrypt(binaryRepository, transferCode, Crypto.KeyDerivation.KeyDerivationCostType.Low, randomService, encryptionAlgorithm)); }
public void EnsureLongTimeDecryptionOfAesGcm() { // Ensure that a once stored cipher can always be decrypted even after changes in the liberary string base64Cipher = "dW5pdHRlc3QkYWVzX2djbSQ0NG04QXBFU1ptcXhnYll2OE5wcWl3PT0kcGJrZGYyJGgwSDdxSGZnVFlXNzBKS3lEb0JLeFE9PSQxMDAwJJsMDjdYEYXYmcqTOFRbge6iVfWo/iny4nrIOMVuoqYak6xB/MAe53G5H3AyxiTi8OENJbi9tzZStpe3p3nlDB7l+J8="; byte[] cipher = CryptoUtils.Base64StringToBytes(base64Cipher); EncryptorDecryptor decryptor = new EncryptorDecryptor("unittest"); string decryptedMessage = CryptoUtils.BytesToString(decryptor.Decrypt(cipher, "brownie")); Assert.AreEqual("The brown fox jumps over the lazy 🐢🖐🏿 doc.", decryptedMessage); }
private static byte[] CreateEncryptedRepository(string password, NoteRepositoryModel repository = null) { if (repository == null) { repository = new NoteRepositoryModel(); } byte[] serializedRepository = XmlUtils.SerializeToXmlBytes(repository); EncryptorDecryptor encryptor = new EncryptorDecryptor("SilentNotes"); return(encryptor.Encrypt(serializedRepository, password, SilentNotes.Crypto.KeyDerivation.KeyDerivationCostType.Low, CommonMocksAndStubs.CryptoRandomService(), BouncyCastleTwofishGcm.CryptoAlgorithmName)); }
public void ReplaceAndEncryptTest() { // arrange var encryptorDecryptor = new EncryptorDecryptor(); // assert Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var appSettings = (AppSettingsSection)config.GetSection("appSettings"); encryptorDecryptor.Decrypt(appSettings.Settings["location"].Value).Should().Be("Canandaigua"); }
public void EnsureLongTimeDecryptionOfTwofishGcm() { // Ensure that a once stored cipher can always be decrypted even after changes in the liberary string base64Cipher = "dW5pdHRlc3QkdHdvZmlzaF9nY20kZHhMWFh4K0UrZ2MzWHdWc01rWUFxQT09JHBia2RmMiRma1BCWTdDWXp1OG5YUlJtYk9DUlp3PT0kMTAwMCRRc0ETSqDekQuBgKJ5x4Mvy02OHsivm0uJ9KchKdpGk+pmbF4Kq/EDbx9Uw54uEZUQLnK70dNKSEVtb1GyUOX1mitr"; byte[] cipher = CryptoUtils.Base64StringToBytes(base64Cipher); EncryptorDecryptor decryptor = new EncryptorDecryptor("unittest"); string decryptedMessage = CryptoUtils.BytesToString(decryptor.Decrypt(cipher, "brownie")); Assert.AreEqual("The brown fox jumps over the lazy 🐢🖐🏿 doc.", decryptedMessage); }
public void CryptoTestEncryptor() { EncryptorDecryptor encryptor = new EncryptorDecryptor("sugus"); ICryptoRandomService randomGenerator = CommonMocksAndStubs.CryptoRandomService(); string message = "Der schnelle Fuchs stolpert über den faulen Hund."; byte[] binaryMessage = CryptoUtils.StringToBytes(message); string password = "******"; byte[] cipher = encryptor.Encrypt(binaryMessage, password, KeyDerivationCostType.Low, randomGenerator, BouncyCastleTwofishGcm.CryptoAlgorithmName); byte[] decryptedMessage = encryptor.Decrypt(cipher, password); Assert.AreEqual(binaryMessage, decryptedMessage); }
/// <summary> /// Adopts the encryption mode to the settings, if the settings are set accordingly and the /// mode differs from the stored one. /// </summary> /// <param name="settings">Settings to update.</param> /// <param name="encryptor">The eccryptor.</param> /// <param name="binaryCloudRepository">The repository containing the encryption mode.</param> /// <returns>Returns true if the encryption mode was adopted, otherwise false.</returns> private static bool AdoptEncryptionMode(SettingsModel settings, EncryptorDecryptor encryptor, byte[] binaryCloudRepository) { if (settings.AdoptCloudEncryptionAlgorithm) { string cloudEncryptionAlgorithm = encryptor.ExtractAlgorithmName(binaryCloudRepository); if (!string.Equals(settings.SelectedEncryptionAlgorithm, cloudEncryptionAlgorithm, StringComparison.OrdinalIgnoreCase)) { settings.SelectedEncryptionAlgorithm = cloudEncryptionAlgorithm; return(true); } } return(false); }
public void OkEncodeDecodeAppSettings() { // arrange var encryptorDecryptor = new EncryptorDecryptor(); // assert Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var appSettings = (AppSettingsSection)config.GetSection("appSettings"); encryptorDecryptor.Decrypt(appSettings.Settings["KeyToEncrypt1"].Value).Should().Be("PlainValue1"); encryptorDecryptor.Decrypt(appSettings.Settings["KeyToEncrypt2"].Value).Should().Be("PlainValue2"); appSettings.Settings["UnTouchedKey1"].Value.Should().Be("UnTouchedValue1"); appSettings.Settings["UnTouchedKey2"].Value.Should().Be("UnTouchedValue2"); }
public void OkEncodeDecodeInnerText() { // arrange var encryptorDecryptor = new EncryptorDecryptor(); // assert encryptorDecryptor.Decrypt(ConfigurationManager.ConnectionStrings["KeyToEncrypt1"].ConnectionString) .Should().Be("Data Source=SomeServer;Initial Catalog=EncryptDB1;Integrated Security=True"); encryptorDecryptor.Decrypt(ConfigurationManager.ConnectionStrings["KeyToEncrypt2"].ConnectionString) .Should().Be("Data Source=SomeServer;Initial Catalog=EncryptDB2;Integrated Security=True"); ConfigurationManager.ConnectionStrings["UnTouchedKey1"].ConnectionString .Should().Be("Data Source=SomeServer;Initial Catalog=SomeDB1;Integrated Security=True"); ConfigurationManager.ConnectionStrings["UnTouchedKey2"].ConnectionString .Should().Be("Data Source=SomeServer;Initial Catalog=SomeDB2;Integrated Security=True"); }
private bool TryDecryptRepositoryWithTransfercode(EncryptorDecryptor encryptor, byte[] binaryCloudRepository, string transferCode, out byte[] decryptedRepository) { try { decryptedRepository = encryptor.Decrypt(binaryCloudRepository, transferCode); return(true); } catch (CryptoExceptionInvalidCipherFormat) { // If the downloaded repository is invalid, this is serioud and we should not continue throw; } catch (Exception) { // Could not decrypt with this transfercode decryptedRepository = null; return(false); } }
static void StringEncryptDecrypt() { KeyBlock encKey = new KeyBlock(64, "SeedPassword123*"); string Original1 = "Some string shorter than 64"; string Original2 = "Some string longer than 64 which is the same as the shorter one but with extra words to make it longer."; string Original3 = "Some string longer than 64 which is the same as the shorter one but with extra words to make it longer but I want to go all the way past 128."; Console.WriteLine(); Console.WriteLine(Original1); Console.WriteLine(Original2); Console.WriteLine(Original3); byte[] scrambleBytes1 = EncryptorDecryptor.ScrambleEncrypt(Encoding.UTF8.GetBytes(Original1), encKey); byte[] scrambleBytes2 = EncryptorDecryptor.ScrambleEncrypt(Encoding.UTF8.GetBytes(Original2), encKey); byte[] scrambleBytes3 = EncryptorDecryptor.ScrambleEncrypt(Encoding.UTF8.GetBytes(Original3), encKey); string scrambleString1 = Encoding.UTF8.GetString(scrambleBytes1); string scrambleString2 = Encoding.UTF8.GetString(scrambleBytes2); string scrambleString3 = Encoding.UTF8.GetString(scrambleBytes3); Console.WriteLine(); Console.WriteLine(scrambleString1); Console.WriteLine(scrambleString2); Console.WriteLine(scrambleString3); KeyBlock decKey = new KeyBlock(64, "SeedPassword123*"); byte[] deScrambled1 = EncryptorDecryptor.ScrambleDecrypt(scrambleBytes1, decKey); byte[] deScrambled2 = EncryptorDecryptor.ScrambleDecrypt(scrambleBytes2, decKey); byte[] deScrambled3 = EncryptorDecryptor.ScrambleDecrypt(scrambleBytes3, decKey); string deScrambledString1 = Encoding.UTF8.GetString(deScrambled1); string deScrambledString2 = Encoding.UTF8.GetString(deScrambled2); string deScrambledString3 = Encoding.UTF8.GetString(deScrambled3); Console.WriteLine(); Console.WriteLine(deScrambledString1); Console.WriteLine(deScrambledString2); Console.WriteLine(deScrambledString3); }
public void OkEncodeDecodeReplaceAttributeAndInnerTextByXPath() { // arrange var encryptorDecryptor = new EncryptorDecryptor(); var dllPath = Assembly.GetAssembly(typeof(TestEnvironmentForEncode)).EscapedCodeBase.TrimStart("file:///".ToArray()); var appConfigPath = string.Format("{0}.config", dllPath); using (var input = new XmlTransformableDocument()) { input.Load(appConfigPath); using (var stringWriter = new StringWriter()) using (var xmlWriter = XmlWriter.Create(stringWriter)) { input.WriteContentTo(xmlWriter); xmlWriter.Flush(); var result = stringWriter.ToString(); var doc = XDocument.Parse(result); var root = doc.Root; // assert var encryptedNode1 = root.Descendants("setting").Single(x => x.Attribute("name").Value == "ExpectedEncrypted1"); var encryptedNode1Attribute = encryptedNode1.Attribute("serializeAs").Value; encryptorDecryptor.Decrypt(encryptedNode1Attribute).Should().Be("String"); var encryptedNode1Value = encryptedNode1.Value; encryptorDecryptor.Decrypt(encryptedNode1Value).Should().Be("SomeNewEncryptedValue1"); var encryptedNode2 = root.Descendants("setting").Single(x => x.Attribute("name").Value == "ExpectedEncrypted2"); var encryptedNode2Attribute = encryptedNode2.Attribute("serializeAs").Value; encryptorDecryptor.Decrypt(encryptedNode2Attribute).Should().Be("String"); var encryptedNode2Value = encryptedNode2.Value; encryptorDecryptor.Decrypt(encryptedNode2Value).Should().Be("EncryptedValue2"); } } }
/// <summary> /// Test the password update from Version1 in Android to Version2 /// </summary> /// <param name="root"></param> protected override void UpdateSettingsFrom1To2(XElement root) { base.UpdateSettingsFrom1To2(root); const string snpsk = "53EC49B1-6600+406b;B84F-0B9CFA1D2BE1"; // Handle protected password XElement oldPasswortElement = root.Element("cloud_storage")?.Element("cloud_password"); XElement cloudStorageAccount = root.Element("cloud_storage_account"); if ((oldPasswortElement != null) && (cloudStorageAccount != null)) { // Deobfuscate old password EncryptorDecryptor decryptor = new EncryptorDecryptor("snps"); byte[] binaryCipher = CryptoUtils.Base64StringToBytes(oldPasswortElement.Value); byte[] unprotectedBinaryPassword = decryptor.Decrypt(binaryCipher, snpsk); // Protect with new data protection service and add to XML string protectedPassword = _dataProtectionService.Protect(unprotectedBinaryPassword); cloudStorageAccount.Add(new XElement("protected_password", protectedPassword)); CryptoUtils.CleanArray(unprotectedBinaryPassword); } }
/// <inheritdoc/> public override async Task Run() { try { SettingsModel settings = _settingsService.LoadSettingsOrDefault(); byte[] binaryCloudRepository = StoryBoard.LoadFromSession <byte[]>(SynchronizationStorySessionKey.BinaryCloudRepository.ToInt()); List <string> transferCodesToTry = ListTransferCodesToTry(settings); // Try to decode with all possible transfer codes EncryptorDecryptor encryptor = new EncryptorDecryptor("SilentNotes"); byte[] decryptedRepository = null; bool successfullyDecryptedRepository = false; int index = 0; while (!successfullyDecryptedRepository && index < transferCodesToTry.Count) { string transferCodeCandidate = transferCodesToTry[index]; successfullyDecryptedRepository = TryDecryptRepositoryWithTransfercode(encryptor, binaryCloudRepository, transferCodeCandidate, out decryptedRepository); if (successfullyDecryptedRepository) { // Store transfercode and encryption mode if necessary if (AdoptTransferCode(settings, transferCodeCandidate) || AdoptEncryptionMode(settings, encryptor, binaryCloudRepository)) { _settingsService.TrySaveSettingsToLocalDevice(settings); } } index++; } if (successfullyDecryptedRepository) { // Deserialize and update repository XDocument cloudRepositoryXml = XmlUtils.LoadFromXmlBytes(decryptedRepository); if (_noteRepositoryUpdater.IsTooNewForThisApp(cloudRepositoryXml)) { throw new SynchronizationStoryBoard.UnsuportedRepositoryRevisionException(); } _noteRepositoryUpdater.Update(cloudRepositoryXml); NoteRepositoryModel cloudRepository = XmlUtils.DeserializeFromXmlDocument <NoteRepositoryModel>(cloudRepositoryXml); // Continue with next step StoryBoard.StoreToSession(SynchronizationStorySessionKey.CloudRepository.ToInt(), cloudRepository); await StoryBoard.ContinueWith(SynchronizationStoryStepId.IsSameRepository.ToInt()); } else { bool existsUserEnteredTransferCode = StoryBoard.TryLoadFromSession <string>(SynchronizationStorySessionKey.UserEnteredTransferCode.ToInt(), out _); if (existsUserEnteredTransferCode) { // Keep transfercode page open and show message _feedbackService.ShowToast(_languageService["sync_error_transfercode"]); } else { // Open transfercode page await StoryBoard.ContinueWith(SynchronizationStoryStepId.ShowTransferCode.ToInt()); } } } catch (Exception ex) { // Keep the current page open and show the error message ShowExceptionMessage(ex, _feedbackService, _languageService); } }
public BouncyCastleAesStream(Stream stream, byte[] key) { Stream = stream; ED = new EncryptorDecryptor(key); }
public BouncyCastleAesStream(Socket client, byte[] key) { Stream = new NetworkStream(client); ED = new EncryptorDecryptor(key); }
public UserController(IAsyncContactRepository <User> userRepository, IAsyncContactRepository <Tenant> tenantRespository, EncryptorDecryptor encryptorDecryptor) { _encryptorDecryptor = encryptorDecryptor; _tenantRepository = tenantRespository; _userRepository = userRepository; }