問題描述
我需要一些簡單的字符串加密,所以我編寫了以下代碼(來自 這里):
I needed some simple string encryption, so I wrote the following code (with a great deal of "inspiration" from here):
代碼似乎工作正常,除了當(dāng)使用不正確的密鑰解密數(shù)據(jù)時(shí),我在解密字符串的 cs.Close() 行上收到 CryptographicException - 填充無效且無法刪除".
The code appears to work fine, except that when decrypting data with an incorrect key, I get a CryptographicException - "Padding is invalid and cannot be removed" - on the cs.Close() line in decryptString.
示例代碼:
我的問題是,這是意料之中的嗎?我原以為用錯(cuò)誤的密碼解密只會(huì)導(dǎo)致無意義的輸出,而不是異常.
My question is, is this to be expected? I would have thought that decrypting with the wrong password would just result in nonsense output, rather than an exception.
推薦答案
雖然已經(jīng)回答了這個(gè)問題,但我認(rèn)為最好解釋一下為什么這是意料之中的.
Although this have been already answered I think it would be a good idea to explain why it is to be expected.
通常會(huì)應(yīng)用填充方案,因?yàn)榇蠖鄶?shù)加密過濾器在語義上并不安全,并且可以防止某些形式的加密攻擊.例如,通常在 RSA 中使用 OAEP 填充方案來防止某些類型的攻擊(例如選擇的明文攻擊或blinding).
A padding scheme is usually applied because most cryptographic filters are not semantically secure and to prevent some forms of cryptoatacks. For example, usually in RSA the OAEP padding scheme is used which prevents some sorts of attacks (such as a chosen plaintext attack or blinding).
在發(fā)送消息之前,填充方案會(huì)在消息 m 上附加一些(通常)隨機(jī)垃圾.在OAEP方法中,例如使用了兩個(gè)Oracle(這是一個(gè)簡單的解釋):
A padding scheme appends some (usually) random garbage to the message m before the message is sent. In the OAEP method, for example, two Oracles are used (this is a simplistic explanation):
- 給定模數(shù)的大小,您用 0 填充 k1 位,用隨機(jī)數(shù)填充 k0 位.
- 然后通過對消息進(jìn)行一些轉(zhuǎn)換,您可以獲得經(jīng)過加密和發(fā)送的填充消息.
這為您提供了消息的隨機(jī)化,并提供了一種測試消息是否垃圾的方法.由于填充方案是可逆的,當(dāng)您解密消息時(shí),雖然您無法說明消息本身的完整性,但實(shí)際上您可以對填充做出一些斷言,因此您可以知道消息是否已正確解密或者您做錯(cuò)了什么(即有人篡改了消息或您使用了錯(cuò)誤的密鑰)
That provides you with a randomization for the messages and with a way to test if the message is garbage or not. As the padding scheme is reversible, when you decrypt the message whereas you can't say anything about the integrity of the message itself you can, in fact, make some assertion about the padding and thus you can know if the message has been correctly decrypted or you're doing something wrong (i.e someone has tampered with the message or you're using the wrong key)
這篇關(guān)于為什么密碼錯(cuò)誤會(huì)導(dǎo)致“填充無效且無法刪除"?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!