/// <summary> /// Decrypts a string. /// </summary> /// <param name="encryptedText">The base64-encrypted string.</param> /// <param name="key">The key to use for decryption.</param> /// <returns>The decrypted string.</returns> public static string Decrypt(this string encryptedText, string key) { if (string.IsNullOrEmpty(encryptedText)) { return(encryptedText); } if (string.IsNullOrEmpty(key)) { #pragma warning disable CA2208 // Instantiate argument exceptions correctly (this class is obsolete, we won't fix it) throw new ArgumentNullException("Missing key"); #pragma warning restore CA2208 // Instantiate argument exceptions correctly } var parts = encryptedText.Split('!'); if (parts.Length != 2) { throw new ArgumentException("EncryptedText is not properly formatted"); } byte[] bytesIv; try { bytesIv = Convert.FromBase64String(parts[0]); } catch (FormatException) { throw new ArgumentException("EncryptedText[0] is not properly formatted"); } byte[] cipherText; try { cipherText = Convert.FromBase64String(parts[1]); } catch (FormatException) { throw new ArgumentException("EncryptedText[1] is not properly formatted"); } byte[] bytesKey; try { bytesKey = Convert.FromBase64String(key); } catch (FormatException) { throw new ArgumentException("Key is not properly formatted"); } // parts[0] == base64 iv parts[1] == base64 encoded encrypted bytes return(EncryptUtilities.DecryptStringFromBytes_Aes(cipherText: cipherText, key: bytesKey, iv: bytesIv)); }
/// <summary> /// Decrypts a string. /// </summary> /// <param name="encryptedText">The base64-encrypted string.</param> /// <param name="key">The key to use for decryption.</param> /// <returns>The decrypted string.</returns> public static string Decrypt(this string encryptedText, string key) { if (string.IsNullOrEmpty(encryptedText)) { return(encryptedText); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("Missing key"); } var parts = encryptedText.Split('!'); if (parts.Length != 2) { throw new ArgumentException("EncryptedText is not properly formatted"); } byte[] bytesIv; try { bytesIv = Convert.FromBase64String(parts[0]); } catch (FormatException) { throw new ArgumentException("EncryptedText[0] is not properly formatted"); } byte[] cipherText; try { cipherText = Convert.FromBase64String(parts[1]); } catch (FormatException) { throw new ArgumentException("EncryptedText[1] is not properly formatted"); } byte[] bytesKey; try { bytesKey = Convert.FromBase64String(key); } catch (FormatException) { throw new ArgumentException("Key is not properly formatted"); } // parts[0] == base64 iv parts[1] == base64 encoded encrypted bytes return(EncryptUtilities.DecryptStringFromBytes_Aes(cipherText: cipherText, key: bytesKey, iv: bytesIv)); }