本文整理汇总了C#中System.Security.Cryptography.X509Certificates.X509Certificate2.GetKeyAlgorithm方法的典型用法代码示例。如果您正苦于以下问题:C# X509Certificate2.GetKeyAlgorithm方法的具体用法?C# X509Certificate2.GetKeyAlgorithm怎么用?C# X509Certificate2.GetKeyAlgorithm使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.X509Certificates.X509Certificate2
的用法示例。
在下文中一共展示了X509Certificate2.GetKeyAlgorithm方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Certificate
public Certificate(X509Certificate2 cert)
{
if (cert == null)
{
throw new ArgumentNullException("cert");
}
certificate = cert;
KeyAlgorithm = certificate.GetKeyAlgorithm();
HasPrivateKey = certificate.HasPrivateKey;
SerialNumber = certificate.SerialNumber;
Thumbprint = certificate.Thumbprint;
FriendlyName = certificate.FriendlyName;// !string.IsNullOrWhiteSpace(_certificate.FriendlyName) ? _certificate.FriendlyName : string.Format("[{0}]\t[{1}]", _certificate.Issuer, _certificate.Subject);
Subject = certificate.Subject;
EffectiveDate = certificate.NotBefore;
ExpirationDate = certificate.NotAfter;
Format = certificate.GetFormat();
Issuer = certificate.Issuer;
SignatureAlgorithm = certificate.SignatureAlgorithm.FriendlyName;
Version = certificate.Version.ToString();
Extentions = new List<string>();
foreach (X509Extension ext in certificate.Extensions)
{
Extentions.Add(ext.Format(false));
}
}
示例2: CertTest_Test
public MFTestResults CertTest_Test()
{
bool bRes = true;
try
{
//string filename = "microsoft.cer";
using (Session session = new Session("", MechanismType.RSA_PKCS))
{
X509Certificate2 cert = new X509Certificate2(session, Properties.Resources.GetBytes(Properties.Resources.BinaryResources.microsoft));
Log.Comment(cert.Subject);
Log.Comment(cert.Issuer);
byte[] serialNumber = new byte[cert.GetSerialNumber().Length];
Array.Copy(cert.GetSerialNumber(), 0,
serialNumber, 0,
cert.GetSerialNumber().Length);
PrintByteArray(serialNumber);
Log.Comment(cert.GetKeyAlgorithm());
byte[] publicKey = new byte[cert.GetPublicKey().Length];
Array.Copy(cert.GetPublicKey(), 0,
publicKey, 0,
cert.GetPublicKey().Length);
PrintByteArray(publicKey);
Log.Comment(cert.GetEffectiveDateString());
Log.Comment(cert.GetExpirationDateString());
}
}
catch
{
bRes = false;
}
return bRes ? MFTestResults.Pass : MFTestResults.Fail;
}
示例3: Assinar
/// <summary>
/// Gera assinatura Digital do XML
/// </summary>
/// <param name="XMLString"></param>
/// <param name="RefUri"></param>
/// <param name="X509Cert"></param>
/// <returns></returns>
public int Assinar(string XMLString, string RefUri, X509Certificate2 X509Cert)
{
int resultado = 0;
msgResultado = "Assinatura realizada com sucesso";
try
{
// certificado para ser utilizado na assinatura
//
string _xnome = "";
bool bX509Cert = false;
if (X509Cert != null)
{
_xnome = X509Cert.Subject.ToString();
}
else
{
bX509Cert = true;
}
X509Certificate2 _X509Cert = new X509Certificate2();
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
X509Certificate2Collection collection1 = (X509Certificate2Collection)collection.Find(X509FindType.FindBySubjectDistinguishedName, (object)_xnome, true);
//if (collection1.Count == 0)
if (bX509Cert)
{
resultado = 2;
msgResultado = "Problemas no certificado digital";
}
else
{
// certificado ok
//_X509Cert = collection1[0];
_X509Cert = X509Cert;
string x;
x = _X509Cert.GetKeyAlgorithm().ToString();
// Create a new XML document.
XmlDocument doc = new XmlDocument();
// Format the document to ignore white spaces.
doc.PreserveWhitespace = false;
// Load the passed XML file using it's name.
try
{
doc.LoadXml(XMLString);
// Verifica se a tag a ser assinada existe é única
int qtdeRefUri = doc.GetElementsByTagName(RefUri).Count;
if (qtdeRefUri == 0)
{
// a URI indicada não existe
resultado = 4;
msgResultado = "A tag de assinatura " + RefUri.Trim() + " inexiste";
}
// Exsiste mais de uma tag a ser assinada
else
{
if (qtdeRefUri > 1)
{
// existe mais de uma URI indicada
resultado = 5;
msgResultado = "A tag de assinatura " + RefUri.Trim() + " não é unica";
}
else
{
try
{
//Claudinei - o.s. 23615 - 10/08/2009
//for (int i = 0; i < qtdeRefUri; i++)
{
//Fim - Claudinei - o.s. 23615 - 10/08/2009
// Create a SignedXml object.
SignedXml signedXml = new SignedXml(doc);
//sTipoAssinatura = _X509Cert.PrivateKey.KeySize.ToString();
// Add the key to the SignedXml document
signedXml.SigningKey = _X509Cert.PrivateKey;
// Create a reference to be signed
Reference reference = new Reference();
// pega o uri que deve ser assinada
//.........这里部分代码省略.........
示例4: TestCertMangling
public void TestCertMangling()
{
string certString = @"MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx
EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0
WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK
jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze
qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI
zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr
PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh
3yILeYQzllt/g0rKVRk=";
X509Certificate2 c = new X509Certificate2();
c.Import(Convert.FromBase64String(certString));
Assert.AreEqual("[email protected], CN=www.google.com, O=\"Google, Inc\", L=Mountain View, S=California, C=US", c.Issuer);
//Assert.AreEqual("CN=Microsoft Corporate Root CA, O=Microsoft Corporation", c.Subject);
Assert.AreEqual("X509", c.GetFormat());
Assert.AreEqual("1.2.840.10045.2.1", c.GetKeyAlgorithm());
Assert.AreEqual("06052B81040022", c.GetKeyAlgorithmParametersString());
Assert.AreEqual("ECC", c.PublicKey.Oid.FriendlyName);
ECDiffieHellmanPublicKey certKey = CryptoUtils.ImportEccPublicKeyFromCertificate(c);
//Console.WriteLine(certKey.ToXmlString());
// https://blogs.msdn.microsoft.com/shawnfa/2007/01/22/elliptic-curve-diffie-hellman/
// http://stackoverflow.com/questions/11266711/using-cngkey-to-generate-rsa-key-pair-in-pem-dkim-compatible-using-c-simi
{
string input = "eyJhbGciOiJFUzM4NCIsIng1dSI6Ik1IWXdFQVlIS29aSXpqMENBUVlGSzRFRUFDSURZZ0FFN25uWnBDZnhtQ3JTd0RkQnY3ZUJYWE10S2hyb3hPcmlFcjNobU1PSkF1dy9acFFYajFLNUdHdEhTNENwRk50dGQxSllBS1lvSnhZZ2F5a3BpZTBFeUF2M3FpSzZ1dElIMnFuT0F0M1ZOclFZWGZJWkpTL1ZSZTNJbDhQZ3U5Q0IifQo.eyJleHAiOjE0NjQ5ODM4NDUsImV4dHJhRGF0YSI6eyJkaXNwbGF5TmFtZSI6Imd1cnVueCIsImlkZW50aXR5IjoiYWY2ZjdjNWUtZmNlYS0zZTQzLWJmM2EtZTAwNWU0MDBlNTc4In0sImlkZW50aXR5UHVibGljS2V5IjoiTUhZd0VBWUhLb1pJemowQ0FRWUZLNEVFQUNJRFlnQUU3bm5acENmeG1DclN3RGRCdjdlQlhYTXRLaHJveE9yaUVyM2htTU9KQXV3L1pwUVhqMUs1R0d0SFM0Q3BGTnR0ZDFKWUFLWW9KeFlnYXlrcGllMEV5QXYzcWlLNnV0SUgycW5PQXQzVk5yUVlYZklaSlMvVlJlM0lsOFBndTlDQiIsIm5iZiI6MTQ2NDk4Mzg0NH0K.4OrvYYbX09iwOkz-7_N_5yEejuATcUogEbe69fB-kr7r6sH_qSu6bxp9L64SEgABb0rU7tyYCLVnaCSQjd9Dvb34WI9EducgOPJ92qHspcpXr7j716LDfhZE31ksMtWQ";
ECDiffieHellmanPublicKey rootKey = CryptoUtils.CreateEcDiffieHellmanPublicKey("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8ELkixyLcwlZryUQcu1TvPOmI2B7vX83ndnWRUaXm74wFfa5f/lwQNTfrLVHa2PmenpGI6JhIMUJaWZrjmMj90NoKNFSNBuKdm8rYiXsfaz3K36x/1U26HpG0ZxK/V1V");
Console.WriteLine($"Root Public Key:\n{rootKey.ToXmlString()}");
CngKey key = CngKey.Import(rootKey.ToByteArray(), CngKeyBlobFormat.EccPublicBlob);
Console.WriteLine("Key family: " + key.AlgorithmGroup);
// "identityPublicKey": "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE7nnZpCfxmCrSwDdBv7eBXXMtKhroxOriEr3hmMOJAuw/ZpQXj1K5GGtHS4CpFNttd1JYAKYoJxYgaykpie0EyAv3qiK6utIH2qnOAt3VNrQYXfIZJS/VRe3Il8Pgu9CB",
var newKey = CryptoUtils.ImportECDsaCngKeyFromString("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE7nnZpCfxmCrSwDdBv7eBXXMtKhroxOriEr3hmMOJAuw/ZpQXj1K5GGtHS4CpFNttd1JYAKYoJxYgaykpie0EyAv3qiK6utIH2qnOAt3VNrQYXfIZJS/VRe3Il8Pgu9CB");
string decoded = JWT.Decode(input, newKey);
//Assert.AreEqual("", decoded);
//ECDsaCng t = new ECDsaCng();
//t.HashAlgorithm = CngAlgorithm.ECDiffieHellmanP384;
//t.KeySize = 384;
//byte[] test = t.Key.Export(CngKeyBlobFormat.EccPublicBlob);
//Assert.AreEqual(test, newKey);
//string decoded = JWT.Decode(input, t.Key);
}
// Private key (in reality this is not necessary since we will generate it)
AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(Base64Url.Decode("MB8CAQAwEAYHKoZIzj0CAQYFK4EEACIECDAGAgEBBAEB"));
PrivateKeyInfo privKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey);
byte[] derKey = privKeyInfo.GetDerEncoded();
CngKey privCngKey = CngKey.Import(derKey, CngKeyBlobFormat.Pkcs8PrivateBlob);
Console.WriteLine(privKeyInfo.PrivateKeyAlgorithm.Algorithm);
Console.WriteLine(privCngKey.Algorithm.Algorithm);
// Public key
ECDiffieHellmanPublicKey clientKey = CryptoUtils.CreateEcDiffieHellmanPublicKey("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEDEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyodFH+wO0dEr4GM1WoaWog8xsYQ6mQJAC0eVpBM96spUB1eMN56+BwlJ4H3Qx4TAvAs");
// EC key to generate shared secret
ECDiffieHellmanCng ecKey = new ECDiffieHellmanCng(privCngKey);
ecKey.HashAlgorithm = CngAlgorithm.Sha256;
ecKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
ecKey.SecretPrepend = new byte[128]; // Server token
//ecKey.SecretPrepend = new byte[0]; // Server token
Console.WriteLine(ecKey.HashAlgorithm);
Console.WriteLine(ecKey.KeyExchangeAlgorithm);
byte[] secret = ecKey.DeriveKeyMaterial(clientKey);
Console.WriteLine(Package.HexDump(secret));
Console.WriteLine(Package.HexDump(Base64Url.Decode("ZOBpyzki/M8UZv5tiBih048eYOBVPkQE3r5Fl0gmUP4=")));
Console.WriteLine(Package.HexDump(Base64Url.Decode("DEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyod")));
//Console.WriteLine(Package.HexDump(Base64Url.Decode("DEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyod")));
}
示例5: AssignSession
public override void AssignSession(Session oS)
{
base.AssignSession(oS);
var dataItems = new List<DataItem>();
dataItems.Add(new DataItem("Is Https", oS.isHTTPS));
if (oS.isHTTPS && oS.oFlags.ContainsKey(CertificateStorage.CeritificateRequestPropertyName))
{
try
{
var thumbprint = oS.oFlags[CertificateStorage.CeritificateRequestPropertyName];
FiddlerApplication.Log.LogString(thumbprint);
if (CertificateStorage.Certificates.ContainsKey(thumbprint))
{
var certificate = CertificateStorage.Certificates[thumbprint];
var cert = new X509Certificate2(certificate);
_informationTab.Certificate = cert;
//most commonly desired information up top.
dataItems.InsertRange(0, new[] { new DataItem("FriendlyName", cert.FriendlyName),
new DataItem("Subject", cert.Subject),
new DataItem("Issuer", cert.Issuer),
new DataItem("Effective Date", cert.GetEffectiveDateString()),
new DataItem("Expiration Date", cert.GetExpirationDateString()),
new DataItem("Thumbprint", cert.Thumbprint),
new DataItem("------------------------", "------------------------")});
//alphabatized data properties below
dataItems.Add(new DataItem("Archived", cert.Archived));
dataItems.Add(new DataItem("FriendlyName", cert.FriendlyName));
dataItems.Add(new DataItem("Certficate Hash", cert.GetCertHashString()));
dataItems.Add(new DataItem("Certificate Format", cert.GetFormat()));
dataItems.Add(new DataItem("Effective Date", cert.GetEffectiveDateString()));
dataItems.Add(new DataItem("Expiration Date", cert.GetExpirationDateString()));
dataItems.Add(new DataItem("Full Issuer Name", cert.IssuerName.Format(true)));
dataItems.Add(new DataItem("Full Subject Name", cert.SubjectName.Format(true)));
dataItems.Add(new DataItem("Has Private Key", cert.HasPrivateKey));
dataItems.Add(new DataItem("Issuer", cert.Issuer));
dataItems.Add(new DataItem("Key Algorithm", cert.GetKeyAlgorithm()));
dataItems.Add(new DataItem("Key Algorithm Parameters", cert.GetKeyAlgorithmParametersString()));
dataItems.Add(new DataItem("Public Key", cert.GetPublicKeyString()));
dataItems.Add(new DataItem("Raw Certificate Data", cert.GetRawCertDataString()));
dataItems.Add(new DataItem("SerialNumberString", cert.GetSerialNumberString()));
dataItems.Add(new DataItem("Subject", cert.Subject));
dataItems.Add(new DataItem("Thumbprint", cert.Thumbprint));
dataItems.Add(new DataItem("Version", cert.Version));
dataItems.Add(new DataItem("------------------------", "------------------------"));
dataItems.Add(new DataItem("Extensions", string.Empty));
dataItems.Add(new DataItem("------------------------", "------------------------"));
foreach (var extension in cert.Extensions)
{
dataItems.Add(new DataItem(extension.Oid.FriendlyName, extension.Format(true)));
}
}
}
catch (Exception ex)
{
FiddlerApplication.Log.LogString("Unexpected error loading the assigned certificate." + ex.Message);
}
}
_informationTab.DataGrid.DataSource = dataItems;
}
示例6: SignXml
public string SignXml(string xmlString, string signTag, X509Certificate2 certificate)
{
try
{
// checking if there is a certified used on xml sign
string _xnome = "";
if (certificate != null)
_xnome = certificate.Subject.ToString();
string x;
x = certificate.GetKeyAlgorithm().ToString();
// Create a new XML document.
XmlDocument doc = new XmlDocument();
// Format the document to ignore white spaces.
doc.PreserveWhitespace = false;
// Load the passed XML file using it’s name.
try
{
doc.LoadXml(xmlString);
// cheching the element will be sign
int tagQuantity = doc.GetElementsByTagName(signTag).Count;
if (tagQuantity == 0)
{
return "A tag de assinatura " + signTag.Trim() + " não existe";
}
else
{
if (tagQuantity > 1)
{
return "A tag de assinatura " + signTag.Trim() + " não é unica";
}
else
{
try
{
// Create a SignedXml object.
SignedXml signedXml = new SignedXml(doc);
// Add the key to the SignedXml document
signedXml.SigningKey = certificate.PrivateKey;
// Create a reference to be signed
Reference reference = new Reference();
XmlAttributeCollection tag = doc.GetElementsByTagName(signTag).Item(0).Attributes;
foreach (XmlAttribute xmlAttr in tag)
{
if (xmlAttr.Name == "Id")
reference.Uri = "#" + xmlAttr.InnerText;
}
// Felipe Hosomi - se reference.Uri == null, dá erro na assinatura
if (reference.Uri == null)
{
reference.Uri = String.Empty;
}
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
reference.AddTransform(c14);
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
// Create a new KeyInfo object
KeyInfo keyInfo = new KeyInfo();
// Load the certificate into a KeyInfoX509Data object
// and add it to the KeyInfo object.
keyInfo.AddClause(new KeyInfoX509Data(certificate));
// Add the KeyInfo object to the SignedXml object.
signedXml.KeyInfo = keyInfo;
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
// save element on XML
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
XmlDocument XMLDoc = new XmlDocument();
XMLDoc.PreserveWhitespace = false;
XMLDoc = doc;
// XML document already signed
return XMLDoc.OuterXml;
}
catch (Exception e)
{
return "Erro ao assinar o documento - " + e.Message;
}
//.........这里部分代码省略.........
示例7: RegisterServiceOID
// Registers the service OID for the given product.
private void RegisterServiceOID(Product product)
{
List<Product> productsUsingThisOID;
X509Certificate2 certificate;
string certificatePath;
string keyAlgorithm;
// If the service is already registered, don't need to do anything
if ((object)product.ServiceOID == null)
{
// Get the path to the certificate used to obtain the OID for this fix
certificatePath = Path.Combine(product.InstallPath, product.Name + ".cer");
if (File.Exists(certificatePath))
{
StatusTextBox.AppendText(string.Format("Registering service OID for {0}... ", product.Name));
// Get the key algorithm of the certificate,
// which is the OID used by the service
certificate = new X509Certificate2(certificatePath);
keyAlgorithm = certificate.GetKeyAlgorithm();
// Determine which other products are sharing this service OID
productsUsingThisOID = m_products
.Where(p => p.ServiceOID == keyAlgorithm)
.ToList();
// Set service OID to the key algorithm of the certificate
product.ServiceOID = keyAlgorithm;
// Store the OID of that certificate in case we need to unregister it later
using (RegistryKey productKey = Registry.LocalMachine.CreateSubKey(string.Format(@"Software\Grid Protection Alliance\{0}", product.Name)))
{
if ((object)productKey != null)
productKey.SetValue("ServiceOID", keyAlgorithm);
}
if (productsUsingThisOID.Count == 0)
{
RegisterOID(keyAlgorithm);
AppendStatusMessage("Done.");
}
else if (productsUsingThisOID.Count == 1)
{
AppendStatusMessage(string.Format("Service OID already registered for {0}.", productsUsingThisOID[0].Name));
}
else
{
AppendStatusMessage(string.Format("Service OID already registered for {0} other products.", productsUsingThisOID.Count));
}
}
}
}