簡體   English   中英

如何解密由RSACryptoServiceProvider簽名的數據

[英]How to decrypt data signed by RSACryptoServiceProvider

我開始在Web服務中使用加密和解密。 我正在使用RSACryptoServiceProvider,並且在使用“ 加密解密”方法時,我沒有問題。

但是,一旦我嘗試將SignData方法與新的SHA1CryptoServiceProvider()作為加密方法一起使用,我將無法恢復原始數據。 我只能驗證它們。 真的不可能檢索簽名的數據嗎? 如果是這樣,整個簽名過程的目的是什么? 還有另一種可能性如何通過某種算法加密數據?

編輯:我發布代碼,這只是從MSDN的更改的示例

static void Main()
{
    try
    {
        //Create a UnicodeEncoder to convert between byte array and string.
        ASCIIEncoding ByteConverter = new ASCIIEncoding();

        string dataString = "Data to Encrypt";

        //Create byte arrays to hold original, encrypted, and decrypted data. 
        byte[] dataToEncrypt = ByteConverter.GetBytes(dataString);
        byte[] encryptedData;
        byte[] signedData;
        byte[] decryptedData;
        byte[] unsignedData;
        var fileName = ConfigurationManager.AppSettings["certificate"];
        var password = ConfigurationManager.AppSettings["password"];
        var certificate = new X509Certificate2(fileName, password);

        //Create a new instance of the RSACryptoServiceProvider class  
        // and automatically create a new key-pair.
        RSACryptoServiceProvider RSAalg = (RSACryptoServiceProvider)certificate.PrivateKey;
        //RSAPKCS1SignatureDeformatter def = (RSAPKCS1SignatureDeformatter)certificate.PrivateKey;

        //Display the origianl data to the console.
        Console.WriteLine("Original Data: {0}", dataString);

        //Encrypt the byte array and specify no OAEP padding.   
        //OAEP padding is only available on Microsoft Windows XP or 
        //later.  
        encryptedData = RSAalg.Encrypt(dataToEncrypt, false);
        signedData = RSAalg.SignData(dataToEncrypt, new SHA1CryptoServiceProvider());

        //Display the encrypted data to the console. 
        Console.WriteLine("Encrypted Data: {0}", ByteConverter.GetString(encryptedData));
        Console.WriteLine("Signed Data: {0}", ByteConverter.GetString(signedData));

        //Pass the data to ENCRYPT and boolean flag specifying  
        //no OAEP padding.
        decryptedData = RSAalg.Decrypt(encryptedData, false);
    //In the next line I get the error of wrong data
        unsignedData = RSAalg.Decrypt(signedData, false);

        //Display the decrypted plaintext to the console. 
        Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData));
        Console.WriteLine("Unsigned plaintext: {0}", ByteConverter.GetString(unsignedData));
    }
    catch (CryptographicException e)
    {
        //Catch this exception in case the encryption did 
        //not succeed.
        Console.WriteLine(e.Message);

    }

    Console.Read();
}

SHA1是一個哈希函數,因此您無法計算具有給定哈希值的消息。 換句話說,您不能簽名/取消簽名,只能簽名和驗證。

暫無
暫無

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

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