如何解密RSACryptoServiceProvider签名的数据

本文关键字:数据 RSACryptoServiceProvider 何解密 解密 | 更新日期: 2023-09-27 18:25:01

我开始在web服务中使用加密和解密。我正在使用RSACryptoServiceProvider,并且在使用Encrypt&解密方法,我没有问题。

但是,一旦我尝试将SignData方法与new 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();
}

如何解密RSACryptoServiceProvider签名的数据

SHA1是一个散列函数,因此您无法计算具有给定散列的消息。换句话说,您不能对消息进行签名/取消签名,只能对其进行签名和验证。