• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ASN1类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中ASN1的典型用法代码示例。如果您正苦于以下问题:C# ASN1类的具体用法?C# ASN1怎么用?C# ASN1使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ASN1类属于命名空间,在下文中一共展示了ASN1类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: VerifySignature

		internal bool VerifySignature (DSA dsa) 
		{
			if (signatureOID != "1.2.840.10040.4.3")
				throw new CryptographicException ("Unsupported hash algorithm: " + signatureOID);
			DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
			// only SHA-1 is supported
			v.SetHashAlgorithm ("SHA1");
			ASN1 sign = new ASN1 (signature);
			if ((sign == null) || (sign.Count != 2))
				return false;
			// parts may be less than 20 bytes (i.e. first bytes were 0x00)
			byte[] part1 = sign [0].Value;
			byte[] part2 = sign [1].Value;
			byte[] sig = new byte [40];
			// parts may be less than 20 bytes (i.e. first bytes were 0x00)
			// parts may be more than 20 bytes (i.e. first byte > 0x80, negative)
			int s1 = System.Math.Max (0, part1.Length - 20);
			int e1 = System.Math.Max (0, 20 - part1.Length);
			Buffer.BlockCopy (part1, s1, sig, e1, part1.Length - s1);
			int s2 = System.Math.Max (0, part2.Length - 20);
			int e2 = System.Math.Max (20, 40 - part2.Length);
			Buffer.BlockCopy (part2, s2, sig, e2, part2.Length - s2);
			return v.VerifySignature (Hash, sig);
		}
开发者ID:carrie901,项目名称:mono,代码行数:24,代码来源:X509CRL.cs


示例2: X509CrlEntry

			internal X509CrlEntry (ASN1 entry) 
			{
				sn = entry [0].Value;
				Array.Reverse (sn);
				revocationDate = ASN1Convert.ToDateTime (entry [1]);
				extensions = new X509ExtensionCollection (entry [2]);
			}
开发者ID:carrie901,项目名称:mono,代码行数:7,代码来源:X509CRL.cs


示例3: GetType

		static public KeyInfo GetType (byte[] data) 
		{
			if (data == null)
				throw new ArgumentNullException ("data");

			KeyInfo ki = KeyInfo.Unknown;
			try {
				ASN1 top = new ASN1 (data);
				if ((top.Tag == 0x30) && (top.Count > 0)) {
					ASN1 firstLevel = top [0];
					switch (firstLevel.Tag) {
						case 0x02:
							ki = KeyInfo.PrivateKey;
							break;
						case 0x30:
							ki = KeyInfo.EncryptedPrivateKey;
							break;
					}
				}
			}
			catch {
				throw new CryptographicException ("invalid ASN.1 data");
			}
			return ki;
		}
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:25,代码来源:PKCS8.cs


示例4: ToString

        static public string ToString(ASN1 seq)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < seq.Count; i++)
            {
                ASN1 entry = seq[i];
                AppendEntry(sb, entry, true);

                // separator (not on last iteration)
                if (i < seq.Count - 1)
                    sb.Append(", ");
            }
            return sb.ToString();
        }
开发者ID:javierpuntonet,项目名称:FacturaE,代码行数:14,代码来源:X501Name.cs


示例5: Decode

		internal AsnDecodeStatus Decode (byte[] extension)
		{
			if ((extension == null) || (extension.Length == 0))
				return AsnDecodeStatus.BadAsn;
			_ski = String.Empty;
			if (extension [0] != 0x04)
				return AsnDecodeStatus.BadTag;
			if (extension.Length == 2)
				return AsnDecodeStatus.InformationNotAvailable;
			if (extension.Length < 3)
				return AsnDecodeStatus.BadLength;

			try {
				ASN1 ex = new ASN1 (extension);
				_subjectKeyIdentifier = ex.Value;
			}
			catch {
				return AsnDecodeStatus.BadAsn;
			}

			return AsnDecodeStatus.Ok;
		}
开发者ID:ANahr,项目名称:mono,代码行数:22,代码来源:X509SubjectKeyIdentifierExtension.cs


示例6: Encode

		internal byte[] Encode ()
		{
			ASN1 ex = null;
			int kubits = (int)_keyUsages;
			byte empty = 0;

			if (kubits == 0) {
				ex = new ASN1 (0x03, new byte[] { empty });
			} else {
				// count empty bits (applicable to first byte only)
				int ku = ((kubits < Byte.MaxValue) ? kubits : (kubits >> 8));
				while (((ku & 0x01) == 0x00) && (empty < 8)) {
					empty++;
					ku >>= 1;
				}

				if (kubits <= Byte.MaxValue) {
					ex = new ASN1 (0x03, new byte[] { empty, (byte)kubits });
				} else {
					ex = new ASN1 (0x03, new byte[] { empty, (byte)kubits, (byte)(kubits >> 8) });
				}
			}

			return ex.GetBytes ();
		}
开发者ID:ANahr,项目名称:mono,代码行数:25,代码来源:X509KeyUsageExtension.cs


示例7: AppendEntry

        static private void AppendEntry(StringBuilder sb, ASN1 entry, bool quotes)
        {
            // multiple entries are valid
            for (int k = 0; k < entry.Count; k++)
            {
                ASN1 pair = entry[k];
                ASN1 s = pair[1];
                if (s == null)
                    continue;

                ASN1 poid = pair[0];
                if (poid == null)
                    continue;

                if (poid.CompareValue(countryName))
                    sb.Append("C=");
                else if (poid.CompareValue(organizationName))
                    sb.Append("O=");
                else if (poid.CompareValue(organizationalUnitName))
                    sb.Append("OU=");
                else if (poid.CompareValue(commonName))
                    sb.Append("CN=");
                else if (poid.CompareValue(localityName))
                    sb.Append("L=");
                else if (poid.CompareValue(stateOrProvinceName))
                    sb.Append("ST=");	// Changed to be RFC2253 Compliant
                else if (poid.CompareValue(streetAddress))
                    sb.Append("STREET=");
                else if (poid.CompareValue(domainComponent))
                    sb.Append("DC=");
                else if (poid.CompareValue(userid))
                    sb.Append("UID=");
                //else if (poid.CompareValue(email))
                //    sb.Append("E=");	// NOTE: Not part of RFC2253
                else if (poid.CompareValue(dnQualifier))
                    sb.Append("dnQualifier=");
                else if (poid.CompareValue(title))
                    sb.Append("T=");
                else if (poid.CompareValue(surname))
                    sb.Append("SN=");
                else if (poid.CompareValue(givenName))
                    sb.Append("G=");
                else if (poid.CompareValue(initial))
                    sb.Append("I=");
                else
                {
                    // unknown OID
                    // sb.Append("OID.");	// NOTE: Not present as RFC2253
                    sb.Append(ASN1Convert.ToOid(poid));
                    sb.Append("=");
                }

                string sValue = null;
                // 16bits or 8bits string ? TODO not complete (+special chars!)
                if (s.Tag == 0x1E)
                {
                    // BMPSTRING
                    StringBuilder sb2 = new StringBuilder();
                    for (int j = 1; j < s.Value.Length; j += 2)
                        sb2.Append((char)s.Value[j]);
                    sValue = sb2.ToString();
                }
                else
                {
                    if (s.Tag == 0x14)
                        sValue = Encoding.UTF7.GetString(s.Value);
                    else
                        sValue = Encoding.UTF8.GetString(s.Value);
                    // in some cases we must quote (") the value
                    // Note: this doesn't seems to conform to RFC2253
                    char[] specials = { ',', '+', '"', '\\', '<', '>', ';' };
                    if (quotes)
                    {
                        if ((sValue.IndexOfAny(specials, 0, sValue.Length) > 0) ||
                            sValue.StartsWith(" ") || (sValue.EndsWith(" ")))
                            sValue = "\"" + sValue + "\"";
                    }
                }

                sb.Append(sValue);

                // separator (not on last iteration)
                if (k < entry.Count - 1)
                    sb.Append(", ");
            }
        }
开发者ID:javierpuntonet,项目名称:FacturaE,代码行数:86,代码来源:X501Name.cs


示例8: Decode

			// methods

			private void Decode (byte[] data) 
			{
				ASN1 encryptedPrivateKeyInfo = new ASN1 (data);
				if (encryptedPrivateKeyInfo.Tag != 0x30)
					throw new CryptographicException ("invalid EncryptedPrivateKeyInfo");

				ASN1 encryptionAlgorithm = encryptedPrivateKeyInfo [0];
				if (encryptionAlgorithm.Tag != 0x30)
					throw new CryptographicException ("invalid encryptionAlgorithm");
				ASN1 algorithm = encryptionAlgorithm [0];
				if (algorithm.Tag != 0x06)
					throw new CryptographicException ("invalid algorithm");
				_algorithm = ASN1Convert.ToOid (algorithm);
				// parameters ANY DEFINED BY algorithm OPTIONAL
				if (encryptionAlgorithm.Count > 1) {
					ASN1 parameters = encryptionAlgorithm [1];
					if (parameters.Tag != 0x30)
						throw new CryptographicException ("invalid parameters");

					ASN1 salt = parameters [0];
					if (salt.Tag != 0x04)
						throw new CryptographicException ("invalid salt");
					_salt = salt.Value;

					ASN1 iterationCount = parameters [1];
					if (iterationCount.Tag != 0x02)
						throw new CryptographicException ("invalid iterationCount");
					_iterations = ASN1Convert.ToInt32 (iterationCount);
				}

				ASN1 encryptedData = encryptedPrivateKeyInfo [1];
				if (encryptedData.Tag != 0x04)
					throw new CryptographicException ("invalid EncryptedData");
				_data = encryptedData.Value;
			}
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:37,代码来源:PKCS8.cs


示例9: Encode

			/*
			 * RSAPrivateKey ::= SEQUENCE {
			 *	version           Version, 
			 *	modulus           INTEGER,  -- n
			 *	publicExponent    INTEGER,  -- e
			 *	privateExponent   INTEGER,  -- d
			 *	prime1            INTEGER,  -- p
			 *	prime2            INTEGER,  -- q
			 *	exponent1         INTEGER,  -- d mod (p-1)
			 *	exponent2         INTEGER,  -- d mod (q-1) 
			 *	coefficient       INTEGER,  -- (inverse of q) mod p
			 *	otherPrimeInfos   OtherPrimeInfos OPTIONAL 
			 * }
			 */
			static public byte[] Encode (RSA rsa) 
			{
				RSAParameters param = rsa.ExportParameters (true);

				ASN1 rsaPrivateKey = new ASN1 (0x30);
				rsaPrivateKey.Add (new ASN1 (0x02, new byte [1] { 0x00 }));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Modulus));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Exponent));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.D));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.P));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Q));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DP));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DQ));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.InverseQ));

				return rsaPrivateKey.GetBytes ();
			}
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:31,代码来源:PKCS8.cs


示例10: GetBytes

			public byte[] GetBytes () 
			{
				ASN1 privateKeyAlgorithm = new ASN1 (0x30);
				privateKeyAlgorithm.Add (ASN1Convert.FromOid (_algorithm));
				privateKeyAlgorithm.Add (new ASN1 (0x05)); // ASN.1 NULL

				ASN1 pki = new ASN1 (0x30);
				pki.Add (new ASN1 (0x02, new byte [1] { (byte) _version }));
				pki.Add (privateKeyAlgorithm);
				pki.Add (new ASN1 (0x04, _key));

				if (_list.Count > 0) {
					ASN1 attributes = new ASN1 (0xA0);
					foreach (ASN1 attribute in _list) {
						attributes.Add (attribute);
					}
					pki.Add (attributes);
				}

				return pki.GetBytes ();
			}
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:21,代码来源:PKCS8.cs


示例11: Read

		protected override void Read (TlsBuffer incoming)
		{
			var length = incoming.ReadByte ();
			for (int i = 0; i < length; i++)
				Parameters.CertificateTypes.Add ((ClientCertificateType)incoming.ReadByte ());

			if (Protocol == TlsProtocolCode.Tls12) {
				var length2 = incoming.ReadInt16 ();
				if ((length2 % 2) != 0)
					throw new TlsException (AlertDescription.IlegalParameter);
				var signatureTypes = new SignatureAndHashAlgorithm [length2 >> 1];
				for (int i = 0; i < signatureTypes.Length; i++)
					Parameters.SignatureParameters.SignatureAndHashAlgorithms.Add (new SignatureAndHashAlgorithm (incoming));
			}

			var length3 = incoming.ReadInt16 ();
			if (incoming.Remaining != length3)
				throw new TlsException (AlertDescription.DecodeError);

			/*
			 * Read requested certificate authorities (Distinguised Names)
			 *
			 * Name ::= SEQUENCE OF RelativeDistinguishedName
			 *
			 * RelativeDistinguishedName ::= SET OF AttributeValueAssertion
			 *
			 * AttributeValueAssertion ::= SEQUENCE {
			 *     attributeType OBJECT IDENTIFIER
			 *     attributeValue ANY
			 * }
			 *
			 */

			while (incoming.Remaining > 0) {
				var rdn = new ASN1 (incoming.ReadBytes (incoming.ReadInt16 ()));
				Parameters.CertificateAuthorities.Add (X501.ToString (rdn));
			}
		}
开发者ID:VimalKumarS,项目名称:mono-tls,代码行数:38,代码来源:TlsCertificateRequest.cs


示例12: Encode

		internal byte[] Encode ()
		{
			ASN1 ex = new ASN1 (0x04, _subjectKeyIdentifier);
			return ex.GetBytes ();
		}
开发者ID:ANahr,项目名称:mono,代码行数:5,代码来源:X509SubjectKeyIdentifierExtension.cs


示例13: Parse

		private void Parse (byte[] crl) 
		{
			string e = "Input data cannot be coded as a valid CRL.";
			try {
				// CertificateList  ::=  SEQUENCE  {
				ASN1 encodedCRL = new ASN1 (encoded);
				if ((encodedCRL.Tag != 0x30) || (encodedCRL.Count != 3))
					throw new CryptographicException (e);

				// CertificateList / TBSCertList,
				ASN1 toBeSigned = encodedCRL [0];
				if ((toBeSigned.Tag != 0x30) || (toBeSigned.Count < 3))
					throw new CryptographicException (e);

				int n = 0;
				// CertificateList / TBSCertList / Version OPTIONAL, -- if present, MUST be v2
				if (toBeSigned [n].Tag == 0x02) {
					version = (byte) (toBeSigned [n++].Value [0] + 1);
				}
				else
					version = 1; // DEFAULT
				// CertificateList / TBSCertList / AlgorithmIdentifier,
				signatureOID = ASN1Convert.ToOid (toBeSigned [n++][0]);
				// CertificateList / TBSCertList / Name,
				issuer = X501.ToString (toBeSigned [n++]);
				// CertificateList / TBSCertList / Time,
				thisUpdate = ASN1Convert.ToDateTime (toBeSigned [n++]);
				// CertificateList / TBSCertList / Time OPTIONAL,
				ASN1 next = toBeSigned [n++];
				if ((next.Tag == 0x17) || (next.Tag == 0x18)) {
					nextUpdate = ASN1Convert.ToDateTime (next);
					next = toBeSigned [n++];
				}
				// CertificateList / TBSCertList / revokedCertificates	SEQUENCE OF SEQUENCE  {
				entries = new ArrayList ();
				// this is OPTIONAL so it may not be present if no entries exists
				if ((next != null) && (next.Tag == 0x30)) {
					ASN1 revokedCertificates = next;
					for (int i=0; i < revokedCertificates.Count; i++) {
						entries.Add (new X509CrlEntry (revokedCertificates [i]));
					}
				} else {
					n--;
				}
				// CertificateList / TBSCertList / crlExtensions [0] Extensions OPTIONAL }
				ASN1 extns = toBeSigned [n];
				if ((extns != null) && (extns.Tag == 0xA0) && (extns.Count == 1))
					extensions = new X509ExtensionCollection (extns [0]);
				else
					extensions = new X509ExtensionCollection (null); // result in a read only object
				// CertificateList / AlgorithmIdentifier
				string signatureAlgorithm = ASN1Convert.ToOid (encodedCRL [1][0]);
				if (signatureOID != signatureAlgorithm)
					throw new CryptographicException (e + " [Non-matching signature algorithms in CRL]");

				// CertificateList / BIT STRING 
				byte[] bitstring = encodedCRL [2].Value;
				// first byte contains unused bits in first byte
				signature = new byte [bitstring.Length - 1];
				Buffer.BlockCopy (bitstring, 1, signature, 0, signature.Length);
			}
			catch {
				throw new CryptographicException (e);
			}
		}
开发者ID:carrie901,项目名称:mono,代码行数:65,代码来源:X509CRL.cs


示例14: GetBytes

			public byte[] GetBytes () 
			{
				ASN1 sequence = new ASN1 (0x30);
				sequence.Add (new ASN1 (0x02, sn));
				sequence.Add (ASN1Convert.FromDateTime (revocationDate));
				if (extensions.Count > 0)
					sequence.Add (new ASN1 (extensions.GetBytes ()));
				return sequence.GetBytes ();
			}
开发者ID:carrie901,项目名称:mono,代码行数:9,代码来源:X509CRL.cs


示例15: Encode_v15

		// PKCS #1 v.2.1, Section 9.2
		// EMSA-PKCS1-v1_5-Encode
		public static byte[] Encode_v15 (HashAlgorithm hash, byte[] hashValue, int emLength) 
		{
			if (hashValue.Length != (hash.HashSize >> 3))
				throw new CryptographicException ("bad hash length for " + hash.ToString ());

			// DigestInfo ::= SEQUENCE {
			//	digestAlgorithm AlgorithmIdentifier,
			//	digest OCTET STRING
			// }
		
			byte[] t = null;

			string oid = CryptoConfig.MapNameToOID (hash.ToString ());
			if (oid != null)
			{
				ASN1 digestAlgorithm = new ASN1 (0x30);
				digestAlgorithm.Add (new ASN1 (CryptoConfig.EncodeOID (oid)));
				digestAlgorithm.Add (new ASN1 (0x05));		// NULL
				ASN1 digest = new ASN1 (0x04, hashValue);
				ASN1 digestInfo = new ASN1 (0x30);
				digestInfo.Add (digestAlgorithm);
				digestInfo.Add (digest);

				t = digestInfo.GetBytes ();
			}
			else
			{
				// There are no valid OID, in this case t = hashValue
				// This is the case of the MD5SHA hash algorithm
				t = hashValue;
			}

			Buffer.BlockCopy (hashValue, 0, t, t.Length - hashValue.Length, hashValue.Length);
	
			int PSLength = System.Math.Max (8, emLength - t.Length - 3);
			// PS = PSLength of 0xff
	
			// EM = 0x00 | 0x01 | PS | 0x00 | T
			byte[] EM = new byte [PSLength + t.Length + 3];
			EM [1] = 0x01;
			for (int i=2; i < PSLength + 2; i++)
				EM[i] = 0xff;
			Buffer.BlockCopy (t, 0, EM, PSLength + 3, t.Length);
	
			return EM;
		}
开发者ID:Jakosa,项目名称:MonoLibraries,代码行数:48,代码来源:PKCS1.cs


示例16: getClientCertRSA

		private RSA getClientCertRSA(RSA privKey)
		{
			RSAParameters rsaParams		= new RSAParameters();
			RSAParameters privateParams = privKey.ExportParameters(true);

			// for RSA m_publickey contains 2 ASN.1 integers
			// the modulus and the public exponent
			ASN1 pubkey = new ASN1 (this.Context.ClientSettings.Certificates[0].GetPublicKey());
			ASN1 modulus = pubkey [0];
			if ((modulus == null) || (modulus.Tag != 0x02))
			{
				return null;
			}
			ASN1 exponent = pubkey [1];
			if (exponent.Tag != 0x02)
			{
				return null;
			}

			rsaParams.Modulus = this.getUnsignedBigInteger(modulus.Value);
			rsaParams.Exponent = exponent.Value;

			// Set private key parameters
			rsaParams.D			= privateParams.D;
			rsaParams.DP		= privateParams.DP;
			rsaParams.DQ		= privateParams.DQ;
			rsaParams.InverseQ	= privateParams.InverseQ;
			rsaParams.P			= privateParams.P;
			rsaParams.Q			= privateParams.Q;			

			// BUG: MS BCL 1.0 can't import a key which 
			// isn't the same size as the one present in
			// the container.
			int keySize = (rsaParams.Modulus.Length << 3);
			RSAManaged rsa = new RSAManaged(keySize);
			rsa.ImportParameters (rsaParams);

			return (RSA)rsa;
		}
开发者ID:nickchal,项目名称:pash,代码行数:39,代码来源:TlsClientCertificateVerify.cs


示例17: SubjectAltName

		// Indirectly (undocumented but) supported extensions

		internal string SubjectAltName (bool multiLine)
		{
			if (_raw.Length < 5)
				return "Information Not Available";

			try {
				ASN1 ex = new ASN1 (_raw);
				StringBuilder sb = new StringBuilder ();
				for (int i=0; i < ex.Count; i++) {
					ASN1 el = ex [i];

					string type = null;
					string name = null;

					switch (el.Tag) {
					case 0x81:
						type = "RFC822 Name=";
						name = Encoding.ASCII.GetString (el.Value);
						break;
					case 0x82:
						type = "DNS Name=";
						name = Encoding.ASCII.GetString (el.Value);
						break;
					default:
						type = String.Format ("Unknown ({0})=", el.Tag);
						name = CryptoConvert.ToHex (el.Value);
						break;
					}

					sb.Append (type);
					sb.Append (name);
					if (multiLine) {
						sb.Append (Environment.NewLine);
					} else if (i < ex.Count - 1) {
						sb.Append (", ");
					}
				}
				return sb.ToString ();
			}
			catch {
				return String.Empty;
			}
		}
开发者ID:ANahr,项目名称:mono,代码行数:45,代码来源:AsnEncodedData.cs


示例18: X509SubjectKeyIdentifierExtension

		public X509SubjectKeyIdentifierExtension (PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical)
		{
			if (key == null)
				throw new ArgumentNullException ("key");

			byte[] pkraw = key.EncodedKeyValue.RawData;
			// compute SKI
			switch (algorithm) {
			// hash of the public key, excluding Tag, Length and unused bits values
			case X509SubjectKeyIdentifierHashAlgorithm.Sha1:
				_subjectKeyIdentifier = SHA1.Create ().ComputeHash (pkraw);
				break;
			// 0100 bit pattern followed by the 60 last bit of the hash
			case X509SubjectKeyIdentifierHashAlgorithm.ShortSha1:
				byte[] hash = SHA1.Create ().ComputeHash (pkraw);
				_subjectKeyIdentifier = new byte [8];
				Buffer.BlockCopy (hash, 12, _subjectKeyIdentifier, 0, 8);
				_subjectKeyIdentifier [0] = (byte) (0x40 | (_subjectKeyIdentifier [0] & 0x0F));
				break;
			// hash of the public key, including Tag, Length and unused bits values
			case X509SubjectKeyIdentifierHashAlgorithm.CapiSha1:
				// CryptoAPI does that hash on the complete subjectPublicKeyInfo (unlike PKIX)
				// http://groups.google.ca/groups?selm=e7RqM%24plCHA.1488%40tkmsftngp02&oe=UTF-8&output=gplain
				ASN1 subjectPublicKeyInfo = new ASN1 (0x30);
				ASN1 algo = subjectPublicKeyInfo.Add (new ASN1 (0x30));
				algo.Add (new ASN1 (CryptoConfig.EncodeOID (key.Oid.Value)));
				algo.Add (new ASN1 (key.EncodedParameters.RawData)); 
				// add an extra byte for the unused bits (none)
				byte[] full = new byte [pkraw.Length + 1];
				Buffer.BlockCopy (pkraw, 0, full, 1, pkraw.Length);
				subjectPublicKeyInfo.Add (new ASN1 (0x03, full));
				_subjectKeyIdentifier = SHA1.Create ().ComputeHash (subjectPublicKeyInfo.GetBytes ());
				break;
			default:
				throw new ArgumentException ("algorithm");
			}

			_oid = new Oid (oid, friendlyName);
			base.Critical = critical;
			RawData = Encode ();
		}
开发者ID:ANahr,项目名称:mono,代码行数:41,代码来源:X509SubjectKeyIdentifierExtension.cs


示例19: CheckSignature

		private bool CheckSignature (string fileName) 
		{
			filename = fileName;
			Open (filename);
			entry = GetSecurityEntry ();
			if (entry == null) {
				// no signature is present
				reason = 1;
				Close ();
				return false;
			}

			PKCS7.ContentInfo ci = new PKCS7.ContentInfo (entry);
			if (ci.ContentType != PKCS7.Oid.signedData) {
				Close ();
				return false;
			}

			PKCS7.SignedData sd = new PKCS7.SignedData (ci.Content);
			if (sd.ContentInfo.ContentType != spcIndirectDataContext) {
				Close ();
				return false;
			}

			coll = sd.Certificates;

			ASN1 spc = sd.ContentInfo.Content;
			signedHash = spc [0][1][1];

			HashAlgorithm ha = null; 
			switch (signedHash.Length) {
				case 16:
					ha = HashAlgorithm.Create ("MD5"); 
					hash = GetHash (ha);
					break;
				case 20:
					ha = HashAlgorithm.Create ("SHA1");
					hash = GetHash (ha);
					break;
				default:
					reason = 5;
					Close ();
					return false;
			}
			Close ();

			if (!signedHash.CompareValue (hash)) {
				reason = 2;
			}

			// messageDigest is a hash of spcIndirectDataContext (which includes the file hash)
			byte[] spcIDC = spc [0].Value;
			ha.Initialize (); // re-using hash instance
			byte[] messageDigest = ha.ComputeHash (spcIDC);

			bool sign = VerifySignature (sd, messageDigest, ha);
			return (sign && (reason == 0));
		}
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:58,代码来源:AuthenticodeDeformatter.cs


示例20: VerifySignature

		//private bool VerifySignature (ASN1 cs, byte[] calculatedMessageDigest, string hashName) 
		private bool VerifySignature (PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha) 
		{
			string contentType = null;
			ASN1 messageDigest = null;
//			string spcStatementType = null;
//			string spcSpOpusInfo = null;

			for (int i=0; i < sd.SignerInfo.AuthenticatedAttributes.Count; i++) {
				ASN1 attr = (ASN1) sd.SignerInfo.AuthenticatedAttributes [i];
				string oid = ASN1Convert.ToOid (attr[0]);
				switch (oid) {
					case "1.2.840.113549.1.9.3":
						// contentType
						contentType = ASN1Convert.ToOid (attr[1][0]);
						break;
					case "1.2.840.113549.1.9.4":
						// messageDigest
						messageDigest = attr[1][0];
						break;
					case "1.3.6.1.4.1.311.2.1.11":
						// spcStatementType (Microsoft code signing)
						// possible values
						// - individualCodeSigning (1 3 6 1 4 1 311 2 1 21)
						// - commercialCodeSigning (1 3 6 1 4 1 311 2 1 22)
//						spcStatementType = ASN1Convert.ToOid (attr[1][0][0]);
						break;
					case "1.3.6.1.4.1.311.2.1.12":
						// spcSpOpusInfo (Microsoft code signing)
/*						try {
							spcSpOpusInfo = System.Text.Encoding.UTF8.GetString (attr[1][0][0][0].Value);
						}
						catch (NullReferenceException) {
							spcSpOpusInfo = null;
						}*/
						break;
					default:
						break;
				}
			}
			if (contentType != spcIndirectDataContext)
				return false;

			// verify message digest
			if (messageDigest == null)
				return false;
			if (!messageDigest.CompareValue (calculatedMessageDigest))
				return false;

			// verify signature
			string hashOID = CryptoConfig.MapNameToOID (ha.ToString ());
			
			// change to SET OF (not [0]) as per PKCS #7 1.5
			ASN1 aa = new ASN1 (0x31);
			foreach (ASN1 a in sd.SignerInfo.AuthenticatedAttributes)
				aa.Add (a);
			ha.Initialize ();
			byte[] p7hash = ha.ComputeHash (aa.GetBytes ());

			byte[] signature = sd.SignerInfo.Signature;
			// we need to find the specified certificate
			string issuer = sd.SignerInfo.IssuerName;
			byte[] serial = sd.SignerInfo.SerialNumber;
			foreach (X509Certificate x509 in coll) {
				if (CompareIssuerSerial (issuer, serial, x509)) {
					// don't verify is key size don't match
					if (x509.PublicKey.Length > (signature.Length >> 3)) {
						// return the signing certificate even if the signature isn't correct
						// (required behaviour for 2.0 support)
						signingCertificate = x509;
						RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA;
						if (rsa.VerifyHash (p7hash, hashOID, signature)) {
							signerChain.LoadCertificates (coll);
							trustedRoot = signerChain.Build (x509);
							break; 
						}
					}
				}
			}

			// timestamp signature is optional
			if (sd.SignerInfo.UnauthenticatedAttributes.Count == 0) {
				trustedTimestampRoot = true;
			}  else {
				for (int i = 0; i < sd.SignerInfo.UnauthenticatedAttributes.Count; i++) {
					ASN1 attr = (ASN1) sd.SignerInfo.UnauthenticatedAttributes[i];
					string oid = ASN1Convert.ToOid (attr[0]);
					switch (oid) {
					case PKCS7.Oid.countersignature:
						// SEQUENCE {
						//   OBJECT IDENTIFIER
						//     countersignature (1 2 840 113549 1 9 6)
						//   SET {
						PKCS7.SignerInfo cs = new PKCS7.SignerInfo (attr[1]);
						trustedTimestampRoot = VerifyCounterSignature (cs, signature);
						break;
					default:
						// we don't support other unauthenticated attributes
						break;
					}
//.........这里部分代码省略.........
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:101,代码来源:AuthenticodeDeformatter.cs



注:本文中的ASN1类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ASObject类代码示例发布时间:2022-05-24
下一篇:
C# ASCIIEncoding类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap