當前位置: 首頁>>代碼示例>>C#>>正文


C# X509Certificate.GetEncoded方法代碼示例

本文整理匯總了C#中Org.BouncyCastle.X509.X509Certificate.GetEncoded方法的典型用法代碼示例。如果您正苦於以下問題:C# X509Certificate.GetEncoded方法的具體用法?C# X509Certificate.GetEncoded怎麽用?C# X509Certificate.GetEncoded使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在Org.BouncyCastle.X509.X509Certificate的用法示例。


在下文中一共展示了X509Certificate.GetEncoded方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: SecureMimeDigitalCertificate

        internal SecureMimeDigitalCertificate(X509Certificate certificate)
        {
            Certificate = certificate;

            var pubkey = certificate.GetPublicKey ();
            if (pubkey is DsaKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.Dsa;
            else if (pubkey is RsaKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.RsaGeneral;
            else if (pubkey is ElGamalKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.ElGamalGeneral;
            else if (pubkey is ECKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.EllipticCurve;
            else if (pubkey is DHKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.DiffieHellman;

            var encoded = certificate.GetEncoded ();
            var fingerprint = new StringBuilder ();
            var sha1 = new Sha1Digest ();
            var data = new byte[20];

            sha1.BlockUpdate (encoded, 0, encoded.Length);
            sha1.DoFinal (data, 0);

            for (int i = 0; i < data.Length; i++)
                fingerprint.Append (data[i].ToString ("X2"));

            Fingerprint = fingerprint.ToString ();
        }
開發者ID:princeoffoods,項目名稱:MimeKit,代碼行數:29,代碼來源:SecureMimeDigitalCertificate.cs

示例2: TimeStampTokenGenerator

		/**
		 * create with a signer with extra signed/unsigned attributes.
		 */
		public TimeStampTokenGenerator(
			AsymmetricKeyParameter	key,
			X509Certificate			cert,
			string					digestOID,
			string					tsaPolicyOID,
			Asn1.Cms.AttributeTable	signedAttr,
			Asn1.Cms.AttributeTable	unsignedAttr)
		{
			this.key = key;
			this.cert = cert;
			this.digestOID = digestOID;
			this.tsaPolicyOID = tsaPolicyOID;
			this.unsignedAttr = unsignedAttr;

			TspUtil.ValidateCertificate(cert);

			//
			// Add the ESSCertID attribute
			//
			IDictionary signedAttrs;
			if (signedAttr != null)
			{
				signedAttrs = signedAttr.ToDictionary();
			}
			else
			{
				signedAttrs = Platform.CreateHashtable();
			}

			try
			{
				byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());

				EssCertID essCertid = new EssCertID(hash);

				Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
					PkcsObjectIdentifiers.IdAASigningCertificate,
					new DerSet(new SigningCertificate(essCertid)));

				signedAttrs[attr.AttrType] = attr;
			}
			catch (CertificateEncodingException e)
			{
				throw new TspException("Exception processing certificate.", e);
			}
			catch (SecurityUtilityException e)
			{
				throw new TspException("Can't find a SHA-1 implementation.", e);
			}

			this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
		}
開發者ID:MBrekhof,項目名稱:pleiobox-clients,代碼行數:55,代碼來源:TimeStampTokenGenerator.cs

示例3: Pair

	// Send either ValidatePair or Pair (depending on Action)
	// request to iPhone and return true upon success or false otherwise.
	private bool Pair(PairAction Action)
	{
		#region Preparation of certificates
		X509V3CertificateGenerator DeviceCG = new X509V3CertificateGenerator();
		DeviceCG.SetPublicKey(DevicePublicKey);
		DeviceCG.SetSerialNumber(Org.BouncyCastle.Math.BigInteger.Zero);
		DeviceCG.SetNotBefore(iPhone.RootCertificate.NotBefore);
		DeviceCG.SetNotAfter(iPhone.RootCertificate.NotAfter);
		DeviceCG.SetSignatureAlgorithm("SHA1WithRSAEncryption");
		DeviceCG.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.BasicConstraints, true, new Org.BouncyCastle.Asn1.X509.BasicConstraints(false));
		DeviceCertificate = DeviceCG.Generate(iPhone.RootKey.Private);

		// The \n at the end of these certificates is crucial; hung me up for a while.
		string sDeviceCertificate = "-----BEGIN CERTIFICATE-----\n"
									+ Convert.ToBase64String(DeviceCertificate.GetEncoded())
									+ "\n-----END CERTIFICATE-----\n";
		byte[] bDeviceCertificate = System.Text.Encoding.UTF8.GetBytes(sDeviceCertificate);
		string sHostCertificate = "-----BEGIN CERTIFICATE-----\n"
									+ Convert.ToBase64String(iPhone.HostCertificate.GetEncoded())
									+ "\n-----END CERTIFICATE-----\n";
		byte[] bHostCertificate = System.Text.Encoding.UTF8.GetBytes(sHostCertificate);
		string sRootCertificate = "-----BEGIN CERTIFICATE-----\n"
									+ Convert.ToBase64String(iPhone.RootCertificate.GetEncoded())
									+ "\n-----END CERTIFICATE-----\n";
		byte[] bRootCertificate = System.Text.Encoding.UTF8.GetBytes(sRootCertificate);
		#endregion

		MemoryStream MS = new MemoryStream();
		XmlWriter XTW = XmlWriter.Create(MS, XWS);
		XTW.WriteStartDocument();
		XTW.WriteDocType("plist", sApplePubID, sAppleSysID, null);
		XTW.WriteStartElement("plist");
		XTW.WriteAttributeString("version", "1.0");
		XTW.WriteStartElement("dict");

		XTW.WriteElementString("key", "PairRecord");
		XTW.WriteStartElement("dict");

		XTW.WriteElementString("key", "DeviceCertificate");
		XTW.WriteStartElement("data");
		XTW.WriteBase64(bDeviceCertificate, 0, bDeviceCertificate.Length);
		XTW.WriteEndElement(); // DeviceCertificate data

		XTW.WriteElementString("key", "HostCertificate");
		XTW.WriteStartElement("data");
		XTW.WriteBase64(bHostCertificate, 0, bHostCertificate.Length);
		XTW.WriteEndElement(); // HostCertificate data

		XTW.WriteElementString("key", "HostID");
		XTW.WriteElementString("string", iPhone.sHostID);
		XTW.WriteElementString("key", "RootCertificate");
		XTW.WriteStartElement("data");
		XTW.WriteBase64(bRootCertificate, 0, bRootCertificate.Length);
		XTW.WriteEndElement(); // RootCertificate data

		XTW.WriteEndElement(); // inner dict

		XTW.WriteElementString("key", "Request");
		switch (Action)
		{
			case PairAction.Pair:
				XTW.WriteElementString("string", "Pair");
				break;

			case PairAction.ValidatePair:
				XTW.WriteElementString("string", "ValidatePair");
				break;

			case PairAction.Unpair:
				XTW.WriteElementString("string", "Unpair");
				break;
		}

		XTW.WriteEndElement(); // outer dict
		XTW.WriteEndElement(); // plist
		XTW.WriteEndDocument();
		XTW.Flush();

		byte[] bXMLData = MS.GetBuffer();
		XTW.Close(); // Closes MS, too.

		PListSend(bXMLData);
		bXMLData = PListReceive();

		if (!CheckXMLForSuccess(bXMLData))
			return false;

		// Have to validate after pairing for "trusted host status", apparently.
		if (Action == PairAction.Pair)
			return Pair(PairAction.ValidatePair);

		return true;
	}
開發者ID:jakubl,項目名稱:jphonewin,代碼行數:95,代碼來源:iphone.cs

示例4: ToX509Certificate

		public static SystemX509.X509Certificate ToX509Certificate(
			X509Certificate x509Cert)
		{
			return new SystemX509.X509Certificate(x509Cert.GetEncoded());
		}
開發者ID:nicecai,項目名稱:iTextSharp-4.1.6,代碼行數:5,代碼來源:DotNetUtilities.cs

示例5: ToAsn1Object

		/**
		 * Return a DERObject containing the encoded certificate.
		 *
		 * @param cert the X509Certificate object to be encoded
		 *
		 * @return the DERObject
		 **/
		private Asn1Object ToAsn1Object(
			X509Certificate cert)
		{
			try
			{
				return Asn1Object.FromByteArray(cert.GetEncoded());
			}
			catch (Exception e)
			{
				throw new CertificateEncodingException("Exception while encoding certificate", e);
			}
		}
開發者ID:ktw,項目名稱:OutlookPrivacyPlugin,代碼行數:19,代碼來源:PkixCertPath.cs

示例6: Match

		public bool Match(
//			Certificate cert)
			X509Certificate x509Cert)
		{
//			if (!(cert is X509Certificate))
//			{
//				return false;
//			}
//
//			X509Certificate x509Cert = (X509Certificate)cert;

			try
			{
				if (holder.BaseCertificateID != null)
				{
					return holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber)
						&& MatchesDN(PrincipalUtilities.GetIssuerX509Principal(x509Cert), holder.BaseCertificateID.Issuer);
				}

				if (holder.EntityName != null)
				{
					if (MatchesDN(PrincipalUtilities.GetSubjectX509Principal(x509Cert), holder.EntityName))
					{
						return true;
					}
				}

				if (holder.ObjectDigestInfo != null)
				{
					IDigest md = null;
					try
					{
						md = DigestUtilities.GetDigest(DigestAlgorithm);
					}
					catch (Exception)
					{
						return false;
					}

					switch (DigestedObjectType)
					{
						case ObjectDigestInfo.PublicKey:
						{
							// TODO: DSA Dss-parms

							//byte[] b = x509Cert.GetPublicKey().getEncoded();
							// TODO Is this the right way to encode?
							byte[] b = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
								x509Cert.GetPublicKey()).GetEncoded();
							md.BlockUpdate(b, 0, b.Length);
							break;
						}

						case ObjectDigestInfo.PublicKeyCert:
						{
							byte[] b = x509Cert.GetEncoded();
							md.BlockUpdate(b, 0, b.Length);
							break;
						}

						// TODO Default handler?
					}

					// TODO Shouldn't this be the other way around?
					if (!Arrays.AreEqual(DigestUtilities.DoFinal(md), GetObjectDigest()))
					{
						return false;
					}
				}
			}
			catch (CertificateEncodingException)
			{
				return false;
			}

			return false;
		}
開發者ID:htlp,項目名稱:itextsharp,代碼行數:77,代碼來源:AttributeCertificateHolder.cs

示例7: Contains

        public unsafe bool Contains(X509Certificate certificate)
        {
            if (certificate == null)
                throw new ArgumentNullException ("certificate");

            if (disposed)
                throw new ObjectDisposedException ("SecKeychain");

            // Note: we don't have to use an alias attribute, it's just that it might be faster to use it (fewer certificates we have to compare raw data for)
            byte[] alias = Encoding.UTF8.GetBytes (certificate.GetCommonName ());
            IntPtr searchRef, itemRef;
            bool found = false;
            byte[] certData;
            OSStatus status;

            fixed (byte* aliasPtr = alias) {
                SecKeychainAttribute* attrs = stackalloc SecKeychainAttribute [1];
                int n = 0;

                if (alias != null)
                    attrs[n++] = new SecKeychainAttribute (SecItemAttr.Alias, (uint) alias.Length, (IntPtr) aliasPtr);

                SecKeychainAttributeList attrList = new SecKeychainAttributeList (n, (IntPtr) attrs);

                status = SecKeychainSearchCreateFromAttributes (Handle, SecItemClass.Certificate, &attrList, out searchRef);
                if (status != OSStatus.Ok)
                    throw new Exception ("Could not enumerate certificates from the keychain. Error:\n" + GetError (status));

                certData = certificate.GetEncoded ();

                while (!found && SecKeychainSearchCopyNext (searchRef, out itemRef) == OSStatus.Ok) {
                    SecItemClass itemClass = 0;
                    IntPtr data = IntPtr.Zero;
                    uint length = 0;

                    status = SecKeychainItemCopyContent (itemRef, ref itemClass, IntPtr.Zero, ref length, ref data);
                    if (status == OSStatus.Ok) {
                        if (certData.Length == (int) length) {
                            byte[] rawData = new byte[(int) length];

                            Marshal.Copy (data, rawData, 0, (int) length);

                            found = true;
                            for (int i = 0; i < rawData.Length; i++) {
                                if (rawData[i] != certData[i]) {
                                    found = false;
                                    break;
                                }
                            }
                        }

                        SecKeychainItemFreeContent (IntPtr.Zero, data);
                    }

                    CFRelease (itemRef);
                }

                CFRelease (searchRef);
            }

            return found;
        }
開發者ID:princeoffoods,項目名稱:MimeKit,代碼行數:62,代碼來源:SecKeychain.cs

示例8: Add

        public bool Add(X509Certificate certificate)
        {
            if (Contains (certificate))
                return true;

            using (var cert = SecCertificate.Create (certificate.GetEncoded ())) {
                return SecCertificateAddToKeychain (cert.Handle, Handle) == OSStatus.Ok;
            }
        }
開發者ID:princeoffoods,項目名稱:MimeKit,代碼行數:9,代碼來源:SecKeychain.cs

示例9: Validate

		/**
		 * Validate the time stamp token.
		 * <p>
		 * To be valid the token must be signed by the passed in certificate and
		 * the certificate must be the one referred to by the SigningCertificate
		 * attribute included in the hashed attributes of the token. The
		 * certificate must also have the ExtendedKeyUsageExtension with only
		 * KeyPurposeID.IdKPTimeStamping and have been valid at the time the
		 * timestamp was created.
		 * </p>
		 * <p>
		 * A successful call to validate means all the above are true.
		 * </p>
		 */
		public void Validate(
			X509Certificate cert)
		{
			try
			{
				byte[] hash = DigestUtilities.CalculateDigest(
					certID.GetHashAlgorithm(), cert.GetEncoded());

				if (!Arrays.ConstantTimeAreEqual(certID.GetCertHash(), hash))
				{
					throw new TspValidationException("certificate hash does not match certID hash.");
				}

				if (certID.IssuerSerial != null)
				{
					if (!certID.IssuerSerial.Serial.Value.Equals(cert.SerialNumber))
					{
						throw new TspValidationException("certificate serial number does not match certID for signature.");
					}

					GeneralName[] names = certID.IssuerSerial.Issuer.GetNames();
					X509Name principal = PrincipalUtilities.GetIssuerX509Principal(cert);
					bool found = false;

					for (int i = 0; i != names.Length; i++)
					{
						if (names[i].TagNo == 4
							&& X509Name.GetInstance(names[i].Name).Equivalent(principal))
						{
							found = true;
							break;
						}
					}

					if (!found)
					{
						throw new TspValidationException("certificate name does not match certID for signature. ");
					}
				}

				TspUtil.ValidateCertificate(cert);

				cert.CheckValidity(tstInfo.GenTime);

				if (!tsaSignerInfo.Verify(cert))
				{
					throw new TspValidationException("signature not created by certificate.");
				}
			}
			catch (CmsException e)
			{
				if (e.InnerException != null)
				{
					throw new TspException(e.Message, e.InnerException);
				}

				throw new TspException("CMS exception: " + e, e);
			}
			catch (CertificateEncodingException e)
			{
				throw new TspException("problem processing certificate: " + e, e);
			}
			catch (SecurityUtilityException e)
			{
				throw new TspException("cannot find algorithm: " + e.Message, e);
			}
		}
開發者ID:randombit,項目名稱:hacrypto,代碼行數:81,代碼來源:TimeStampToken.cs

示例10: TimeStampTokenGenerator

        /**
         * create with a signer with extra signed/unsigned attributes.
         */
        public TimeStampTokenGenerator(
			AsymmetricKeyParameter	key,
			X509Certificate			cert,
			string					digestOID,
			string					tsaPolicyOID,
			Asn1.Cms.AttributeTable	signedAttr,
			Asn1.Cms.AttributeTable	unsignedAttr)
        {
            this.key = key;
            this.cert = cert;
            this.digestOID = digestOID;
            this.tsaPolicyOID = tsaPolicyOID;
            this.unsignedAttr = unsignedAttr;

            TspUtil.ValidateCertificate(cert);

            //
            // add the essCertid
            //
            Hashtable signedAttrs;
            if (signedAttr != null)
            {
                signedAttrs = signedAttr.ToHashtable();
            }
            else
            {
                signedAttrs = new Hashtable();
            }

            IDigest digest;
            try
            {
                digest = DigestUtilities.GetDigest("SHA-1");
            }
            catch (Exception e)
            {
                throw new TspException("Can't find a SHA-1 implementation.", e);
            }

            try
            {
                byte[] certEncoded = cert.GetEncoded();
                digest.BlockUpdate(certEncoded, 0, certEncoded.Length);
                byte[] hash = DigestUtilities.DoFinal(digest);

                EssCertID essCertid = new EssCertID(hash);

                Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
                    PkcsObjectIdentifiers.IdAASigningCertificate,
                    new DerSet(new SigningCertificate(essCertid)));

                signedAttrs[attr.AttrType] = attr;
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("Exception processing certificate.", e);
            }

            this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
        }
開發者ID:hjgode,項目名稱:iTextSharpCF,代碼行數:63,代碼來源:TimeStampTokenGenerator.cs

示例11: Add

 public bool Add(X509Certificate certificate)
 {
     using (var cert = SecCertificate.Create (certificate.GetEncoded ())) {
         var status = SecCertificateAddToKeychain (cert.Handle, Handle);
         return status == OSStatus.Ok || status == OSStatus.DuplicateItem;
     }
 }
開發者ID:vdaron,項目名稱:MimeKit,代碼行數:7,代碼來源:SecKeychain.cs

示例12: ExportCertificate

 private static byte[] ExportCertificate(X509Certificate certificate, AsymmetricCipherKeyPair subjectKeyPair, TCertificateFormat certificateFormat)
 {
     byte[] result = null;
     switch (certificateFormat)
     {
         case TCertificateFormat.NotSet:
             break;
         case TCertificateFormat.PEM:
             using (MemoryStream stream = new MemoryStream())
             {
                 using (StreamWriter writer = new StreamWriter(stream))
                 {
                     Org.BouncyCastle.Utilities.IO.Pem.PemWriter pemWriter = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(writer);
                     if (subjectKeyPair.Private is ECKeyParameters)
                     {
                         ECPrivateKeyParameters priv = (ECPrivateKeyParameters)subjectKeyPair.Private;
                         ECDomainParameters dp = priv.Parameters;
                         int orderBitLength = dp.N.BitLength;
                         Org.BouncyCastle.Asn1.Sec.ECPrivateKeyStructure ec;
                         Org.BouncyCastle.Asn1.X9.X962Parameters x962;
                         if (priv.PublicKeyParamSet == null)
                         {
                             Org.BouncyCastle.Asn1.X9.X9ECParameters ecP = new Org.BouncyCastle.Asn1.X9.X9ECParameters(dp.Curve, dp.G, dp.N, dp.H, dp.GetSeed());
                             x962 = new Org.BouncyCastle.Asn1.X9.X962Parameters(ecP);
                         }
                         else
                         {
                             x962 = new Org.BouncyCastle.Asn1.X9.X962Parameters(priv.PublicKeyParamSet);
                         }
                         ec = new Org.BouncyCastle.Asn1.Sec.ECPrivateKeyStructure(orderBitLength, priv.D, SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public).PublicKeyData, x962);
                         pemWriter.WriteObject(new Org.BouncyCastle.Utilities.IO.Pem.PemObject("EC PRIVATE KEY", ec.GetEncoded()));
                     }
                     else
                     {
                         pemWriter.WriteObject(new Org.BouncyCastle.OpenSsl.MiscPemGenerator(subjectKeyPair.Private));
                     }
                     pemWriter.WriteObject(new Org.BouncyCastle.OpenSsl.MiscPemGenerator(subjectKeyPair.Public));
                     pemWriter.WriteObject(new Org.BouncyCastle.OpenSsl.MiscPemGenerator(certificate));
                     writer.Flush();
                     result = stream.ToArray();
                 }
             }
             break;
         case TCertificateFormat.PFX:
             //Asn1Sequence asn1Sequence = Asn1Sequence.GetInstance(Asn1Object.FromByteArray(certificate.GetEncoded()));
             //asn1Sequence.GetObjects
             //Org.BouncyCastle.Asn1.Pkcs.Pfx pfx = new Org.BouncyCastle.Asn1.Pkcs.Pfx();
             //Org.BouncyCastle.Asn1.Pkcs.PrivateKeyInfo info = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
             //result = pfx.GetEncoded(Asn1Encodable.Der);
             break;
         case TCertificateFormat.CER:
             result = certificate.GetEncoded();
             break;
         default:
             break;
     }
     return result;
 }
開發者ID:CreatorDev,項目名稱:DTLS.Net,代碼行數:58,代碼來源:Certificates.cs


注:本文中的Org.BouncyCastle.X509.X509Certificate.GetEncoded方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。