我需要制作软件激活机制。 所以我最终得到了这个方案: 应用程序基于计算机硬件创建唯一ID。 买方通过电子邮件将此ID发送给我。 我用我的私钥签名,然后发回签名的字符串。 应用程序验证字符串(使用包含的公钥对其进行解码并将其与硬件ID进行比较)。
到目前为止,我完成了硬件ID,我已经用openssl创建了密钥(1024bit),这两个文件是private.pem和public.pem。
我使用了msdn提供的一些代码,但我不太了解如何将我的密钥导入RSA算法。 一些代码如下,任何帮助将不胜感激......
try
{
// Create a UnicodeEncoder to convert between byte array and string.
ASCIIEncoding ByteConverter = new ASCIIEncoding();
string dataString = CompID.Text;
// 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);
ActCode.Text = Encoding.UTF8.GetString(signedData, 0, signedData.Length);
// Verify the data and display the result to the
// console.
if (VerifySignedHash(originalData, signedData, Key))
{
MessageBox.Show("The data was verified.");
}
else
{
MessageBox.Show("The data does not match the signature.");
}
}
catch (ArgumentNullException)
{
MessageBox.Show("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)
{
MessageBox.Show(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)
{
MessageBox.Show(e.Message);
return false;
}
}