我正在數字簽署xml文檔。這裏是我的代碼:如何在簽署文檔時檢查DSC(USB令牌)是否已連接?
private void mbSign_Click_1(object sender, EventArgs e)
{
try
{
CadesSignature cs = new CadesSignature(FStrDSCSNo);
cs.DigitalSignatureCertificate = DigitalCertificate.LoadCertificate(false, string.Empty, "Select Certificate", "Select the certificate for digital signature");
RSACryptoServiceProvider rsaEncryptor = (RSACryptoServiceProvider)cs.DigitalSignatureCertificate.PrivateKey;
L_ADSC_ValidTo = cs.DigitalSignatureCertificate.NotAfter.ToShortDateString();
if (DateTime.Now <= DateTime.ParseExact(L_ADSC_ValidTo, "dd/MM/yyyy", null))
{
FObjLog.WriteToLog("Valid DSC");
L_ADSC_CertStatus = "A";
// Sign the XML document.
//DataTable dt_SignXMlAndSignaute = new DataTable();
SignXml(rsaEncryptor);
}
}
catch (CryptographicException)
{
MessageBox.Show("Invalid DSC Selection.Please Choose Correct DSC");
FObjLog.WriteToLog("Invalid DSC Selection.Please Choose Correct DSC");
}
catch (NullReferenceException)
{
MessageBox.Show("Please Attach DSC");
FObjLog.WriteToLog("Please Attach DSC");
}
}
public void SignXml(RSA Key)
{
XmlDocument LXMLDoc = new XmlDocument();
if (File.Exists(LXMLPath))
{
LXMLDoc.Load(LXMLPath);
}
if (LXMLDoc == null)
throw new ArgumentException("LXMLDoc");
if (Key == null)
throw new ArgumentException("Key");
// Create a SignedXml object.
SignedXml signedXml = new SignedXml(LXMLDoc);
// Add the key to the SignedXml document.
signedXml.SigningKey = Key;
// Create a reference to be signed.
Reference reference = new Reference();
//reference.Uri = txtfilepath.Text;
reference.Uri = "";
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env); // calculating Digest value
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
// Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(new RSAKeyValue((RSA)Key));
signedXml.KeyInfo = keyInfo;
signedXml.ComputeSignature();
string FullSignatureValue = "";
string SignatureValue = "";
XmlElement xmlDigitalSignature = signedXml.GetXml();
FullSignatureValue = xmlDigitalSignature.InnerText;
string[] Sign = FullSignatureValue.Split(new char[] { '=' }, 2);
SignatureValue = Sign[1].ToString();
signedXml = new SignedXml(LXMLDoc);
LXMLDoc.DocumentElement.AppendChild(LXMLDoc.ImportNode(xmlDigitalSignature, true));
}
在這裏我能簽署文件,但我無法檢查是否在簽署時連接USB令牌。這裏發生的情況是,即使沒有連接USB令牌,也會彈出證書供選擇,因爲證書在本地可用。當您從Internet Explorer中刪除所有證書並嘗試使用未連接的USB令牌進行簽名時,它會要求連接DSC卡(USB令牌)。我只想在連接DSC(USB令牌)時簽署文件。我如何確保在簽名時連接USB?