private byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV) { // Check arguments. if (plainText == null || plainText.Length <= 0) { throw new ArgumentNullException("plainText"); } if (Key == null || Key.Length <= 0) { throw new ArgumentNullException("Key"); } if (IV == null || IV.Length <= 0) { throw new ArgumentNullException("IV"); } byte[] encrypted; string ivString; // Create an AesManaged object // with the specified key and IV. using (AesManaged aesAlg = new AesManaged()) { aesAlg.Key = Key; aesAlg.IV = IV; ivString = EncodingTools.Base64EncodeByteArrayToString(aesAlg.IV); // Create an encryptor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. try { using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); } } } catch (Exception e) { encrypted = new byte[0]; _logger.AddLogEntry($"Failed to encrypt settings: {e.Message}"); } } // Return the encrypted bytes from the memory stream. return(encrypted); }
private Tuple <byte[], byte[]> FindIv(string input) { var splitInput = input.Split('|'); if (splitInput.Length != 2) { _logger.AddLogEntry("Failed to get IV from string provided."); return(null); } // position 0 is IV return(Tuple.Create(EncodingTools.Base64DecodeStringToByteArray(splitInput[0]), EncodingTools.Base64DecodeStringToByteArray(splitInput[1]))); }
public string AesEncrypt(string input, string pass, byte[] iv = null) { byte[] encrypted; string ivString; using (AesManaged aes = new AesManaged()) { // Encrypt the string to an array of bytes. aes.Key = Hashing.ComputeSha256(pass); encrypted = EncryptStringToBytes_Aes(input, aes.Key, aes.IV); ivString = EncodingTools.Base64EncodeByteArrayToString(aes.IV); } return(ivString + '|' + EncodingTools.Base64EncodeByteArrayToString(encrypted)); }
public string AesDecrypt(string input, string pass, byte[] iv = null) { string decrpyted; byte[] encryptedMessage = EncodingTools.StringToByteArray(input); if (iv == null) { var inputIvTuple = FindIv(input); iv = inputIvTuple.Item1; encryptedMessage = inputIvTuple.Item2; // if still null :( if (iv == null || encryptedMessage == null) { _logger.AddLogEntry($"Failed to gather required information. iv: {iv}, encryptedMessage: {encryptedMessage}"); return(string.Empty); } } try { using (AesManaged aes = new AesManaged()) { aes.Key = Hashing.ComputeSha256(pass); aes.IV = iv; // Encrypt the string to an array of bytes. decrpyted = DecryptStringFromBytes_Aes(encryptedMessage, aes.Key, aes.IV); } } catch (Exception e) { _logger.AddLogEntry($"Failed to decrypt message: {e}"); return(string.Empty); } return(decrpyted); }