Thứ Ba, 29 tháng 7, 2008

Certificates Signiture

string url = string.Empty;
rsa = null;
certificate = null;
RSACryptoServiceProvider.UseMachineKeyStore = true;

CspParameters csp = new CspParameters();
csp.Flags = CspProviderFlags.UseMachineKeyStore;
ICertificate2 selectedCert = null;


//open the ceritificate store
Store st = new Store();

st.Open(CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE,
"My",
CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED);
//search for the certificate with the digital signature
enabled
foreach (ICertificate2 currCert in st.Certificates)
{

if (currCert.HasPrivateKey())
{
selectedCert = currCert;
break;
}
}
//check if the certificate was found or not
if (selectedCert == null || selectedCert.HasPrivateKey()
== false ||

selectedCert.PublicKey().Algorithm.FriendlyName != "RSA")
{
StringBuilder sb = new StringBuilder();
sb.Append("Can't find a vaild certificate!\n\n");
sb.Append("Valid Certificate Authorities are :\n");
System.Collections.IEnumerator myEnum =
issuerlist.GetEnumerator();
while (myEnum.MoveNext())
sb.Append(myEnum.Current).Append("\n");
throw new Exception(sb.ToString());
}

certificate = selectedCert;

//create cerificate provider
csp.KeyContainerName =
selectedCert.PrivateKey.ContainerName;
csp.ProviderName = selectedCert.PrivateKey.ProviderName;
csp.ProviderType =
Convert.ToInt32(selectedCert.PrivateKey.ProviderType);

//the certificate key number by the key specifications
switch (selectedCert.PrivateKey.KeySpec)
{
case CAPICOM_KEY_SPEC.CAPICOM_KEY_SPEC_KEYEXCHANGE:
csp.KeyNumber = 1;
break;

case CAPICOM_KEY_SPEC.CAPICOM_KEY_SPEC_SIGNATURE:
csp.KeyNumber = 2;
break;
}

//for machine keys use the local store of the machine
if (selectedCert.PrivateKey.IsMachineKeyset())
{
csp.Flags = CspProviderFlags.UseMachineKeyStore;
}
//create rsa cryptogragic provider based on the CSP
try
{
rsa = new RSACryptoServiceProvider(csp);//Here i get
the Exception
}
catch
{ }

Không có nhận xét nào: