当前位置: 首页 > 编程语言 > C#

如何解密AES-256-CBC加密字符串分享

时间:2023-04-10 18:35:36 C#

如何解密AES-256-CBC加密字符串我是C#的新手,我真的需要帮助。我需要在C#中使用AES-256-CBC加密/解密字符串,我发现这是为了加密字符串:publicstaticstringEncryptString(stringmessage,stringKeyString,stringIVString){byte[]Key=ASCIIEncoding.UTF8.GetBytes(KeyString);byte[]IV=ASCIIEncoding.UTF8.GetBytes(IVString);字符串加密=空;RijndaelManagedrj=newRijndaelManaged();rj.Key=密钥;rj.IV=IV;rj.Mode=CipherMode.CBC;尝试{MemoryStreamms=newMemoryStream();使用(CryptoStreamcs=newCryptoStream(ms,rj.CreateEncryptor(Key,IV),CryptoStreamMode.Write)){使用(StreamWritersw=newStreamWriter(cs)){sw.Write(message);sw.Close();}cs.Close();}byte[]encoded=ms.ToArray();encrypted=Convert.ToBase64String(编码);关闭();}catch(CryptographicExceptione){Console.WriteLine("ACryptographicerroroccurred:{0}",e.Message);返回空值;}catch(UnauthorizedAccessExceptione){Console.WriteLine("发生文件错误:{0}",e.Message);返回空值;}catch(Exceptione){Console.WriteLine("发生错误:{0}",e.Message);}最后{rj.Clear();}返回加密;我尝试根据上面的代码编写一个解密函数,下面的代码是我所做的://DecryptabytearrayintoabytearrayusingakeyandanIVprivatebyte[]Decrypt(byte[]cipherData,byte[]Key,byte[]IV){byte[]decryptedData;//字符串明文=空;//内存流ms=newMemoryStream(cipherData);RijndaelManagedalg=newRijndaelManaged();alg.KeySize=256;alg.BlockSize=128;alg.Key=键;alg.IV=IV;alg.Mode=CipherMode.CBC;alg.Padding=PaddingMode.Zeros;//Array.Copy(Key,0,IV,0,IV.Length);ICryptoTransform解密器=alg.CreateDecryptor(alg.Key,alg.IV);使用(MemoryStreamms=newMemoryStream(cipherData)){使用(CryptoStreamcsDecrypt=newCryptoStream(ms,解密器,CryptoStreamMode.Read)){使用(StreamReadersw=newStreamReader(csDecrypt)){sw.ReadToEnd();sw.Close();}csDecrypt.Close();解密数据=ms.ToArray();}}//字节[]decryptedData=System.Text.Encoding.Unicode.GetBytes(明文);返回解密数据;但这是胡说八道,它不会解密任何我真的很困惑并需要帮助的东西。谢谢你的帮助!P/s:请不要给我其他类似的回答问题,我已经看过了。他们的加密函数与上面的加密函数没有相同的输出,而我需要解密一个必须用上面的函数加密的字符串。我有两个朋友用PHP和Objective-C写了一个解密函数,和上面的加密函数很匹配,让他们再写一次不好。查看您的加密,应该这样做,传递加密的结果字符串应该返回原始字符串;//使用密钥和IV将字符串解密为字符串byte[]iv=Encoding.UTF8.GetBytes(ivString);尝试使用(varrijndaelManaged=newRijndaelManaged{Key=key,IV=iv,Mode=CipherMode.CBC})使用(varmemoryStream=newMemoryStream(Convert.FromBase64String(cipherData)))使用(varcryptoStream=newCryptoStream(memoryStream),rijndaelManaged.CreateDecryptor(key,iv),CryptoStreamMode.Read)){返回新的StreamReader(cryptoStream).ReadToEnd();}}catch(CryptographicExceptione){Console.WriteLine("发生密码错误:{0}",e.Message);返回空值;}//你可能想在这里捕获更多异常...}小记;您在密钥字符串中使用UTF8编码获取密钥,UTF8编码可能会为国际字符提供多个字节,这可能会导致密钥或IV加密/解密的长度错误。此外,使用8个字符的小范围密码/密钥加上可打印字符不会为您提供非常安全的加密,您可能希望在将字符串用作密钥之前通过SHA1或类似方式运行该字符串(不幸的是,这将使其不同于当前加密)以上就是C#学习教程:如何解密AES-256-CBC加密字符串的全部内容。注意——本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: