xamarin uwp数字证书公钥私钥

时间:2021-05-08 22:18:17

对于数字证书存储导入到电脑中,采用如下方式:

 /// <summary>
/// 导入证书
/// </summary>
/// <param name="rawData">证书字节数组</param>
/// <param name="keyStorePassWord">keyStore密码</param>
/// <param name="keyPassWord">证书密码</param>
/// <param name="certificateType">证书类型</param>
/// <returns>true表示导入成功 false表示导入失败</returns>
public bool ImportCertificate(byte[] rawData, string keyStorePassWord, string keyPassWord, string mailAccount, CertificateType certificateType = CertificateType.Pkcs12)
{
try
{
bool result = false;
if (certificateType == CertificateType.Pkcs12)
{
using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadWrite);
X509Certificate2 certificate = new X509Certificate2(rawData, keyPassWord, X509KeyStorageFlags.Exportable);
//X509Certificate2 certificate = new X509Certificate2(rawData, keyPassWord, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
//获取公钥
var cerPublicKey = certificate.Export(X509ContentType.Cert);
result =true; store.Add(certificate);
}
return result;
}
else
{
X509Certificate2 certificate = new X509Certificate2(rawData, keyPassWord);
result =true;
return result;
} }
catch (Exception ex)
{
DAL.ErrorLog.AddErrorLogs("证书保存失败!" + ex.Message);
return false;
}
}

对应的获取相应的数字证书的私钥:

 /// <summary>
/// 获取P12格式的证书
/// </summary>
/// <param name="serialNumber">证书序列号</param>
/// <param name="keyStorePassWord">keyStore密码</param>
/// <param name="keyPassWord">证书密码</param>
/// <param name="hasCertificate">证书类型</param>
/// <returns>如果返回null 表示没有获取到证书</returns>
public byte[] GetCertificate(string serialNumber, string keyStorePassWord, string keyPassWord)
{
byte[] result = null;
try
{
using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadWrite);
foreach (var item in store.Certificates)
{
if (item.SerialNumber == serialNumber)
{
result = item.Export(X509ContentType.Pfx, keyPassWord);
//result = item.RawData;
break;
}
}
}
}
catch (Exception ex)
{
string errorMessage = ex.Message;
result = null;
}
return result;
}

上面的result = item.Export(X509ContentType.Pfx, keyPassWord);方法需注意:当参数为两个时,及你把证书密码放上去的时候获取的是私钥,当为如下时获取的是公钥:result = item.Export(X509ContentType.Pfx);