示例#1
0
            public static byte[] Encode(RSA rsa)
            {
                RSAParameters rsaParameters = rsa.ExportParameters(true);
                ASN1          asN1          = new ASN1((byte)48);

                asN1.Add(new ASN1((byte)2, new byte[1]));
                asN1.Add(ASN1Convert.FromUnsignedBigInteger(rsaParameters.Modulus));
                asN1.Add(ASN1Convert.FromUnsignedBigInteger(rsaParameters.Exponent));
                asN1.Add(ASN1Convert.FromUnsignedBigInteger(rsaParameters.D));
                asN1.Add(ASN1Convert.FromUnsignedBigInteger(rsaParameters.P));
                asN1.Add(ASN1Convert.FromUnsignedBigInteger(rsaParameters.Q));
                asN1.Add(ASN1Convert.FromUnsignedBigInteger(rsaParameters.DP));
                asN1.Add(ASN1Convert.FromUnsignedBigInteger(rsaParameters.DQ));
                asN1.Add(ASN1Convert.FromUnsignedBigInteger(rsaParameters.InverseQ));
                return(asN1.GetBytes());
            }
        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();
        }
示例#3
0
        internal byte[] Encode()
        {
            if (_signingTime.Year <= 1600)
            {
                throw new ArgumentOutOfRangeException("<= 1600");
            }
            // Only UTCTIME is supported by FX 2.0
            if ((_signingTime.Year < 1950) || (_signingTime.Year >= 2050))
            {
                throw new CryptographicException("[1950,2049]");
            }

            string date = _signingTime.ToString("yyMMddHHmmss", CultureInfo.InvariantCulture) + "Z";
            ASN1   attr = new ASN1(0x17, Encoding.ASCII.GetBytes(date));

            return(attr.GetBytes());
        }
示例#4
0
        public X500DistinguishedName(string distinguishedName, X500DistinguishedNameFlags flag)
        {
            if (distinguishedName == null)
            {
                throw new ArgumentNullException("distinguishedName");
            }
            if ((flag != 0) && ((flag & AllFlags) == 0))
            {
                throw new ArgumentException("flag");
            }

            Oid = new Oid();
            if (distinguishedName.Length == 0)
            {
                // empty (0x00) ASN.1 sequence (0x30)
                RawData = new byte [2] {
                    0x30, 0x00
                };
                DecodeRawData();
            }
            else
            {
                ASN1 dn = MX.X501.FromString(distinguishedName);
                if ((flag & X500DistinguishedNameFlags.Reversed) != 0)
                {
                    ASN1 rdn = new ASN1(0x30);
                    for (int i = dn.Count - 1; i >= 0; i--)
                    {
                        rdn.Add(dn [i]);
                    }
                    dn = rdn;
                }
                RawData = dn.GetBytes();
                if (flag == X500DistinguishedNameFlags.None)
                {
                    name = distinguishedName;
                }
                else
                {
                    name = Decode(flag);
                }
            }
        }
        /// <summary>Initializes a new instance of the <see cref="T:System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension" /> class using a public key, a hash algorithm identifier, and a value indicating whether the extension is critical. </summary>
        /// <param name="key">A <see cref="T:System.Security.Cryptography.X509Certificates.PublicKey" /> object to create a subject key identifier (SKI) from.</param>
        /// <param name="algorithm">One of the <see cref="T:System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm" /> values that identifies which hash algorithm to use.</param>
        /// <param name="critical">true if the extension is critical; otherwise, false.</param>
        public X509SubjectKeyIdentifierExtension(PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            byte[] rawData = key.EncodedKeyValue.RawData;
            switch (algorithm)
            {
            case X509SubjectKeyIdentifierHashAlgorithm.Sha1:
                this._subjectKeyIdentifier = SHA1.Create().ComputeHash(rawData);
                break;

            case X509SubjectKeyIdentifierHashAlgorithm.ShortSha1:
            {
                byte[] src = SHA1.Create().ComputeHash(rawData);
                this._subjectKeyIdentifier = new byte[8];
                Buffer.BlockCopy(src, 12, this._subjectKeyIdentifier, 0, 8);
                this._subjectKeyIdentifier[0] = (64 | (this._subjectKeyIdentifier[0] & 15));
                break;
            }

            case X509SubjectKeyIdentifierHashAlgorithm.CapiSha1:
            {
                ASN1 asn  = new ASN1(48);
                ASN1 asn2 = asn.Add(new ASN1(48));
                asn2.Add(new ASN1(CryptoConfig.EncodeOID(key.Oid.Value)));
                asn2.Add(new ASN1(key.EncodedParameters.RawData));
                byte[] array = new byte[rawData.Length + 1];
                Buffer.BlockCopy(rawData, 0, array, 1, rawData.Length);
                asn.Add(new ASN1(3, array));
                this._subjectKeyIdentifier = SHA1.Create().ComputeHash(asn.GetBytes());
                break;
            }

            default:
                throw new ArgumentException("algorithm");
            }
            this._oid     = new Oid("2.5.29.14", "Subject Key Identifier");
            base.Critical = critical;
            base.RawData  = this.Encode();
        }
        /* SubjectPublicKeyInfo  ::=  SEQUENCE  {
         *      algorithm            AlgorithmIdentifier,
         *      subjectPublicKey     BIT STRING  }
         */
        private ASN1 SubjectPublicKeyInfo()
        {
            ASN1 keyInfo = new ASN1(0x30);

            if (aa is RSA)
            {
                keyInfo.Add(PKCS7.AlgorithmIdentifier("1.2.840.113549.1.1.1"));
                RSAParameters p = (aa as RSA).ExportParameters(false);

                /* RSAPublicKey ::= SEQUENCE {
                 *       modulus            INTEGER,    -- n
                 *       publicExponent     INTEGER  }  -- e
                 */
                ASN1 key = new ASN1(0x30);
                key.Add(ASN1Convert.FromUnsignedBigInteger(p.Modulus));
                key.Add(ASN1Convert.FromUnsignedBigInteger(p.Exponent));
                keyInfo.Add(new ASN1(UniqueIdentifier(key.GetBytes())));
            }
            else if (aa is DSA)
            {
                DSAParameters p = (aa as DSA).ExportParameters(false);

                /* Dss-Parms  ::=  SEQUENCE  {
                 *       p             INTEGER,
                 *       q             INTEGER,
                 *       g             INTEGER  }
                 */
                ASN1 param = new ASN1(0x30);
                param.Add(ASN1Convert.FromUnsignedBigInteger(p.P));
                param.Add(ASN1Convert.FromUnsignedBigInteger(p.Q));
                param.Add(ASN1Convert.FromUnsignedBigInteger(p.G));
                keyInfo.Add(PKCS7.AlgorithmIdentifier("1.2.840.10040.4.1", param));
                ASN1 key = keyInfo.Add(new ASN1(0x03));
                // DSAPublicKey ::= INTEGER  -- public key, y
                key.Add(ASN1Convert.FromUnsignedBigInteger(p.Y));
            }
            else
            {
                throw new NotSupportedException("Unknown Asymmetric Algorithm " + aa.ToString());
            }
            return(keyInfo);
        }
示例#7
0
        // Class {
        //   Class {
        //     Class { Enum },
        //     Class { OID(NTLMSSP) },
        //     Class { OctetStream } } }
        public byte [] ProcessSpnegoInitialContextTokenResponse()
        {
            ASN1 top  = new ASN1(0xA1);
            ASN1 asn  = new ASN1(0x30);
            ASN1 asn1 = new ASN1(0xA0);

            // FIXME: what is this enum?
            asn1.Add(new ASN1(0x0A, new byte [] { 1 })); // Enum whatever
            ASN1 asn2 = new ASN1(0xA1);

            asn2.Add(ASN1Convert.FromOid(Constants.OidNtlmSsp));
            ASN1 asn3 = new ASN1(0xA2);

            asn3.Add(new ASN1(0x04, ProcessMessageType2()));
            asn.Add(asn1);
            asn.Add(asn2);
            asn.Add(asn3);
            top.Add(asn);
            return(top.GetBytes());
        }
示例#8
0
            /*
             * 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());
            }
 /// <summary>Initializes a new instance of the <see cref="T:System.Security.Cryptography.X509Certificates.X500DistinguishedName" /> class using the specified string and <see cref="T:System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags" /> flag.</summary>
 /// <param name="distinguishedName">A string that represents the distinguished name.</param>
 /// <param name="flag">An <see cref="T:System.Security.Cryptography.X509Certificates.X500DistinguishedName" /> object that specifies the characteristics of the distinguished name.</param>
 public X500DistinguishedName(string distinguishedName, X500DistinguishedNameFlags flag)
 {
     if (distinguishedName == null)
     {
         throw new ArgumentNullException("distinguishedName");
     }
     if (flag != X500DistinguishedNameFlags.None && (flag & (X500DistinguishedNameFlags.Reversed | X500DistinguishedNameFlags.UseSemicolons | X500DistinguishedNameFlags.DoNotUsePlusSign | X500DistinguishedNameFlags.DoNotUseQuotes | X500DistinguishedNameFlags.UseCommas | X500DistinguishedNameFlags.UseNewLines | X500DistinguishedNameFlags.UseUTF8Encoding | X500DistinguishedNameFlags.UseT61Encoding | X500DistinguishedNameFlags.ForceUTF8Encoding)) == X500DistinguishedNameFlags.None)
     {
         throw new ArgumentException("flag");
     }
     base.Oid = new Oid();
     if (distinguishedName.Length == 0)
     {
         byte[] array = new byte[2];
         array[0]     = 48;
         base.RawData = array;
         this.DecodeRawData();
     }
     else
     {
         ASN1 asn = X501.FromString(distinguishedName);
         if ((flag & X500DistinguishedNameFlags.Reversed) != X500DistinguishedNameFlags.None)
         {
             ASN1 asn2 = new ASN1(48);
             for (int i = asn.Count - 1; i >= 0; i--)
             {
                 asn2.Add(asn[i]);
             }
             asn = asn2;
         }
         base.RawData = asn.GetBytes();
         if (flag == X500DistinguishedNameFlags.None)
         {
             this.name = distinguishedName;
         }
         else
         {
             this.name = this.Decode(flag);
         }
     }
 }
  ///
  /// SEQUENCE (a)
  ///  +- INTEGER (V)              // Version - 0 (v1998)
  ///  +- SEQUENCE (b)
  ///  |   +- OID (oid)            // 1.2.840.113549.1.1.1
  ///  |   +- Nil (c)
  ///  +- OCTETSTRING(PRVKY) (os)  // Private Key Parameter
  ///
  ///  However, OCTETSTRING(PRVKY) wraps
  ///    SEQUENCE(
  ///      INTEGER(0)              // Version - 0 (v1998)
  ///      INTEGER(N)
  ///      INTEGER(E)
  ///      INTEGER(D)
  ///      INTEGER(P)
  ///      INTEGER(Q)
  ///      INTEGER(DP)
  ///      INTEGER(DQ)
  ///      INTEGER(InvQ)
  ///    )
  public static byte[] RSAKeyToASN1(RSAParameters PrivateKey) {
    ASN1 v = ASN1Convert.FromUnsignedBigInteger(new byte[] {0});

    ASN1 b = PKCS7.AlgorithmIdentifier ("1.2.840.113549.1.1.1");

    ASN1 os = new ASN1(0x30);
    os.Add(ASN1Convert.FromUnsignedBigInteger(new byte[] {0}));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.Modulus));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.Exponent));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.D));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.P));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.Q));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.DP));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.DQ));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.InverseQ));

    ASN1 pem = new ASN1(0x30);
    pem.Add(v);
    pem.Add(b);
    // Make this into an OCTET string
    pem.Add(new ASN1(0x04, os.GetBytes()));
    return pem.GetBytes();
  }
示例#11
0
        internal byte[] Encode()
        {
            ASN1 ex = new ASN1(0x30);

            if (_certificateAuthority)
            {
                ex.Add(new ASN1(0x01, new byte[] { 0xFF }));
            }
            if (_hasPathLengthConstraint)
            {
                // MS encodes the 0 (pathLengthConstraint is OPTIONAL)
                // and in a long form (02 00 versus 02 01 00)
                if (_pathLengthConstraint == 0)
                {
                    ex.Add(new ASN1(0x02, new byte[] { 0x00 }));
                }
                else
                {
                    ex.Add(ASN1Convert.FromInt32(_pathLengthConstraint));
                }
            }

            return(ex.GetBytes());
        }
示例#12
0
        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());
            }
            string text = CryptoConfig.MapNameToOID(hash.ToString());

            byte[] array;
            if (text != null)
            {
                ASN1 asn = new ASN1(48);
                asn.Add(new ASN1(CryptoConfig.EncodeOID(text)));
                asn.Add(new ASN1(5));
                ASN1 asn2 = new ASN1(4, hashValue);
                ASN1 asn3 = new ASN1(48);
                asn3.Add(asn);
                asn3.Add(asn2);
                array = asn3.GetBytes();
            }
            else
            {
                array = hashValue;
            }
            Buffer.BlockCopy(hashValue, 0, array, array.Length - hashValue.Length, hashValue.Length);
            int num = Math.Max(8, emLength - array.Length - 3);

            byte[] array2 = new byte[num + array.Length + 3];
            array2[1] = 1;
            for (int i = 2; i < num + 2; i++)
            {
                array2[i] = byte.MaxValue;
            }
            Buffer.BlockCopy(array, 0, array2, num + 3, array.Length);
            return(array2);
        }
示例#13
0
        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());
            }
            string oid = CryptoConfig.MapNameToOID(hash.ToString());

            byte[] numArray1;
            if (oid != null)
            {
                ASN1 asn1_1 = new ASN1((byte)48);
                asn1_1.Add(new ASN1(CryptoConfig.EncodeOID(oid)));
                asn1_1.Add(new ASN1((byte)5));
                ASN1 asn1_2 = new ASN1((byte)4, hashValue);
                ASN1 asN1   = new ASN1((byte)48);
                asN1.Add(asn1_1);
                asN1.Add(asn1_2);
                numArray1 = asN1.GetBytes();
            }
            else
            {
                numArray1 = hashValue;
            }
            Buffer.BlockCopy((Array)hashValue, 0, (Array)numArray1, numArray1.Length - hashValue.Length, hashValue.Length);
            int num = System.Math.Max(8, emLength - numArray1.Length - 3);

            byte[] numArray2 = new byte[num + numArray1.Length + 3];
            numArray2[1] = (byte)1;
            for (int index = 2; index < num + 2; ++index)
            {
                numArray2[index] = byte.MaxValue;
            }
            Buffer.BlockCopy((Array)numArray1, 0, (Array)numArray2, num + 3, numArray1.Length);
            return(numArray2);
        }
        internal byte[] Encode()
        {
            ASN1 asn = new ASN1(48);

            if (this._certificateAuthority)
            {
                asn.Add(new ASN1(1, new byte[]
                {
                    byte.MaxValue
                }));
            }
            if (this._hasPathLengthConstraint)
            {
                if (this._pathLengthConstraint == 0)
                {
                    asn.Add(new ASN1(2, new byte[1]));
                }
                else
                {
                    asn.Add(ASN1Convert.FromInt32(this._pathLengthConstraint));
                }
            }
            return(asn.GetBytes());
        }
示例#15
0
        private bool VerifySignature(PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha)
        {
            string a   = null;
            ASN1   asn = null;
            int    i   = 0;

            while (i < sd.SignerInfo.AuthenticatedAttributes.Count)
            {
                ASN1   asn2  = (ASN1)sd.SignerInfo.AuthenticatedAttributes[i];
                string text  = ASN1Convert.ToOid(asn2[0]);
                string text2 = text;
                switch (text2)
                {
                case "1.2.840.113549.1.9.3":
                    a = ASN1Convert.ToOid(asn2[1][0]);
                    break;

                case "1.2.840.113549.1.9.4":
                    asn = asn2[1][0];
                    break;
                }
IL_F1:
                i++;
                continue;
                goto IL_F1;
            }
            if (a != "1.3.6.1.4.1.311.2.1.4")
            {
                return(false);
            }
            if (asn == null)
            {
                return(false);
            }
            if (!asn.CompareValue(calculatedMessageDigest))
            {
                return(false);
            }
            string str  = CryptoConfig.MapNameToOID(ha.ToString());
            ASN1   asn3 = new ASN1(49);

            foreach (object obj in sd.SignerInfo.AuthenticatedAttributes)
            {
                ASN1 asn4 = (ASN1)obj;
                asn3.Add(asn4);
            }
            ha.Initialize();
            byte[] rgbHash    = ha.ComputeHash(asn3.GetBytes());
            byte[] signature  = sd.SignerInfo.Signature;
            string issuerName = sd.SignerInfo.IssuerName;

            byte[] serialNumber = sd.SignerInfo.SerialNumber;
            foreach (X509Certificate x509Certificate in this.coll)
            {
                if (this.CompareIssuerSerial(issuerName, serialNumber, x509Certificate) && x509Certificate.PublicKey.Length > signature.Length >> 3)
                {
                    this.signingCertificate = x509Certificate;
                    RSACryptoServiceProvider rsacryptoServiceProvider = (RSACryptoServiceProvider)x509Certificate.RSA;
                    if (rsacryptoServiceProvider.VerifyHash(rgbHash, str, signature))
                    {
                        this.signerChain.LoadCertificates(this.coll);
                        this.trustedRoot = this.signerChain.Build(x509Certificate);
                        break;
                    }
                }
            }
            if (sd.SignerInfo.UnauthenticatedAttributes.Count == 0)
            {
                this.trustedTimestampRoot = true;
            }
            else
            {
                int j = 0;
                while (j < sd.SignerInfo.UnauthenticatedAttributes.Count)
                {
                    ASN1   asn5  = (ASN1)sd.SignerInfo.UnauthenticatedAttributes[j];
                    string text3 = ASN1Convert.ToOid(asn5[0]);
                    string text2 = text3;
                    if (text2 != null)
                    {
                        if (AuthenticodeDeformatter.< > f__switch$map2 == null)
                        {
                            AuthenticodeDeformatter.< > f__switch$map2 = new Dictionary <string, int>(1)
                            {
                                {
                                    "1.2.840.113549.1.9.6",
                                    0
                                }
                            };
                        }
                        int num;
                        if (AuthenticodeDeformatter.< > f__switch$map2.TryGetValue(text2, out num))
                        {
                            if (num == 0)
                            {
                                PKCS7.SignerInfo cs = new PKCS7.SignerInfo(asn5[1]);
                                this.trustedTimestampRoot = this.VerifyCounterSignature(cs, signature);
                            }
                        }
                    }
IL_35D:
                    j++;
                    continue;
                    goto IL_35D;
                }
            }
            return(this.trustedRoot && this.trustedTimestampRoot);
        }
		/* SubjectPublicKeyInfo  ::=  SEQUENCE  {
		 *      algorithm            AlgorithmIdentifier,
		 *      subjectPublicKey     BIT STRING  }
		 */
		private ASN1 SubjectPublicKeyInfo () 
		{
			ASN1 keyInfo = new ASN1 (0x30);
			if (aa is RSA) {
				keyInfo.Add (PKCS7.AlgorithmIdentifier ("1.2.840.113549.1.1.1"));
				RSAParameters p = (aa as RSA).ExportParameters (false);
				/* RSAPublicKey ::= SEQUENCE {
				 *       modulus            INTEGER,    -- n
				 *       publicExponent     INTEGER  }  -- e
				 */
				ASN1 key = new ASN1 (0x30);
				key.Add (ASN1Convert.FromUnsignedBigInteger (p.Modulus));
				key.Add (ASN1Convert.FromUnsignedBigInteger (p.Exponent));
				keyInfo.Add (new ASN1 (UniqueIdentifier (key.GetBytes ())));
			}
			else if (aa is DSA) {
				DSAParameters p = (aa as DSA).ExportParameters (false);
				/* Dss-Parms  ::=  SEQUENCE  {
				 *       p             INTEGER,
				 *       q             INTEGER,
				 *       g             INTEGER  }
				 */
				ASN1 param = new ASN1 (0x30);
				param.Add (ASN1Convert.FromUnsignedBigInteger (p.P));
				param.Add (ASN1Convert.FromUnsignedBigInteger (p.Q));
				param.Add (ASN1Convert.FromUnsignedBigInteger (p.G));
				keyInfo.Add (PKCS7.AlgorithmIdentifier ("1.2.840.10040.4.1", param));
				ASN1 key = keyInfo.Add (new ASN1 (0x03));
				// DSAPublicKey ::= INTEGER  -- public key, y
				key.Add (ASN1Convert.FromUnsignedBigInteger (p.Y));
			}
			else
				throw new NotSupportedException ("Unknown Asymmetric Algorithm " + aa.ToString ());
			return keyInfo;
		}
		private bool VerifyCounterSignature (PKCS7.SignerInfo cs, byte[] signature) 
		{
			// SEQUENCE {
			//   INTEGER 1
			if (cs.Version != 1)
				return false;
			//   SEQUENCE {
			//      SEQUENCE {

			string contentType = null;
			ASN1 messageDigest = null;
			for (int i=0; i < cs.AuthenticatedAttributes.Count; i++) {
				// SEQUENCE {
				//   OBJECT IDENTIFIER
				ASN1 attr = (ASN1) cs.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.2.840.113549.1.9.5":
						// SEQUENCE {
						//   OBJECT IDENTIFIER
						//     signingTime (1 2 840 113549 1 9 5)
						//   SET {
						//     UTCTime '030124013651Z'
						//   }
						// }
						timestamp = ASN1Convert.ToDateTime (attr[1][0]);
						break;
					default:
						break;
				}
			}

			if (contentType != PKCS7.Oid.data) 
				return false;

			// verify message digest
			if (messageDigest == null)
				return false;
			// TODO: must be read from the ASN.1 structure
			string hashName = null;
			switch (messageDigest.Length) {
				case 16:
					hashName = "MD5";
					break;
				case 20:
					hashName = "SHA1";
					break;
			}
			HashAlgorithm ha = HashAlgorithm.Create (hashName);
			if (!messageDigest.CompareValue (ha.ComputeHash (signature)))
				return false;

			// verify signature
			byte[] counterSignature = cs.Signature;

			// change to SET OF (not [0]) as per PKCS #7 1.5
			ASN1 aa = new ASN1 (0x31);
			foreach (ASN1 a in cs.AuthenticatedAttributes)
				aa.Add (a);
			byte[] p7hash = ha.ComputeHash (aa.GetBytes ());

			// we need to try all certificates
			string issuer = cs.IssuerName;
			byte[] serial = cs.SerialNumber;
			foreach (X509Certificate x509 in coll) {
				if (CompareIssuerSerial (issuer, serial, x509)) {
					if (x509.PublicKey.Length > counterSignature.Length) {
						RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA;
						// we need to HACK around bad (PKCS#1 1.5) signatures made by Verisign Timestamp Service
						// and this means copying stuff into our own RSAManaged to get the required flexibility
						RSAManaged rsam = new RSAManaged ();
						rsam.ImportParameters (rsa.ExportParameters (false));
						if (PKCS1.Verify_v15 (rsam, ha, p7hash, counterSignature, true)) {
							timestampChain.LoadCertificates (coll);
							return (timestampChain.Build (x509));
						}
					}
				}
			}
			// no certificate can verify this signature!
			return false;
		}
示例#18
0
 public byte[] GetBytes()
 {
     return(asn.GetBytes());
 }
示例#19
0
        private bool VerifyCounterSignature(PKCS7.SignerInfo cs, byte[] signature)
        {
            if (cs.Version != 1)
            {
                return(false);
            }
            string a   = null;
            ASN1   aSN = null;

            for (int i = 0; i < cs.AuthenticatedAttributes.Count; i++)
            {
                ASN1 aSN2 = (ASN1)cs.AuthenticatedAttributes[i];
                switch (ASN1Convert.ToOid(aSN2[0]))
                {
                case "1.2.840.113549.1.9.3":
                    a = ASN1Convert.ToOid(aSN2[1][0]);
                    break;

                case "1.2.840.113549.1.9.4":
                    aSN = aSN2[1][0];
                    break;

                case "1.2.840.113549.1.9.5":
                    timestamp = ASN1Convert.ToDateTime(aSN2[1][0]);
                    break;
                }
            }
            if (a != "1.2.840.113549.1.7.1")
            {
                return(false);
            }
            if (aSN == null)
            {
                return(false);
            }
            string hashName = null;

            switch (aSN.Length)
            {
            case 16:
                hashName = "MD5";
                break;

            case 20:
                hashName = "SHA1";
                break;
            }
            HashAlgorithm hashAlgorithm = HashAlgorithm.Create(hashName);

            if (!aSN.CompareValue(hashAlgorithm.ComputeHash(signature)))
            {
                return(false);
            }
            byte[] signature2 = cs.Signature;
            ASN1   aSN3       = new ASN1(49);

            foreach (ASN1 authenticatedAttribute in cs.AuthenticatedAttributes)
            {
                aSN3.Add(authenticatedAttribute);
            }
            byte[] hashValue  = hashAlgorithm.ComputeHash(aSN3.GetBytes());
            string issuerName = cs.IssuerName;

            byte[] serialNumber = cs.SerialNumber;
            foreach (X509Certificate item in coll)
            {
                if (CompareIssuerSerial(issuerName, serialNumber, item) && item.PublicKey.Length > signature2.Length)
                {
                    RSACryptoServiceProvider rSACryptoServiceProvider = (RSACryptoServiceProvider)item.RSA;
                    RSAManaged rSAManaged = new RSAManaged();
                    rSAManaged.ImportParameters(rSACryptoServiceProvider.ExportParameters(includePrivateParameters: false));
                    if (PKCS1.Verify_v15(rSAManaged, hashAlgorithm, hashValue, signature2, tryNonStandardEncoding: true))
                    {
                        timestampChain.LoadCertificates(coll);
                        return(timestampChain.Build(item));
                    }
                }
            }
            return(false);
        }
示例#20
0
        // that's were the real job is!
        private void Parse(byte[] data)
        {
            try {
                decoder = new ASN1(data);
                // Certificate
                if (decoder.Tag != 0x30)
                {
                    throw new CryptographicException(encoding_error);
                }
                // Certificate / TBSCertificate
                if (decoder [0].Tag != 0x30)
                {
                    throw new CryptographicException(encoding_error);
                }

                ASN1 tbsCertificate = decoder [0];

                int tbs = 0;
                // Certificate / TBSCertificate / Version
                ASN1 v = decoder [0][tbs];
                version = 1;                                    // DEFAULT v1
                if ((v.Tag == 0xA0) && (v.Count > 0))
                {
                    // version (optional) is present only in v2+ certs
                    version += v [0].Value [0];                         // zero based
                    tbs++;
                }

                // Certificate / TBSCertificate / CertificateSerialNumber
                ASN1 sn = decoder [0][tbs++];
                if (sn.Tag != 0x02)
                {
                    throw new CryptographicException(encoding_error);
                }
                serialnumber = sn.Value;
                Array.Reverse(serialnumber, 0, serialnumber.Length);

                // Certificate / TBSCertificate / AlgorithmIdentifier
                tbs++;
                // ASN1 signatureAlgo = tbsCertificate.Element (tbs++, 0x30);

                issuer       = tbsCertificate.Element(tbs++, 0x30);
                m_issuername = X501.ToString(issuer);

                ASN1 validity  = tbsCertificate.Element(tbs++, 0x30);
                ASN1 notBefore = validity [0];
                m_from = ASN1Convert.ToDateTime(notBefore);
                ASN1 notAfter = validity [1];
                m_until = ASN1Convert.ToDateTime(notAfter);

                subject   = tbsCertificate.Element(tbs++, 0x30);
                m_subject = X501.ToString(subject);

                ASN1 subjectPublicKeyInfo = tbsCertificate.Element(tbs++, 0x30);

                ASN1 algorithm = subjectPublicKeyInfo.Element(0, 0x30);
                ASN1 algo      = algorithm.Element(0, 0x06);
                m_keyalgo = ASN1Convert.ToOid(algo);
                // parameters ANY DEFINED BY algorithm OPTIONAL
                // so we dont ask for a specific (Element) type and return DER
                ASN1 parameters = algorithm [1];
                m_keyalgoparams = ((algorithm.Count > 1) ? parameters.GetBytes() : null);

                ASN1 subjectPublicKey = subjectPublicKeyInfo.Element(1, 0x03);
                // we must drop th first byte (which is the number of unused bits
                // in the BITSTRING)
                int n = subjectPublicKey.Length - 1;
                m_publickey = new byte [n];
                Buffer.BlockCopy(subjectPublicKey.Value, 1, m_publickey, 0, n);

                // signature processing
                byte[] bitstring = decoder [2].Value;
                // first byte contains unused bits in first byte
                signature = new byte [bitstring.Length - 1];
                Buffer.BlockCopy(bitstring, 1, signature, 0, signature.Length);

                algorithm       = decoder [1];
                algo            = algorithm.Element(0, 0x06);
                m_signaturealgo = ASN1Convert.ToOid(algo);
                parameters      = algorithm [1];
                if (parameters != null)
                {
                    m_signaturealgoparams = parameters.GetBytes();
                }
                else
                {
                    m_signaturealgoparams = null;
                }

                // Certificate / TBSCertificate / issuerUniqueID
                ASN1 issuerUID = tbsCertificate.Element(tbs, 0x81);
                if (issuerUID != null)
                {
                    tbs++;
                    issuerUniqueID = issuerUID.Value;
                }

                // Certificate / TBSCertificate / subjectUniqueID
                ASN1 subjectUID = tbsCertificate.Element(tbs, 0x82);
                if (subjectUID != null)
                {
                    tbs++;
                    subjectUniqueID = subjectUID.Value;
                }

                // Certificate / TBSCertificate / Extensions
                ASN1 extns = tbsCertificate.Element(tbs, 0xA3);
                if ((extns != null) && (extns.Count == 1))
                {
                    extensions = new X509ExtensionCollection(extns [0]);
                }
                else
                {
                    extensions = new X509ExtensionCollection(null);
                }

                // keep a copy of the original data
                m_encodedcert = (byte[])data.Clone();
            }
            catch (Exception ex) {
                throw new CryptographicException(encoding_error, ex);
            }
        }
示例#21
0
 public byte[] GetBytes()
 {
     return(ASN1.GetBytes());
 }
		internal byte[] Encode ()
		{
			ASN1 ex = new ASN1 (0x04, _subjectKeyIdentifier);
			return ex.GetBytes ();
		}
示例#23
0
文件: X509CRL.cs 项目: carrie901/mono
			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 ();
			}
        internal byte[] Encode()
        {
            ASN1 ex = new ASN1(0x04, _subjectKeyIdentifier);

            return(ex.GetBytes());
        }
示例#25
0
		internal byte[] Encode ()
		{
			ASN1 ex = new ASN1 (0x30);

			if (_certificateAuthority)
				ex.Add (new ASN1 (0x01, new byte[] { 0xFF }));
			if (_hasPathLengthConstraint) {
				// MS encodes the 0 (pathLengthConstraint is OPTIONAL)
				// and in a long form (02 00 versus 02 01 00)
				if (_pathLengthConstraint == 0)
					ex.Add (new ASN1 (0x02, new byte[] { 0x00 }));
				else
					ex.Add (ASN1Convert.FromInt32 (_pathLengthConstraint));
			}

			return ex.GetBytes ();
		}
示例#26
0
		// 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;
		}
示例#27
0
        private bool VerifyCounterSignature(PKCS7.SignerInfo cs, byte[] signature)
        {
            if (cs.Version != 1)
            {
                return(false);
            }
            string a   = null;
            ASN1   asn = null;
            int    i   = 0;

            while (i < cs.AuthenticatedAttributes.Count)
            {
                ASN1   asn2  = (ASN1)cs.AuthenticatedAttributes[i];
                string text  = ASN1Convert.ToOid(asn2[0]);
                string text2 = text;
                switch (text2)
                {
                case "1.2.840.113549.1.9.3":
                    a = ASN1Convert.ToOid(asn2[1][0]);
                    break;

                case "1.2.840.113549.1.9.4":
                    asn = asn2[1][0];
                    break;

                case "1.2.840.113549.1.9.5":
                    this.timestamp = ASN1Convert.ToDateTime(asn2[1][0]);
                    break;
                }
IL_FC:
                i++;
                continue;
                goto IL_FC;
            }
            if (a != "1.2.840.113549.1.7.1")
            {
                return(false);
            }
            if (asn == null)
            {
                return(false);
            }
            string hashName = null;
            int    length   = asn.Length;

            if (length != 16)
            {
                if (length == 20)
                {
                    hashName = "SHA1";
                }
            }
            else
            {
                hashName = "MD5";
            }
            HashAlgorithm hashAlgorithm = HashAlgorithm.Create(hashName);

            if (!asn.CompareValue(hashAlgorithm.ComputeHash(signature)))
            {
                return(false);
            }
            byte[] signature2 = cs.Signature;
            ASN1   asn3       = new ASN1(49);

            foreach (object obj in cs.AuthenticatedAttributes)
            {
                ASN1 asn4 = (ASN1)obj;
                asn3.Add(asn4);
            }
            byte[] hashValue  = hashAlgorithm.ComputeHash(asn3.GetBytes());
            string issuerName = cs.IssuerName;

            byte[] serialNumber = cs.SerialNumber;
            foreach (X509Certificate x509Certificate in this.coll)
            {
                if (this.CompareIssuerSerial(issuerName, serialNumber, x509Certificate) && x509Certificate.PublicKey.Length > signature2.Length)
                {
                    RSACryptoServiceProvider rsacryptoServiceProvider = (RSACryptoServiceProvider)x509Certificate.RSA;
                    RSAManaged rsamanaged = new RSAManaged();
                    rsamanaged.ImportParameters(rsacryptoServiceProvider.ExportParameters(false));
                    if (PKCS1.Verify_v15(rsamanaged, hashAlgorithm, hashValue, signature2, true))
                    {
                        this.timestampChain.LoadCertificates(this.coll);
                        return(this.timestampChain.Build(x509Certificate));
                    }
                }
            }
            return(false);
        }
        internal byte[] Encode()
        {
            ASN1 asn = new ASN1(4, this._subjectKeyIdentifier);

            return(asn.GetBytes());
        }
示例#29
0
			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 ();
			}
 private void Parse(byte[] data)
 {
     try
     {
         this.decoder = new ASN1(data);
         if (this.decoder.Tag != 48)
         {
             throw new CryptographicException(X509Certificate.encoding_error);
         }
         if (this.decoder[0].Tag != 48)
         {
             throw new CryptographicException(X509Certificate.encoding_error);
         }
         ASN1 asn  = this.decoder[0];
         int  num  = 0;
         ASN1 asn2 = this.decoder[0][num];
         this.version = 1;
         if (asn2.Tag == 160 && asn2.Count > 0)
         {
             this.version += (int)asn2[0].Value[0];
             num++;
         }
         ASN1 asn3 = this.decoder[0][num++];
         if (asn3.Tag != 2)
         {
             throw new CryptographicException(X509Certificate.encoding_error);
         }
         this.serialnumber = asn3.Value;
         Array.Reverse(this.serialnumber, 0, this.serialnumber.Length);
         num++;
         this.issuer       = asn.Element(num++, 48);
         this.m_issuername = X501.ToString(this.issuer);
         ASN1 asn4 = asn.Element(num++, 48);
         ASN1 time = asn4[0];
         this.m_from = ASN1Convert.ToDateTime(time);
         ASN1 time2 = asn4[1];
         this.m_until   = ASN1Convert.ToDateTime(time2);
         this.subject   = asn.Element(num++, 48);
         this.m_subject = X501.ToString(this.subject);
         ASN1 asn5 = asn.Element(num++, 48);
         ASN1 asn6 = asn5.Element(0, 48);
         ASN1 asn7 = asn6.Element(0, 6);
         this.m_keyalgo = ASN1Convert.ToOid(asn7);
         ASN1 asn8 = asn6[1];
         this.m_keyalgoparams = ((asn6.Count <= 1) ? null : asn8.GetBytes());
         ASN1 asn9 = asn5.Element(1, 3);
         int  num2 = asn9.Length - 1;
         this.m_publickey = new byte[num2];
         Buffer.BlockCopy(asn9.Value, 1, this.m_publickey, 0, num2);
         byte[] value = this.decoder[2].Value;
         this.signature = new byte[value.Length - 1];
         Buffer.BlockCopy(value, 1, this.signature, 0, this.signature.Length);
         asn6 = this.decoder[1];
         asn7 = asn6.Element(0, 6);
         this.m_signaturealgo = ASN1Convert.ToOid(asn7);
         asn8 = asn6[1];
         if (asn8 != null)
         {
             this.m_signaturealgoparams = asn8.GetBytes();
         }
         else
         {
             this.m_signaturealgoparams = null;
         }
         ASN1 asn10 = asn.Element(num, 129);
         if (asn10 != null)
         {
             num++;
             this.issuerUniqueID = asn10.Value;
         }
         ASN1 asn11 = asn.Element(num, 130);
         if (asn11 != null)
         {
             num++;
             this.subjectUniqueID = asn11.Value;
         }
         ASN1 asn12 = asn.Element(num, 163);
         if (asn12 != null && asn12.Count == 1)
         {
             this.extensions = new X509ExtensionCollection(asn12[0]);
         }
         else
         {
             this.extensions = new X509ExtensionCollection(null);
         }
         this.m_encodedcert = (byte[])data.Clone();
     }
     catch (Exception inner)
     {
         throw new CryptographicException(X509Certificate.encoding_error, inner);
     }
 }
		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 ();
		}
示例#32
0
			// Note: PKCS#8 doesn't define how to generate the key required for encryption
			// so you're on your own. Just don't try to copy the big guys too much ;)
			// Netscape:	http://www.cs.auckland.ac.nz/~pgut001/pubs/netscape.txt
			// Microsoft:	http://www.cs.auckland.ac.nz/~pgut001/pubs/breakms.txt
			public byte[] GetBytes ()
			{
				if (_algorithm == null)
					throw new CryptographicException ("No algorithm OID specified");

				ASN1 encryptionAlgorithm = new ASN1 (0x30);
				encryptionAlgorithm.Add (ASN1Convert.FromOid (_algorithm));

				// parameters ANY DEFINED BY algorithm OPTIONAL
				if ((_iterations > 0) || (_salt != null)) {
					ASN1 salt = new ASN1 (0x04, _salt);
					ASN1 iterations = ASN1Convert.FromInt32 (_iterations);

					ASN1 parameters = new ASN1 (0x30);
					parameters.Add (salt);
					parameters.Add (iterations);
					encryptionAlgorithm.Add (parameters);
				}

				// encapsulates EncryptedData into an OCTET STRING
				ASN1 encryptedData = new ASN1 (0x04, _data);

				ASN1 encryptedPrivateKeyInfo = new ASN1 (0x30);
				encryptedPrivateKeyInfo.Add (encryptionAlgorithm);
				encryptedPrivateKeyInfo.Add (encryptedData);

				return encryptedPrivateKeyInfo.GetBytes ();
			}
示例#33
0
		internal byte[] Encode ()
		{
			ASN1 ex = new ASN1 (0x30);
			foreach (Oid oid in _enhKeyUsage) {
				ex.Add (ASN1Convert.FromOid (oid.Value));
			}
			return ex.GetBytes ();
		}
示例#34
0
        private bool VerifySignature(PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha)
        {
            string a   = null;
            ASN1   aSN = null;

            for (int i = 0; i < sd.SignerInfo.AuthenticatedAttributes.Count; i++)
            {
                ASN1 aSN2 = (ASN1)sd.SignerInfo.AuthenticatedAttributes[i];
                switch (ASN1Convert.ToOid(aSN2[0]))
                {
                case "1.2.840.113549.1.9.3":
                    a = ASN1Convert.ToOid(aSN2[1][0]);
                    break;

                case "1.2.840.113549.1.9.4":
                    aSN = aSN2[1][0];
                    break;
                }
            }
            if (a != "1.3.6.1.4.1.311.2.1.4")
            {
                return(false);
            }
            if (aSN == null)
            {
                return(false);
            }
            if (!aSN.CompareValue(calculatedMessageDigest))
            {
                return(false);
            }
            string str  = CryptoConfig.MapNameToOID(ha.ToString());
            ASN1   aSN3 = new ASN1(49);

            foreach (ASN1 authenticatedAttribute in sd.SignerInfo.AuthenticatedAttributes)
            {
                aSN3.Add(authenticatedAttribute);
            }
            ha.Initialize();
            byte[] rgbHash    = ha.ComputeHash(aSN3.GetBytes());
            byte[] signature  = sd.SignerInfo.Signature;
            string issuerName = sd.SignerInfo.IssuerName;

            byte[] serialNumber = sd.SignerInfo.SerialNumber;
            foreach (X509Certificate item in coll)
            {
                if (CompareIssuerSerial(issuerName, serialNumber, item) && item.PublicKey.Length > signature.Length >> 3)
                {
                    signingCertificate = item;
                    RSACryptoServiceProvider rSACryptoServiceProvider = (RSACryptoServiceProvider)item.RSA;
                    if (rSACryptoServiceProvider.VerifyHash(rgbHash, str, signature))
                    {
                        signerChain.LoadCertificates(coll);
                        trustedRoot = signerChain.Build(item);
                        break;
                    }
                }
            }
            if (sd.SignerInfo.UnauthenticatedAttributes.Count == 0)
            {
                trustedTimestampRoot = true;
            }
            else
            {
                for (int j = 0; j < sd.SignerInfo.UnauthenticatedAttributes.Count; j++)
                {
                    ASN1 aSN4 = (ASN1)sd.SignerInfo.UnauthenticatedAttributes[j];
                    switch (ASN1Convert.ToOid(aSN4[0]))
                    {
                    case "1.2.840.113549.1.9.6":
                    {
                        PKCS7.SignerInfo cs = new PKCS7.SignerInfo(aSN4[1]);
                        trustedTimestampRoot = VerifyCounterSignature(cs, signature);
                        break;
                    }
                    }
                }
            }
            return(trustedRoot && trustedTimestampRoot);
        }
    //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;
                }
            }
        }

        return (trustedRoot && trustedTimestampRoot);
    }
示例#36
0
 private void Parse(byte[] data)
 {
     try
     {
         this.decoder = new ASN1(data);
         if (this.decoder.Tag != 0x30)
         {
             throw new CryptographicException(encoding_error);
         }
         if (this.decoder[0].Tag != 0x30)
         {
             throw new CryptographicException(encoding_error);
         }
         ASN1 asn   = this.decoder[0];
         int  index = 0;
         ASN1 asn2  = this.decoder[0][index];
         this.version = 1;
         if ((asn2.Tag == 160) && (asn2.Count > 0))
         {
             this.version += asn2[0].Value[0];
             index++;
         }
         ASN1 asn3 = this.decoder[0][index++];
         if (asn3.Tag != 2)
         {
             throw new CryptographicException(encoding_error);
         }
         this.serialnumber = asn3.Value;
         Array.Reverse(this.serialnumber, 0, this.serialnumber.Length);
         index++;
         this.issuer       = asn.Element(index++, 0x30);
         this.m_issuername = X501.ToString(this.issuer);
         ASN1 asn4 = asn.Element(index++, 0x30);
         ASN1 time = asn4[0];
         this.m_from = ASN1Convert.ToDateTime(time);
         ASN1 asn6 = asn4[1];
         this.m_until   = ASN1Convert.ToDateTime(asn6);
         this.subject   = asn.Element(index++, 0x30);
         this.m_subject = X501.ToString(this.subject);
         ASN1 asn7 = asn.Element(index++, 0x30);
         ASN1 asn8 = asn7.Element(0, 0x30);
         ASN1 asn9 = asn8.Element(0, 6);
         this.m_keyalgo = ASN1Convert.ToOid(asn9);
         ASN1 asn10 = asn8[1];
         this.m_keyalgoparams = (asn8.Count <= 1) ? null : asn10.GetBytes();
         ASN1 asn11 = asn7.Element(1, 3);
         int  count = asn11.Length - 1;
         this.m_publickey = new byte[count];
         Buffer.BlockCopy(asn11.Value, 1, this.m_publickey, 0, count);
         byte[] src = this.decoder[2].Value;
         this.signature = new byte[src.Length - 1];
         Buffer.BlockCopy(src, 1, this.signature, 0, this.signature.Length);
         asn8 = this.decoder[1];
         asn9 = asn8.Element(0, 6);
         this.m_signaturealgo = ASN1Convert.ToOid(asn9);
         asn10 = asn8[1];
         if (asn10 != null)
         {
             this.m_signaturealgoparams = asn10.GetBytes();
         }
         else
         {
             this.m_signaturealgoparams = null;
         }
         ASN1 asn12 = asn.Element(index, 0x81);
         if (asn12 != null)
         {
             index++;
             this.issuerUniqueID = asn12.Value;
         }
         ASN1 asn13 = asn.Element(index, 130);
         if (asn13 != null)
         {
             index++;
             this.subjectUniqueID = asn13.Value;
         }
         ASN1 asn14 = asn.Element(index, 0xa3);
         if ((asn14 != null) && (asn14.Count == 1))
         {
             this.extensions = new X509ExtensionCollection(asn14[0]);
         }
         else
         {
             this.extensions = new X509ExtensionCollection(null);
         }
         this.m_encodedcert = (byte[])data.Clone();
     }
     catch (Exception exception)
     {
         throw new CryptographicException(encoding_error, exception);
     }
 }
		//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;
					}
				}
			}

			return (trustedRoot && trustedTimestampRoot);
		}
		private byte[] UniqueIdentifier (byte[] id) 
		{
			// UniqueIdentifier  ::=  BIT STRING
			ASN1 uid = new ASN1 (0x03);
			// first byte in a BITSTRING is the number of unused bits in the first byte
			byte[] v = new byte [id.Length + 1];
			Buffer.BlockCopy (id, 0, v, 1, id.Length);
			uid.Value = v;
			return uid.GetBytes ();
		}
    private bool VerifyCounterSignature (PKCS7.SignerInfo cs, byte[] signature)
    {
        // SEQUENCE {
        //   INTEGER 1
        if (cs.Version != 1)
            return false;
        //   SEQUENCE {
        //      SEQUENCE {

        string contentType = null;
        ASN1 messageDigest = null;
        for (int i=0; i < cs.AuthenticatedAttributes.Count; i++)
        {
            // SEQUENCE {
            //   OBJECT IDENTIFIER
            ASN1 attr = (ASN1) cs.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.2.840.113549.1.9.5":
                // SEQUENCE {
                //   OBJECT IDENTIFIER
                //     signingTime (1 2 840 113549 1 9 5)
                //   SET {
                //     UTCTime '030124013651Z'
                //   }
                // }
                timestamp = ASN1Convert.ToDateTime (attr[1][0]);
                break;
            default:
                break;
            }
        }

        if (contentType != PKCS7.Oid.data)
            return false;

        // verify message digest
        if (messageDigest == null)
            return false;
        // TODO: must be read from the ASN.1 structure
        string hashName = null;
        switch (messageDigest.Length)
        {
        case 16:
            hashName = "MD5";
            break;
        case 20:
            hashName = "SHA1";
            break;
        }
        HashAlgorithm ha = HashAlgorithm.Create (hashName);
        if (!messageDigest.CompareValue (ha.ComputeHash (signature)))
            return false;

        // verify signature
        byte[] counterSignature = cs.Signature;

        // change to SET OF (not [0]) as per PKCS #7 1.5
        ASN1 aa = new ASN1 (0x31);
        foreach (ASN1 a in cs.AuthenticatedAttributes)
            aa.Add (a);
        byte[] p7hash = ha.ComputeHash (aa.GetBytes ());

        // we need to try all certificates
        string issuer = cs.IssuerName;
        byte[] serial = cs.SerialNumber;
        foreach (X509Certificate x509 in coll)
        {
            if (CompareIssuerSerial (issuer, serial, x509))
            {
                if (x509.PublicKey.Length > counterSignature.Length)
                {
                    RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA;
                    // we need to HACK around bad (PKCS#1 1.5) signatures made by Verisign Timestamp Service
                    // and this means copying stuff into our own RSAManaged to get the required flexibility
                    RSAManaged rsam = new RSAManaged ();
                    rsam.ImportParameters (rsa.ExportParameters (false));
                    if (PKCS1.Verify_v15 (rsam, ha, p7hash, counterSignature, true))
                    {
                        timestampChain.LoadCertificates (coll);
                        return (timestampChain.Build (x509));
                    }
                }
            }
        }
        // no certificate can verify this signature!
        return false;
    }
示例#40
0
        internal byte[] Encode()
        {
            ASN1 md = new ASN1(0x04, _messageDigest);

            return(md.GetBytes());
        }
示例#41
0
			/*
			 * 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 ();
			}
示例#42
0
        private bool VerifyCounterSignature(PKCS7.SignerInfo cs, byte[] signature)
        {
            if (cs.Version == 1)
            {
                string str = null;
                ASN1   asn = null;
                for (int i = 0; i < cs.AuthenticatedAttributes.Count; i++)
                {
                    ASN1   asn2 = (ASN1)cs.AuthenticatedAttributes[i];
                    string key  = ASN1Convert.ToOid(asn2[0]);
                    if (key != null)
                    {
                        if (__f__switch_map3 == null)
                        {
                            Dictionary <string, int> dictionary = new Dictionary <string, int>(3)
                            {
                                {
                                    "1.2.840.113549.1.9.3",
                                    0
                                },
                                {
                                    "1.2.840.113549.1.9.4",
                                    1
                                },
                                {
                                    "1.2.840.113549.1.9.5",
                                    2
                                }
                            };
                            __f__switch_map3 = dictionary;
                        }
                        if (__f__switch_map3.TryGetValue(key, out int num2))
                        {
                            switch (num2)
                            {
                            case 0:
                                str = ASN1Convert.ToOid(asn2[1][0]);
                                break;

                            case 1:
                                asn = asn2[1][0];
                                break;

                            case 2:
                                this.timestamp = ASN1Convert.ToDateTime(asn2[1][0]);
                                break;
                            }
                        }
                    }
                }

                if (str != "1.2.840.113549.1.7.1")
                {
                    return(false);
                }

                if (asn == null)
                {
                    return(false);
                }

                string hashName = null;
                switch (asn.Length)
                {
                case 0x10:
                    hashName = "MD5";
                    break;

                case 20:
                    hashName = "SHA1";
                    break;
                }

                HashAlgorithm hash = HashAlgorithm.Create(hashName);
                if (asn.CompareValue(hash.ComputeHash(signature)))
                {
                    byte[]      buffer     = cs.Signature;
                    ASN1        asn3       = new ASN1(0x31);
                    IEnumerator enumerator = cs.AuthenticatedAttributes.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            ASN1 current = (ASN1)enumerator.Current;
                            asn3.Add(current);
                        }
                    }
                    finally
                    {
                        if (enumerator is IDisposable disposable)
                        {
                            disposable.Dispose();
                        }
                    }

                    byte[] hashValue    = hash.ComputeHash(asn3.GetBytes());
                    string issuerName   = cs.IssuerName;
                    byte[] serialNumber = cs.SerialNumber;
                    X509CertificateCollection.X509CertificateEnumerator enumerator2 = this.coll.GetEnumerator();
                    try
                    {
                        while (enumerator2.MoveNext())
                        {
                            X509Certificate current = enumerator2.Current;
                            if (this.CompareIssuerSerial(issuerName, serialNumber, current) &&
                                (current.PublicKey.Length > buffer.Length))
                            {
                                RSACryptoServiceProvider rSA = (RSACryptoServiceProvider)current.RSA;
                                RSAManaged rsa = new RSAManaged();
                                rsa.ImportParameters(rSA.ExportParameters(false));
                                if (PKCS1.Verify_v15(rsa, hash, hashValue, buffer, true))
                                {
                                    this.timestampChain.LoadCertificates(this.coll);
                                    return(this.timestampChain.Build(current));
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (enumerator2 is IDisposable disposable2)
                        {
                            disposable2.Dispose();
                        }
                    }
                }
            }

            return(false);
        }
示例#43
0
        private bool VerifySignature(PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha)
        {
            string str = null;
            ASN1   asn = null;
            string str3;
            Dictionary <string, int> dictionary;

            for (int i = 0; i < sd.SignerInfo.AuthenticatedAttributes.Count; i++)
            {
                ASN1 asn2 = (ASN1)sd.SignerInfo.AuthenticatedAttributes[i];
                str3 = ASN1Convert.ToOid(asn2[0]);
                if (str3 != null)
                {
                    if (__f__switch_map1 == null)
                    {
                        dictionary = new Dictionary <string, int>(4)
                        {
                            {
                                "1.2.840.113549.1.9.3",
                                0
                            },
                            {
                                "1.2.840.113549.1.9.4",
                                1
                            },
                            {
                                "1.3.6.1.4.1.311.2.1.11",
                                2
                            },
                            {
                                "1.3.6.1.4.1.311.2.1.12",
                                3
                            }
                        };
                        __f__switch_map1 = dictionary;
                    }
                    if (__f__switch_map1.TryGetValue(str3, out int num2))
                    {
                        switch (num2)
                        {
                        case 0:
                            str = ASN1Convert.ToOid(asn2[1][0]);
                            break;

                        case 1:
                            asn = asn2[1][0];
                            break;
                        }
                    }
                }
            }

            if (str != "1.3.6.1.4.1.311.2.1.4")
            {
                return(false);
            }

            if (asn == null)
            {
                return(false);
            }

            if (!asn.CompareValue(calculatedMessageDigest))
            {
                return(false);
            }

            string      str4       = CryptoConfig.MapNameToOID(ha.ToString());
            ASN1        asn3       = new ASN1(0x31);
            IEnumerator enumerator = sd.SignerInfo.AuthenticatedAttributes.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    ASN1 current = (ASN1)enumerator.Current;
                    asn3.Add(current);
                }
            }
            finally
            {
                if (enumerator is IDisposable disposable)
                {
                    disposable.Dispose();
                }
            }

            ha.Initialize();
            byte[] rgbHash    = ha.ComputeHash(asn3.GetBytes());
            byte[] signature  = sd.SignerInfo.Signature;
            string issuerName = sd.SignerInfo.IssuerName;

            byte[] serialNumber = sd.SignerInfo.SerialNumber;
            X509CertificateCollection.X509CertificateEnumerator enumerator2 = this.coll.GetEnumerator();
            try
            {
                while (enumerator2.MoveNext())
                {
                    X509Certificate current = enumerator2.Current;
                    if (this.CompareIssuerSerial(issuerName, serialNumber, current) &&
                        (current.PublicKey.Length > (signature.Length >> 3)))
                    {
                        this.signingCertificate = current;
                        RSACryptoServiceProvider rSA = (RSACryptoServiceProvider)current.RSA;
                        if (rSA.VerifyHash(rgbHash, str4, signature))
                        {
                            this.signerChain.LoadCertificates(this.coll);
                            this.trustedRoot = this.signerChain.Build(current);
                            goto Label_0295;
                        }
                    }
                }
            }
            finally
            {
                if (enumerator2 is IDisposable disposable2)
                {
                    disposable2.Dispose();
                }
            }

Label_0295:
            if (sd.SignerInfo.UnauthenticatedAttributes.Count == 0)
            {
                this.trustedTimestampRoot = true;
            }
            else
            {
                for (int j = 0; j < sd.SignerInfo.UnauthenticatedAttributes.Count; j++)
                {
                    ASN1 asn5 = (ASN1)sd.SignerInfo.UnauthenticatedAttributes[j];
                    str3 = ASN1Convert.ToOid(asn5[0]);
                    if (str3 != null)
                    {
                        if (__f__switch_map2 == null)
                        {
                            dictionary = new Dictionary <string, int>(1)
                            {
                                {
                                    "1.2.840.113549.1.9.6",
                                    0
                                }
                            };
                            __f__switch_map2 = dictionary;
                        }
                        if (__f__switch_map2.TryGetValue(str3, out int num2) && (num2 == 0))
                        {
                            PKCS7.SignerInfo cs = new PKCS7.SignerInfo(asn5[1]);
                            this.trustedTimestampRoot = this.VerifyCounterSignature(cs, signature);
                        }
                    }
                }
            }

            return(this.trustedRoot && this.trustedTimestampRoot);
        }
		private bool VerifyCounterSignature (PKCS7.SignerInfo cs, byte[] signature) 
		{
			// SEQUENCE {
			//   INTEGER 1
			if (cs.Version != 1)
				return false;
			//   SEQUENCE {
			//      SEQUENCE {

			string contentType = null;
			ASN1 messageDigest = null;
			for (int i=0; i < cs.AuthenticatedAttributes.Count; i++) {
				// SEQUENCE {
				//   OBJECT IDENTIFIER
				ASN1 attr = (ASN1) cs.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.2.840.113549.1.9.5":
						// SEQUENCE {
						//   OBJECT IDENTIFIER
						//     signingTime (1 2 840 113549 1 9 5)
						//   SET {
						//     UTCTime '030124013651Z'
						//   }
						// }
						timestamp = ASN1Convert.ToDateTime (attr[1][0]);
						break;
					default:
						break;
				}
			}

			if (contentType != PKCS7.Oid.data) 
				return false;

			// verify message digest
			if (messageDigest == null)
				return false;
			// TODO: must be read from the ASN.1 structure
			string hashName = null;
			switch (messageDigest.Length) {
				case 16:
					hashName = "MD5";
					break;
				case 20:
					hashName = "SHA1";
					break;
			}
			HashAlgorithm ha = HashAlgorithm.Create (hashName);
			if (!messageDigest.CompareValue (ha.ComputeHash (signature)))
				return false;

			// verify signature
			byte[] counterSignature = cs.Signature;
			string hashOID = CryptoConfig.MapNameToOID (hashName);

			// change to SET OF (not [0]) as per PKCS #7 1.5
			ASN1 aa = new ASN1 (0x31);
			foreach (ASN1 a in cs.AuthenticatedAttributes)
				aa.Add (a);
			byte[] p7hash = ha.ComputeHash (aa.GetBytes ());

			// we need to try all certificates
			string issuer = cs.IssuerName;
			byte[] serial = cs.SerialNumber;
			foreach (X509Certificate x509 in coll) {
				if (CompareIssuerSerial (issuer, serial, x509)) {
					// don't verify if key size don't match
					if (x509.PublicKey.Length > (counterSignature.Length >> 3)) {
						RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA;
						if (rsa.VerifyHash (p7hash, hashOID, counterSignature)) {
							timestampChain.LoadCertificates (coll);
							return (timestampChain.Build (x509));
						}
					}
				}
			}
			// no certificate can verify this signature!
			return false;
		}