[英]C# AES 256-Bit Decrypt given Encrypted Text and Secret
如果我知道密鑰,有人問我如何解密給定的AES 256位加密字符串。 我對加密技術不太熟悉,所以我坐下來研究這個問題。
我在MSDN上找到了這個例子 ,並嘗試修改它只做Decrypt:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
internal class AesExample
{
public static void Main()
{
var encryptedString = "U2FsdGVkX1/cHT8XuHCfpw0AV4jpaO8JfLqUeCRJqjY=";
var secret = "SPARKY";
// I know this is not the correct way to get my input byte arrays...
// Just illustrating that I DO need byte arrays.
var encryptedBytes = Encoding.UTF8.GetBytes(encryptedString);
var secretBytes = Encoding.UTF8.GetBytes(secret);
try
{
using (var aes = new AesManaged())
{
aes.Key = secretBytes;
// Decrypt the bytes to a string.
var decryptedString = Decrypt(encryptedBytes, aes.Key, aes.IV);
//Display the original data and the decrypted data.
Console.WriteLine("Encrypted: {0}", encryptedString);
Console.WriteLine("Decrypted: {0}", decryptedString);
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
private static string Decrypt(byte[] cipherText, byte[] key, byte[] iv)
{
// Declare the string used to hold
// the decrypted text.
string plaintext;
// Create an AesManaged object
// with the specified key and IV.
using (var aes = new AesManaged())
{
aes.Key = key;
aes.IV = iv;
// Create a decrytor to perform the stream transform.
var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
// Create the streams used for decryption.
using (var msDecrypt = new MemoryStream(cipherText))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
當然,只要我點擊以下行,就會拋出CryptographicExcetion,並顯示消息“指定密鑰不是此算法的有效大小”。 ==> aes.Key = secretBytes
有人建議對這個秘密進行SHA1哈希並將其修改為20個字節。 我試過了,我開始得到一個新的CryptographicException,消息“要解密的數據長度無效”。
所以,我有幾個問題:
1)只有加密文本和密鑰才能實現這一點嗎?
2)如果是這樣,它們是否需要做一些基本假設,比如CipherMode? 我讀到ECB模式沒有初始化向量。 這就是我問的原因。
3)我需要做什么才能將輸入(加密文本和密鑰)放入正確的Byte []格式以使解密工作?
謝謝!
您可能需要更多信息才能使其工作。 回答您的具體問題:
Rfc2898DeriveBytes
(.NET中一種流行的KDF)運行您的密碼,以獲得可能有效的不同AES密鑰,但它也需要您顯然沒有的參數。 您還可以嘗試使用密碼的各種SHA哈希摘要,但是20個字節也不是有效的AES密鑰 - 您需要16,24或32字節密鑰。 Convert.FromBase64String(encryptedString);
在.NET中將它轉換為字節數組非常簡單Convert.FromBase64String(encryptedString);
。 這聽起來像一個有趣的練習,但你可能只是在沒有更多信息的情況下最終會感到沮喪。
AES密鑰長度為128,192和256位,具體取決於您要使用的密碼。 您必須確保您的字符串是適當的字節長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.