簡體   English   中英

使用RSACryptoServiceProvider使用過期的證書加密/解密數據沒有錯誤

[英]No error encrypting / decrypting data with an expired certificate using RSACryptoServiceProvider

我目前正在做一個概念證明,以使用證書對數據進行加密。 它運作良好,但現在,我想嘗試證書過期的情況。 我創建了一個過期的證書,但令我驚訝的是,即使使用了過期的證書,一切正常。 我期待一個錯誤。

您是否知道這是因為它是自簽名證書?

這是我用來測試案例的代碼

[TestMethod]
public void Encrypt_decrypt_with_expired_certificate()
{
    //Arrange
    var baseString = "This is an encryption test";
    X509Certificate2 newX509Certificate2 = new X509Certificate2("d:\\testx509certExpired.pfx", "apassword");
    Console.WriteLine(newX509Certificate2.NotAfter); //Show the expiration date which is in the past
    var encryptor = new CertificateEncryptor(newX509Certificate2); //This class is a simple wrapper around RSACryptoServiceProvider

    //Act
    string encryptedResult = encryptor.Encrypt(baseString); //Exception expected because of the expired certificate but not thrown

    //Assert
    Console.WriteLine("Base string : {0}", baseString);
    Console.WriteLine("Encrypted string : {0}", encryptedResult);
    Assert.IsNotNull(encryptedResult);

    //revert back
    string decryptedString = encryptor.Decrypt(encryptedResult);
    Console.WriteLine("Decrypted string : {0}", decryptedString);
    Assert.AreEqual(baseString, decryptedString);
}

謝謝

正如GregS所說, RSACryptoServiceProvider類(不是X509Certificate2)提供了執行加密操作的能力。 RSACryptoServiceProvider對證書一無所知,只知道密鑰及其參數。 這就是為什么您看不到任何錯誤的原因。

這意味着證書驗證-是您的應用程序責任。 加密數據時應檢查證書,並跳過所有證書檢查以解密數據。

嘗試訪問證書的X509Certificate2.PublicKey.Key屬性時,如果證書不在其有效期內,則應引發CryptographicException。

這是我從證書加載公鑰和私鑰以執行加密操作的方式:

using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

class Example

{
    private RSACryptoServiceProvider publicKey,
                                     privateKey;

    private bool getRSAKeys(X509Certificate2 cert, StoreLocation location)
    {
        try
        {
            //This will throw a CryptographicException if the certificate is expired
            publicKey = (RSACryptoServiceProvider)cert.PublicKey.Key;

            privateKey = (RSACryptoServiceProvider)cert.PrivateKey;
            return true;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("The certificate is expired or otherwise unusable\r\n" + e.ToString());
            return false;
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM