且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 AesCryptoServiceProvider 获取不正确的解密值

更新时间:2023-11-08 10:56:04

使用密码原语很容易犯实现错误,人们一直在这样做,***使用 高级库,如果可以的话.

It is easy to make implementation mistakes with cryptographic primitives, people do it all the time, it's best to use a high level library if you can.

我有一个代码段,我会不断查看并更新它,它与您的效果非常接近'重新做.它还对密文进行身份验证,如果有任何对手可以将选定的密文发送到您的解密实现,我会建议这样做,有很多与修改密文相关的旁道攻击.

I have a snippet that I try to keep reviewed and up to date, that works pretty close to what you're doing. It also does authentication on the cipher text, which I would recommend if there is anyway an adversary could send chosen ciphertext to your decryption implementation, there are a lot of side channel attacks related to modifying the ciphertext.

但是,您遇到的问题与填充没有任何关系,如果您的密文与您的密钥和 iv 不匹配,并且您没有验证您的 iv 和密文,您通常会得到填充错误(如果这是冒泡的客户端,则称为 填充预言机).您需要将主语句更改为:

However, the problem you're having does not have any thing to do with padding, if your ciphertext doesn't matchup to your key and iv, and you didn't authenticate your iv and ciphertext, you'll typically get a padding error (if this is bubbled up a client it's called a padding oracle). You need to change your main statement to:

    string valid128BitString = "AAECAwQFBgcICQoLDA0ODw==";
    string inputValue = "Test";
    string keyValue = valid128BitString;


    byte[] byteValForString = Encoding.UTF8.GetBytes(inputValue);
    EncryptResult result = Aes128Utility.EncryptData(byteValForString, keyValue);
    EncryptResult encyptedValue = new EncryptResult();
    encyptedValue.IV = result.IV; //<--Very Important
    encyptedValue.EncryptedMsg = result.EncryptedMsg;

    string finalResult =Encoding.UTF8.GetString(Aes128Utility.DecryptData(encyptedValue, keyValue));

因此,您使用与加密相同的 IV 来解密.

So you use the same IV to decrypt as you did to encrypt.