コード例 #1
0
        protected override void Encode()
        {
            ASN1 asn = new ASN1(48);

            if (this.cA)
            {
                asn.Add(new ASN1(1, new byte[]
                {
                    byte.MaxValue
                }));
            }
            if (this.cA && this.pathLenConstraint >= 0)
            {
                asn.Add(ASN1Convert.FromInt32(this.pathLenConstraint));
            }
            this.extnValue = new ASN1(4);
            this.extnValue.Add(asn);
        }
コード例 #2
0
        protected override void Encode()
        {
            ASN1 aSN = new ASN1(48);

            if (cA)
            {
                aSN.Add(new ASN1(1, new byte[1]
                {
                    255
                }));
            }
            if (cA && pathLenConstraint >= 0)
            {
                aSN.Add(ASN1Convert.FromInt32(pathLenConstraint));
            }
            extnValue = new ASN1(4);
            extnValue.Add(aSN);
        }
コード例 #3
0
        internal byte[] Encode()
        {
            ASN1 asn = new ASN1(48);

            foreach (Oid oid in this._enhKeyUsage)
            {
                asn.Add(ASN1Convert.FromOid(oid.Value));
            }
            return(asn.GetBytes());
        }
コード例 #4
0
        internal byte[] Encode()
        {
            ASN1 ex = new ASN1(0x30);

            foreach (Oid oid in _enhKeyUsage)
            {
                ex.Add(ASN1Convert.FromOid(oid.Value));
            }
            return(ex.GetBytes());
        }
コード例 #5
0
        private ASN1 Attribute(string oid, ASN1 value)
        {
            ASN1 asn = new ASN1(48);

            asn.Add(ASN1Convert.FromOid(oid));
            ASN1 asn2 = asn.Add(new ASN1(49));

            asn2.Add(value);
            return(asn);
        }
コード例 #6
0
        private ASN1 Attribute(string oid, ASN1 value)
        {
            ASN1 attr = new ASN1(0x30);

            attr.Add(ASN1Convert.FromOid(oid));
            ASN1 aset = attr.Add(new ASN1(0x31));

            aset.Add(value);
            return(attr);
        }
コード例 #7
0
		protected override void Encode () 
		{
			ASN1 seq = new ASN1 (0x30);
			foreach (string oid in keyPurpose) {
				seq.Add (ASN1Convert.FromOid (oid));
			}

			extnValue = new ASN1 (0x04);
			extnValue.Add (seq);
		}
コード例 #8
0
        private ASN1 Attribute(string oid, ASN1 value)
        {
            ASN1 aSN = new ASN1(48);

            aSN.Add(ASN1Convert.FromOid(oid));
            ASN1 aSN2 = aSN.Add(new ASN1(49));

            aSN2.Add(value);
            return(aSN);
        }
コード例 #9
0
ファイル: PKCS8.cs プロジェクト: msruzy/digimon-linkz-client
            public static byte[] Encode(RSA rsa)
            {
                RSAParameters rsaparameters = rsa.ExportParameters(true);
                ASN1          asn           = new ASN1(48);

                asn.Add(new ASN1(2, new byte[1]));
                asn.Add(ASN1Convert.FromUnsignedBigInteger(rsaparameters.Modulus));
                asn.Add(ASN1Convert.FromUnsignedBigInteger(rsaparameters.Exponent));
                asn.Add(ASN1Convert.FromUnsignedBigInteger(rsaparameters.D));
                asn.Add(ASN1Convert.FromUnsignedBigInteger(rsaparameters.P));
                asn.Add(ASN1Convert.FromUnsignedBigInteger(rsaparameters.Q));
                asn.Add(ASN1Convert.FromUnsignedBigInteger(rsaparameters.DP));
                asn.Add(ASN1Convert.FromUnsignedBigInteger(rsaparameters.DQ));
                asn.Add(ASN1Convert.FromUnsignedBigInteger(rsaparameters.InverseQ));
                return(asn.GetBytes());
            }
コード例 #10
0
            public static byte[] Encode(RSA rsa)
            {
                RSAParameters rSAParameters = rsa.ExportParameters(includePrivateParameters: true);
                ASN1          aSN           = new ASN1(48);

                aSN.Add(new ASN1(2, new byte[1]));
                aSN.Add(ASN1Convert.FromUnsignedBigInteger(rSAParameters.Modulus));
                aSN.Add(ASN1Convert.FromUnsignedBigInteger(rSAParameters.Exponent));
                aSN.Add(ASN1Convert.FromUnsignedBigInteger(rSAParameters.D));
                aSN.Add(ASN1Convert.FromUnsignedBigInteger(rSAParameters.P));
                aSN.Add(ASN1Convert.FromUnsignedBigInteger(rSAParameters.Q));
                aSN.Add(ASN1Convert.FromUnsignedBigInteger(rSAParameters.DP));
                aSN.Add(ASN1Convert.FromUnsignedBigInteger(rSAParameters.DQ));
                aSN.Add(ASN1Convert.FromUnsignedBigInteger(rSAParameters.InverseQ));
                return(aSN.GetBytes());
            }
コード例 #11
0
        protected override void Encode()
        {
            extnValue = new ASN1(4);
            ushort num = (ushort)kubits;
            byte   b   = 16;

            if (num > 0)
            {
                b = 15;
                while (b > 0 && (num & 0x8000) != 32768)
                {
                    num = (ushort)(num << 1);
                    b   = (byte)(b - 1);
                }
                if (kubits > 255)
                {
                    b = (byte)(b - 8);
                    extnValue.Add(new ASN1(3, new byte[3]
                    {
                        b,
                        (byte)kubits,
                        (byte)(kubits >> 8)
                    }));
                }
                else
                {
                    extnValue.Add(new ASN1(3, new byte[2]
                    {
                        b,
                        (byte)kubits
                    }));
                }
            }
            else
            {
                extnValue.Add(new ASN1(3, new byte[2]
                {
                    7,
                    0
                }));
            }
        }
コード例 #12
0
        /* 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);
        }
コード例 #13
0
        /// <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();
        }
コード例 #14
0
        /// <summary>
        /// Encodes the value of the extension to ASN.1.
        /// </summary>
        protected override void Encode()
        {
            var asn1 = new ASN1(0x04);

            if (ExtensionValue != null)
            {
                asn1.Add(new ASN1(0x04, _extensionValue));
            }

            extnValue = asn1;
        }
コード例 #15
0
ファイル: X509Extensions.cs プロジェクト: waffle-iron/nequeo
		public byte[] GetBytes () 
		{
			if (InnerList.Count < 1)
				return null;
			ASN1 sequence = new ASN1 (0x30);
			for (int i=0; i < InnerList.Count; i++) {
				X509Extension x = (X509Extension) InnerList [i];
				sequence.Add (x.ASN1);
			}
			return sequence.GetBytes ();
		}
コード例 #16
0
        // Class { Class { Class { OctetStream } } }
        public byte [] ProcessSpnegoProcessContextToken(string user, string pass)
        {
            ASN1 asn  = new ASN1(0xA1);
            ASN1 asn2 = new ASN1(0x30);
            ASN1 asn3 = new ASN1(0xA2);

            asn3.Add(new ASN1(0x04, ProcessMessageType3(user, pass)));
            asn2.Add(asn3);
            asn.Add(asn2);
            return(asn.GetBytes());
        }
コード例 #17
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());
        }
コード例 #18
0
        protected override void Encode()
        {
            ASN1 aSN = new ASN1(48);

            foreach (string item in keyPurpose)
            {
                aSN.Add(ASN1Convert.FromOid(item));
            }
            extnValue = new ASN1(4);
            extnValue.Add(aSN);
        }
コード例 #19
0
        protected override void Encode()
        {
            ASN1 asn = new ASN1(48);

            foreach (object obj in this.keyPurpose)
            {
                string oid = (string)obj;
                asn.Add(ASN1Convert.FromOid(oid));
            }
            this.extnValue = new ASN1(4);
            this.extnValue.Add(asn);
        }
コード例 #20
0
        protected override void Encode()
        {
            if (ski == null)
            {
                throw new InvalidOperationException("Invalid SubjectKeyIdentifier extension");
            }

            var seq = new ASN1(0x04, ski);

            extnValue = new ASN1(0x04);
            extnValue.Add(seq);
        }
コード例 #21
0
 public bool Timestamp(string fileName)
 {
     try
     {
         AuthenticodeDeformatter authenticodeDeformatter = new AuthenticodeDeformatter(fileName);
         byte[] signature = authenticodeDeformatter.Signature;
         if (signature != null)
         {
             Open(fileName);
             PKCS7.ContentInfo contentInfo = new PKCS7.ContentInfo(signature);
             pkcs7 = new PKCS7.SignedData(contentInfo.Content);
             byte[] bytes = Timestamp(pkcs7.SignerInfo.Signature);
             ASN1   aSN   = new ASN1(Convert.FromBase64String(Encoding.ASCII.GetString(bytes)));
             ASN1   aSN2  = new ASN1(signature);
             ASN1   aSN3  = aSN2.Element(1, 160);
             if (aSN3 == null)
             {
                 return(false);
             }
             ASN1 aSN4 = aSN3.Element(0, 48);
             if (aSN4 == null)
             {
                 return(false);
             }
             ASN1 aSN5 = aSN4.Element(3, 160);
             if (aSN5 == null)
             {
                 aSN5 = new ASN1(160);
                 aSN4.Add(aSN5);
             }
             for (int i = 0; i < aSN[1][0][3].Count; i++)
             {
                 aSN5.Add(aSN[1][0][3][i]);
             }
             ASN1 aSN6 = aSN4[aSN4.Count - 1];
             ASN1 aSN7 = aSN6[0];
             ASN1 aSN8 = aSN7[aSN7.Count - 1];
             if (aSN8.Tag != 161)
             {
                 aSN8 = new ASN1(161);
                 aSN7.Add(aSN8);
             }
             aSN8.Add(Attribute("1.2.840.113549.1.9.6", aSN[1][0][4][0]));
             return(Save(fileName, aSN2.GetBytes()));
         }
     }
     catch (Exception value)
     {
         Console.WriteLine(value);
     }
     return(false);
 }
コード例 #22
0
 public bool Timestamp(string fileName)
 {
     try
     {
         AuthenticodeDeformatter authenticodeDeformatter = new AuthenticodeDeformatter(fileName);
         byte[] signature = authenticodeDeformatter.Signature;
         if (signature != null)
         {
             base.Open(fileName);
             PKCS7.ContentInfo contentInfo = new PKCS7.ContentInfo(signature);
             this.pkcs7 = new PKCS7.SignedData(contentInfo.Content);
             byte[] bytes = this.Timestamp(this.pkcs7.SignerInfo.Signature);
             ASN1   asn   = new ASN1(Convert.FromBase64String(Encoding.ASCII.GetString(bytes)));
             ASN1   asn2  = new ASN1(signature);
             ASN1   asn3  = asn2.Element(1, 160);
             if (asn3 == null)
             {
                 return(false);
             }
             ASN1 asn4 = asn3.Element(0, 48);
             if (asn4 == null)
             {
                 return(false);
             }
             ASN1 asn5 = asn4.Element(3, 160);
             if (asn5 == null)
             {
                 asn5 = new ASN1(160);
                 asn4.Add(asn5);
             }
             for (int i = 0; i < asn[1][0][3].Count; i++)
             {
                 asn5.Add(asn[1][0][3][i]);
             }
             ASN1 asn6 = asn4[asn4.Count - 1];
             ASN1 asn7 = asn6[0];
             ASN1 asn8 = asn7[asn7.Count - 1];
             if (asn8.Tag != 161)
             {
                 asn8 = new ASN1(161);
                 asn7.Add(asn8);
             }
             asn8.Add(this.Attribute("1.2.840.113549.1.9.6", asn[1][0][4][0]));
             return(this.Save(fileName, asn2.GetBytes()));
         }
     }
     catch (Exception value)
     {
         Console.WriteLine(value);
     }
     return(false);
 }
コード例 #23
0
        protected override ASN1 ToBeSigned(string oid)
        {
            ASN1 asn = new ASN1(48);

            if (this.version > 1)
            {
                byte[] data = new byte[]
                {
                    this.version - 1
                };
                ASN1 asn2 = asn.Add(new ASN1(160));
                asn2.Add(new ASN1(2, data));
            }
            asn.Add(new ASN1(2, this.sn));
            asn.Add(PKCS7.AlgorithmIdentifier(oid));
            asn.Add(X501.FromString(this.issuer));
            ASN1 asn3 = asn.Add(new ASN1(48));

            asn3.Add(ASN1Convert.FromDateTime(this.notBefore));
            asn3.Add(ASN1Convert.FromDateTime(this.notAfter));
            asn.Add(X501.FromString(this.subject));
            asn.Add(this.SubjectPublicKeyInfo());
            if (this.version > 1)
            {
                if (this.issuerUniqueID != null)
                {
                    asn.Add(new ASN1(161, this.UniqueIdentifier(this.issuerUniqueID)));
                }
                if (this.subjectUniqueID != null)
                {
                    asn.Add(new ASN1(161, this.UniqueIdentifier(this.subjectUniqueID)));
                }
                if (this.version > 2 && this.extensions.Count > 0)
                {
                    asn.Add(new ASN1(163, this.extensions.GetBytes()));
                }
            }
            return(asn);
        }
コード例 #24
0
        protected override void Encode()
        {
            ASN1 seq = new ASN1(0x30);

            if (aki == null)
            {
                throw new InvalidOperationException("Invalid AuthorityKeyIdentifier extension");
            }

            seq.Add(new ASN1(0x80, aki));
            extnValue = new ASN1(0x04);
            extnValue.Add(seq);
        }
コード例 #25
0
        protected override ASN1 ToBeSigned(string oid)
        {
            ASN1 aSN = new ASN1(48);

            if (version > 1)
            {
                byte[] data = new byte[1]
                {
                    (byte)(version - 1)
                };
                ASN1 aSN2 = aSN.Add(new ASN1(160));
                aSN2.Add(new ASN1(2, data));
            }
            aSN.Add(new ASN1(2, sn));
            aSN.Add(PKCS7.AlgorithmIdentifier(oid));
            aSN.Add(X501.FromString(issuer));
            ASN1 aSN3 = aSN.Add(new ASN1(48));

            aSN3.Add(ASN1Convert.FromDateTime(notBefore));
            aSN3.Add(ASN1Convert.FromDateTime(notAfter));
            aSN.Add(X501.FromString(subject));
            aSN.Add(SubjectPublicKeyInfo());
            if (version > 1)
            {
                if (issuerUniqueID != null)
                {
                    aSN.Add(new ASN1(161, UniqueIdentifier(issuerUniqueID)));
                }
                if (subjectUniqueID != null)
                {
                    aSN.Add(new ASN1(161, UniqueIdentifier(subjectUniqueID)));
                }
                if (version > 2 && extensions.Count > 0)
                {
                    aSN.Add(new ASN1(163, extensions.GetBytes()));
                }
            }
            return(aSN);
        }
コード例 #26
0
        protected override ASN1 ToBeSigned(string oid)
        {
            ASN1 asN1_1 = new ASN1((byte)48);

            if (this.version > (byte)1)
            {
                byte[] data = new byte[1]
                {
                    (byte)((uint)this.version - 1U)
                };
                asN1_1.Add(new ASN1((byte)160)).Add(new ASN1((byte)2, data));
            }
            asN1_1.Add(new ASN1((byte)2, this.sn));
            asN1_1.Add(PKCS7.AlgorithmIdentifier(oid));
            asN1_1.Add(X501.FromString(this.issuer));
            ASN1 asN1_2 = asN1_1.Add(new ASN1((byte)48));

            asN1_2.Add(ASN1Convert.FromDateTime(this.notBefore));
            asN1_2.Add(ASN1Convert.FromDateTime(this.notAfter));
            asN1_1.Add(X501.FromString(this.subject));
            asN1_1.Add(this.SubjectPublicKeyInfo());
            if (this.version > (byte)1)
            {
                if (this.issuerUniqueID != null)
                {
                    asN1_1.Add(new ASN1((byte)161, this.UniqueIdentifier(this.issuerUniqueID)));
                }
                if (this.subjectUniqueID != null)
                {
                    asN1_1.Add(new ASN1((byte)161, this.UniqueIdentifier(this.subjectUniqueID)));
                }
                if (this.version > (byte)2 && this.extensions.Count > 0)
                {
                    asN1_1.Add(new ASN1((byte)163, this.extensions.GetBytes()));
                }
            }
            return(asN1_1);
        }
コード例 #27
0
  ///
  /// 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();
  }
コード例 #28
0
        private byte[] Header(byte[] fileHash, string hashAlgorithm)
        {
            string hashOid = CryptoConfig.MapNameToOID(hashAlgorithm);
            ASN1   content = new ASN1(0x30);
            ASN1   c1      = content.Add(new ASN1(0x30));

            c1.Add(ASN1Convert.FromOid(spcPelmageData));
            c1.Add(new ASN1(0x30, obsolete));
            ASN1 c2 = content.Add(new ASN1(0x30));

            c2.Add(AlgorithmIdentifier(hashOid));
            c2.Add(new ASN1(0x04, fileHash));

            pkcs7.HashName = hashAlgorithm;
            pkcs7.Certificates.AddRange(certs);
            pkcs7.ContentInfo.ContentType = spcIndirectDataContext;
            pkcs7.ContentInfo.Content.Add(content);

            pkcs7.SignerInfo.Certificate = certs [0];
            pkcs7.SignerInfo.Key         = rsa;

            ASN1 opus = null;

            if (url == null)
            {
                opus = Attribute(spcSpOpusInfo, Opus(description, null));
            }
            else
            {
                opus = Attribute(spcSpOpusInfo, Opus(description, url.ToString()));
            }
            pkcs7.SignerInfo.AuthenticatedAttributes.Add(opus);
            // When using the MS Root Agency (test) we can't include this attribute in the signature or it won't validate!
            // pkcs7.SignerInfo.AuthenticatedAttributes.Add (Attribute (spcStatementType, new ASN1 (0x30, ASN1Convert.FromOid (commercialCodeSigning).GetBytes ())));
            pkcs7.GetASN1();              // sign
            return(pkcs7.SignerInfo.Signature);
        }
コード例 #29
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());
            }
コード例 #30
0
        public byte[] GetBytes()
        {
            if (this.InnerList.Count < 1)
            {
                return((byte[])null);
            }
            ASN1 asN1 = new ASN1((byte)48);

            for (int index = 0; index < this.InnerList.Count; ++index)
            {
                X509Extension inner = (X509Extension)this.InnerList[index];
                asN1.Add(inner.ASN1);
            }
            return(asN1.GetBytes());
        }
コード例 #31
0
		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;
		}
コード例 #32
0
            internal ASN1 GetASN1(byte encoding)
            {
                byte encode = encoding;
                if (encode == 0xFF)
                    encode = SelectBestEncoding();

                ASN1 asn1 = new ASN1(0x30);
                asn1.Add(ASN1Convert.FromOid(oid));
                switch (encode)
                {
                    case 0x13:
                        // PRINTABLESTRING
                        asn1.Add(new ASN1(0x13, Encoding.ASCII.GetBytes(attrValue)));
                        break;
                    case 0x16:
                        // IA5STRING
                        asn1.Add(new ASN1(0x16, Encoding.ASCII.GetBytes(attrValue)));
                        break;
                    case 0x1E:
                        // BMPSTRING
                        asn1.Add(new ASN1(0x1E, Encoding.BigEndianUnicode.GetBytes(attrValue)));
                        break;
                }
                return asn1;
            }
コード例 #33
0
		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 ();
		}
コード例 #34
0
ファイル: PKCS1.cs プロジェクト: Jakosa/MonoLibraries
		// 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;
		}
コード例 #35
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 ();
			}
コード例 #36
0
		/* 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;
		}
コード例 #37
0
		protected override ASN1 ToBeSigned (string oid) 
		{
			// TBSCertificate
			ASN1 tbsCert = new ASN1 (0x30);

			if (version > 1) {
				// TBSCertificate / [0] Version DEFAULT v1,
				byte[] ver = { (byte)(version - 1) };
				ASN1 v = tbsCert.Add (new ASN1 (0xA0));
				v.Add (new ASN1 (0x02, ver));
			}

			// TBSCertificate / CertificateSerialNumber,
			tbsCert.Add (new ASN1 (0x02, sn));

			// TBSCertificate / AlgorithmIdentifier,
                        tbsCert.Add (PKCS7.AlgorithmIdentifier (oid));

			// TBSCertificate / Name
			tbsCert.Add (X501.FromString (issuer));

			// TBSCertificate / Validity
			ASN1 validity = tbsCert.Add (new ASN1 (0x30));
			// TBSCertificate / Validity / Time
			validity.Add (ASN1Convert.FromDateTime (notBefore));
			// TBSCertificate / Validity / Time
			validity.Add (ASN1Convert.FromDateTime (notAfter));

			// TBSCertificate / Name
			tbsCert.Add (X501.FromString (subject));

			// TBSCertificate / SubjectPublicKeyInfo
			tbsCert.Add (SubjectPublicKeyInfo ());
                        
			if (version > 1) {
				// TBSCertificate / [1]  IMPLICIT UniqueIdentifier OPTIONAL
				if (issuerUniqueID != null)
					tbsCert.Add (new ASN1 (0xA1, UniqueIdentifier (issuerUniqueID)));

				// TBSCertificate / [2]  IMPLICIT UniqueIdentifier OPTIONAL
				if (subjectUniqueID != null)
					tbsCert.Add (new ASN1 (0xA1, UniqueIdentifier (subjectUniqueID)));

				// TBSCertificate / [3]  Extensions OPTIONAL
				if ((version > 2) &&  (extensions.Count > 0))
					tbsCert.Add (new ASN1 (0xA3, extensions.GetBytes ()));
			}

			return tbsCert;
		}
コード例 #38
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 ();
			}
コード例 #39
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 ();
		}
コード例 #40
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 ();
			}
コード例 #41
0
		//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);
		}
コード例 #42
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 ();
			}
コード例 #43
0
		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;
		}
コード例 #44
0
ファイル: X500DistinguishedName.cs プロジェクト: ANahr/mono
		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 {
				var 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);
			}
		}
コード例 #45
0
		internal byte[] Encode ()
		{
			ASN1 ex = new ASN1 (0x30);
			foreach (Oid oid in _enhKeyUsage) {
				ex.Add (ASN1Convert.FromOid (oid.Value));
			}
			return ex.GetBytes ();
		}