.NET Framework 4.7中RSA.OaepSHA256加密是否采用MGF1填充?代码咨询
Great questions—let's unpack them step by step:
问题1:在System.Security.Cryptography.RSA.Encrypt方法中使用RSAEncryptionPadding.OaepSHA256时,是否默认采用MGF1填充?
Short answer: Yes, it does.
In .NET Framework 4.7, the RSAEncryptionPadding.OaepSHA256 preset follows the PKCS#1 v2.2 standard, which specifies MGF1 as the default (and widely accepted) mask generation function for OAEP padding. Not only that, it uses SHA256 as the hash algorithm for both the OAEP digest calculation and the MGF1 function itself—this is the standard, secure configuration for OAEP-SHA256.
问题2:代码是否符合OaepSHA256 + MGF1的需求?
First, let's clarify the relationship between OAEP and MGF1 to clear up any confusion:
- OAEP (Optimal Asymmetric Encryption Padding) is a full padding scheme for RSA that adds extra security layers to prevent common attacks (like chosen-ciphertext attacks).
- MGF1 (Mask Generation Function 1) is the critical building block OAEP uses to generate the cryptographic masks needed for its padding process. You can think of OAEP as the complete recipe, and MGF1 as one of the key ingredients that makes the recipe work as intended.
Now, looking at your code:
var encryptionCert = new X509Certificate2(certBytes); using (var rsaPublicKey = encryptionCert.GetRSAPublicKey()) { var encryptedKeyBytes = rsaPublicKey.Encrypt(plainBytes, RSAEncryptionPadding.OaepSHA256); }
This code perfectly meets your requirement. As we covered earlier, RSAEncryptionPadding.OaepSHA256 in .NET Framework 4.7 is exactly RSA encryption with OAEP-SHA256 padding, which inherently uses MGF1 (with SHA256 as its hash function). You don't need to make any modifications—your implementation is correctly using the combination you specified.
If you ever want to make this explicit for code clarity (though it's not necessary here), you could also write RSAEncryptionPadding.CreateOaep(HashAlgorithmName.SHA256) instead of using the preset—this is functionally identical and does the exact same thing.
内容的提问来源于stack exchange,提问作者Raghu

