简体   繁体   English

C#中的AES解密独特

[英]AES decryption in C# uniqUE

I am using the AES to encrypt and decrypt passwords on a website.我正在使用 AES 加密和解密网站上的密码。 Anyways;无论如何; the encrypting works just fine.加密工作得很好。 But I have some problems with the decrypting.但是我在解密时遇到了一些问题。 On the line:在线上:

byte[] decrypted = DecryptStringFromBytes_Aes(encrypted, key, iv);

I recieve this error: Cannot implicity convert type 'string' to 'byte[]'.我收到此错误:无法隐式将类型“字符串”转换为“字节[]”。 I have tried lots of things, but nothing seem to work.我尝试了很多东西,但似乎没有任何效果。

You can see the rest of the code below.您可以在下面看到其余的代码。

string original = txtEncrypt.Text;

        byte[] key = new byte[] { 3,122,23,189,15,2,55,82,97,17,255,45,1,65,41,200 };

        byte[] iv = new byte[16];
        Aes myAes = Aes.Create();

        byte[] encrypted = EncryptStringToBytes_Aes(original, key, iv);
        byte[] decrypted = DecryptStringFromBytes_Aes(encrypted, key, iv);

Sincerely, Adrian真诚的,阿德里安

The sample code that you used returns the ciphertext as byte array.您使用的示例代码将密文作为字节数组返回。 Modern ciphers, like AES in CBC mode as you're using, operate on bytes, not strings.现代密码,如您使用的 CBC 模式下的 AES,对字节而不是字符串进行操作。

So if you need a string then you need to convert to a string and then back again.因此,如果您需要一个字符串,那么您需要转换为一个字符串,然后再返回。 For this you could use an encoding such as base 64 encoding.为此,您可以使用诸如 base 64 编码之类的编码。 So encode to base 64 after encryption and then decode before decryption.所以加密后编码为base 64,然后在解密前解码。

If you just directly interpret the bytes as a string (eg UTF-8) then you will experience data loss as not every byte is a valid / printable UTF-8 character.如果您只是直接将字节解释为字符串(例如 UTF-8),那么您将遇到数据丢失,因为并非每个字节都是有效/可打印的 UTF-8 字符。

Don't forget to include all required information that needs to be shared, such as the IV.不要忘记包含需要共享的所有必需信息,例如 IV。 The example code conveniently forgets about that. 示例代码很方便地忘记了这一点。

Note that CBC is not secure for transport mode security;请注意,CBC 对于传输模式的安全性并不安全; only use for data at rest.仅用于静态数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM