有人问我,如果我知道一个AES 256位加密的字符串的秘钥,我该如何解密它。由于我对加密不太熟悉,所以我开始探究这个问题。
我在MSDN上找到了这个示例,并尝试修改它只进行解密:
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;
}
}
当我运行到以下这一行时,抛出了CryptographicException异常,异常信息为“指定的密钥对于此算法无效。” ==> aes.Key = secretBytes
有人建议对密钥进行SHA1哈希,并将其裁剪为20个字节。 我尝试了一下,结果开始收到新的CryptographicException异常,异常信息为“要解密的数据长度无效。”
所以,我有几个问题:
1)仅给定加密文本和密钥,这是否可能?
2)如果可以,是否需要做出一些基本假设,比如CipherMode?我读到ECB模式没有初始化向量,这就是我问的原因。
3)我需要做些什么才能将输入(加密文本和密钥)转换为正确的Byte []格式以使解密正常工作?
谢谢!
AesManaged
或类似功能的C#程序吗?我之所以问这个问题,是因为我曾经尝试将JavaScript代码移植到C#时遇到了问题。JavaScript代码使用的AES实现无法用C#中任何标准的AES类复制。 - Ichabod Clay