C#AES 256位解密给定的加密文本和密码
有人问我,如果知道密钥,如何解密给定的AES 256位加密字符串。我对加密不是很熟悉,所以我坐下来研究这个问题 我找到了,并尝试将其修改为仅进行解密:C#AES 256位解密给定的加密文本和密码,c#,encryption,aes,C#,Encryption,Aes,有人问我,如果知道密钥,如何解密给定的AES 256位加密字符串。我对加密不是很熟悉,所以我坐下来研究这个问题 我找到了,并尝试将其修改为仅进行解密: using System; using System.IO; using System.Security.Cryptography; using System.Text; internal class AesExample { public static void Main() { var encryptedSt
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
有人建议对这个秘密进行一番讨论,然后把它改成20个“是”。我试过了,我开始得到一个新的加密异常,消息是“要解密的数据长度无效”
因此,我有几个问题:
1) 如果只提供加密文本和密钥,这是否可能
2) 如果是这样的话,它们是否是人们需要做出的一些基本假设,比如密码?我读到ECB模式没有初始化向量。这就是为什么我要问
3) 我需要做什么才能将输入(加密文本和密钥)转换为正确的Byte[]格式,以便解密工作
谢谢 AES密钥长度为128、192和256位,具体取决于要使用的密码。您必须确保字符串的字节长度合适。您可能需要更多信息才能完成此操作。要回答您的具体问题:
这听起来是一个有趣的练习,但如果没有更多的信息,你可能最终会感到沮丧。encryptedString UTF-16不是吗?那么为什么要将其编码为UTF-8?@NaNa-我不知道确切的编码是什么,但将其更改为UTF16(encoding.Unicode in.Net)会导致相同的“要解密的数据长度无效”加密异常。无论是谁问你这个问题,他们是否指定了加密字符串的获取方式?与中一样,它是否使用了另一个C#程序,该程序具有或类似功能?我问这个问题的唯一原因是我在不久前尝试将javascript代码移植到C#时遇到了一个问题。javascript代码使用的AES实现无法与C#中的任何标准AES类复制。@IchabodClay-不,它们没有。感觉有点像PHP代码。PHP使用零值字节将密钥扩展到128位(然后根据大小扩展为192位或256位)。它使用相同的填充思想。当涉及到加密标准时,两者当然都是完全愚蠢的,但事实确实如此。哦,许多PHP站点也使用块大小为256位的Rijndael,而不是AES。