我的程序首先使用.net自带的工具makecer.exe来生成带有私钥的pfx证书,然后想要使用此证书来实现RSA加密解密,但是在用公钥加密的时候没问题,用私钥解密的时候出现问题,提示或者是“该项不适于在指定状态下使用”,或者是“不正确的项”
protected void Button6_Click(object sender, EventArgs e)
{
string CurrentPath = Server.MapPath("./");//获得所在页面的当前目录,等价于Server.MapPath("")。
CreateCertWithPrivateKey("mycer.pfx", Server.MapPath("makecert.exe"));
ExportToPfxFile("mycer.pfx", CurrentPath+"mypfx.pfx", "123", true);
}
/// <summary>
/// 根据指定的证书名和makecert全路径生成证书(包含公钥和私钥,并保存在MY存储区)
/// </summary>
/// <param name="subjectName"></param>
/// <param name="makecertPath"></param>
/// <returns></returns>
public static bool CreateCertWithPrivateKey(string subjectName, string makecertPath)
{
subjectName = "CN=" + subjectName;
string param = " -pe -ss my -n \"" + subjectName + "\" ";
try
{
Process p = Process.Start(makecertPath, param);
p.WaitForExit();
p.Close();
}
catch (Exception e)
{
// LogRecord.putErrorLog(e.ToString(), "DataCerficate.CreateCertWithPrivateKey");
return false;
}
return true;
}
/// <summary>
/// 从WINDOWS证书存储区的个人MY区找到主题为subjectName的证书,
/// 并导出为pfx文件,同时为其指定一个密码
/// 并将证书从个人区删除(如果isDelFromstor为true)
/// </summary>
/// <param name="subjectName">证书主题,不包含CN=</param>
/// <param name="pfxFileName">pfx文件名</param>
/// <param name="password">pfx文件密码</param>
/// <param name="isDelFromStore">是否从存储区删除</param>
/// <returns></returns>
public static bool ExportToPfxFile(string subjectName, string pfxFileName,
string password, bool isDelFromStore)
{
subjectName = "CN=" + subjectName;
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates;
foreach (X509Certificate2 x509 in storecollection)
{
if (x509.Subject == subjectName)
{
Debug.Print(string.Format("certificate name: {0}", x509.Subject));
byte[] pfxByte = x509.Export(X509ContentType.Pfx, password);
using (FileStream fileStream = new FileStream(pfxFileName, FileMode.Create))
{
// Write the data to the file, byte by byte.
for (int i = 0; i < pfxByte.Length; i++)
fileStream.WriteByte(pfxByte[i]);
// Set the stream position to the beginning of the file.
fileStream.Seek(0, SeekOrigin.Begin);
// Read and verify the data.
for (int i = 0; i < fileStream.Length; i++)
{
if (pfxByte[i] != fileStream.ReadByte())
{
// LogRecord.putErrorLog("Export pfx error while verify the pfx file!", "ExportToPfxFile");
fileStream.Close();
return false;
}
}
fileStream.Close();
}
if (isDelFromStore == true)
store.Remove(x509);
}
}
store.Close();
store = null;
storecollection = null;
return true;
}
就是运行到如下图所示的断点位置时候出现错误:
恳求大侠给予指点,不胜感激!!
博主,您好,我遇到相同的问题,在网上搜索良久,无果,请问该问题解决了吗?还是被丢弃了?感谢先。
见 https://www.cnblogs.com/eshizhan/archive/2012/10/07/2713680.html。 makecert.exe参数必须加上-pe
(将所生成的私钥标记为可导出。这样可将私钥包括在证书中。)