加密数据并验证签名C#
我想申请两份。第一个将对文件进行加密并签名。第二个是加密和验证数据。我使用以下代码作为示例加密数据并验证签名C#,c#,rsa,rsacryptoserviceprovider,C#,Rsa,Rsacryptoserviceprovider,我想申请两份。第一个将对文件进行加密并签名。第二个是加密和验证数据。我使用以下代码作为示例 using System; using System.Security.Cryptography; using System.Text; class RSACSPSample { static void Main() { try { // Create a UnicodeEncoder to convert between byte
using System;
using System.Security.Cryptography;
using System.Text;
class RSACSPSample
{
static void Main()
{
try
{
// Create a UnicodeEncoder to convert between byte array and string.
ASCIIEncoding ByteConverter = new ASCIIEncoding();
string dataString = "Data to Sign";
// Create byte arrays to hold original, encrypted, and decrypted data.
byte[] originalData = ByteConverter.GetBytes(dataString);
byte[] signedData;
// Create a new instance of the RSACryptoServiceProvider class
// and automatically create a new key-pair.
RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();
// Export the key information to an RSAParameters object.
// You must pass true to export the private key for signing.
// However, you do not need to export the private key
// for verification.
RSAParameters Key = RSAalg.ExportParameters(true);
// Hash and sign the data.
signedData = HashAndSignBytes(originalData, Key);
// Verify the data and display the result to the
// console.
if(VerifySignedHash(originalData, signedData, Key))
{
Console.WriteLine("The data was verified.");
}
else
{
Console.WriteLine("The data does not match the signature.");
}
}
catch(ArgumentNullException)
{
Console.WriteLine("The data was not signed or verified");
}
}
public static byte[] HashAndSignBytes(byte[] DataToSign, RSAParameters Key)
{
try
{
// Create a new instance of RSACryptoServiceProvider using the
// key from RSAParameters.
RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();
RSAalg.ImportParameters(Key);
// Hash and sign the data. Pass a new instance of SHA1CryptoServiceProvider
// to specify the use of SHA1 for hashing.
return RSAalg.SignData(DataToSign, new SHA1CryptoServiceProvider());
}
catch(CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
}
public static bool VerifySignedHash(byte[] DataToVerify, byte[] SignedData, RSAParameters Key)
{
try
{
// Create a new instance of RSACryptoServiceProvider using the
// key from RSAParameters.
RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();
RSAalg.ImportParameters(Key);
// Verify the data using the signature. Pass a new instance of SHA1CryptoServiceProvider
// to specify the use of SHA1 for hashing.
return RSAalg.VerifyData(DataToVerify, new SHA1CryptoServiceProvider(), SignedData);
}
catch(CryptographicException e)
{
Console.WriteLine(e.Message);
return false;
}
}
}
问题是我无法理解如何获取函数VerifySignedHash的原始数据(第一个参数)?我的意思是应用程序(签名检查器)将读取签名数据。如何将已签名的数据转换为原始数据进行数据验证?是否确实要对数据进行加密和数字签名?目前,您仅创建数字签名。你所谓的签名数据实际上就是签名。它不包含数据本身。哦……现在我明白了。签名是否与数据分开存储,不是吗?是的,签名是分开的。如果您希望同时传输数据和签名(或将其存储在单个文件中),则需要提供自己的传输或文件格式。