Example #1
0
            public int Compare(object x, object y)
            {
                if (x == null)
                {
                    return((y != null) ? -1 : 0);
                }
                if (y == null)
                {
                    return(1);
                }
                ASN1 asn  = x as ASN1;
                ASN1 asn2 = y as ASN1;

                if (asn == null || asn2 == null)
                {
                    throw new ArgumentException(Locale.GetText("Invalid objects."));
                }
                byte[] bytes  = asn.GetBytes();
                byte[] bytes2 = asn2.GetBytes();
                for (int i = 0; i < bytes.Length; i++)
                {
                    if (i == bytes2.Length)
                    {
                        break;
                    }
                    if (bytes[i] != bytes2[i])
                    {
                        return((bytes[i] >= bytes2[i]) ? 1 : -1);
                    }
                }
                if (bytes.Length > bytes2.Length)
                {
                    return(1);
                }
                if (bytes.Length < bytes2.Length)
                {
                    return(-1);
                }
                return(0);
            }
Example #2
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();
  }
Example #3
0
            public bool VerifySignature(AsymmetricAlgorithm aa)
            {
                if (aa == null)
                {
                    return(false);
                }

                RSAPKCS1SignatureDeformatter r = new RSAPKCS1SignatureDeformatter(aa);

                r.SetHashAlgorithm(hashAlgorithm);
                HashAlgorithm ha = HashAlgorithm.Create(hashAlgorithm);

                byte[] signature = signerInfo.Signature;
                byte[] hash      = null;

                if (mda)
                {
                    ASN1 asn = new ASN1(0x31);
                    foreach (ASN1 attr in signerInfo.AuthenticatedAttributes)
                    {
                        asn.Add(attr);
                    }

                    hash = ha.ComputeHash(asn.GetBytes());
                }
                else
                {
                    hash = ha.ComputeHash(contentInfo.Content[0].Value);
                }

                if (hash != null && signature != null)
                {
                    return(r.VerifySignature(hash, signature));
                }
                return(false);
            }
Example #4
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 ();
		}
Example #5
0
        public virtual byte[] GetBytes()
        {
            byte[] array = null;
            if (this.Count > 0)
            {
                int       num       = 0;
                ArrayList arrayList = new ArrayList();
                foreach (object obj in this.elist)
                {
                    ASN1   asn   = (ASN1)obj;
                    byte[] bytes = asn.GetBytes();
                    arrayList.Add(bytes);
                    num += bytes.Length;
                }
                array = new byte[num];
                int num2 = 0;
                for (int i = 0; i < this.elist.Count; i++)
                {
                    byte[] array2 = (byte[])arrayList[i];
                    Buffer.BlockCopy(array2, 0, array, num2, array2.Length);
                    num2 += array2.Length;
                }
            }
            else if (this.m_aValue != null)
            {
                array = this.m_aValue;
            }
            int num3 = 0;

            byte[] array3;
            if (array != null)
            {
                int num4 = array.Length;
                if (num4 > 127)
                {
                    if (num4 <= 255)
                    {
                        array3 = new byte[3 + num4];
                        Buffer.BlockCopy(array, 0, array3, 3, num4);
                        num3      = 129;
                        array3[2] = (byte)num4;
                    }
                    else if (num4 <= 65535)
                    {
                        array3 = new byte[4 + num4];
                        Buffer.BlockCopy(array, 0, array3, 4, num4);
                        num3      = 130;
                        array3[2] = (byte)(num4 >> 8);
                        array3[3] = (byte)num4;
                    }
                    else if (num4 <= 16777215)
                    {
                        array3 = new byte[5 + num4];
                        Buffer.BlockCopy(array, 0, array3, 5, num4);
                        num3      = 131;
                        array3[2] = (byte)(num4 >> 16);
                        array3[3] = (byte)(num4 >> 8);
                        array3[4] = (byte)num4;
                    }
                    else
                    {
                        array3 = new byte[6 + num4];
                        Buffer.BlockCopy(array, 0, array3, 6, num4);
                        num3      = 132;
                        array3[2] = (byte)(num4 >> 24);
                        array3[3] = (byte)(num4 >> 16);
                        array3[4] = (byte)(num4 >> 8);
                        array3[5] = (byte)num4;
                    }
                }
                else
                {
                    array3 = new byte[2 + num4];
                    Buffer.BlockCopy(array, 0, array3, 2, num4);
                    num3 = num4;
                }
                if (this.m_aValue == null)
                {
                    this.m_aValue = array;
                }
            }
            else
            {
                array3 = new byte[2];
            }
            array3[0] = this.m_nTag;
            array3[1] = (byte)num3;
            return(array3);
        }
Example #6
0
		public virtual byte[] Sign (DSA key) 
		{
			string oid = "1.2.840.10040.4.3";
			ASN1 tbs = ToBeSigned (oid);
			HashAlgorithm ha = HashAlgorithm.Create (hashName);
			if (!(ha is SHA1))
				throw new NotSupportedException ("Only SHA-1 is supported for DSA");
			byte[] hash = ha.ComputeHash (tbs.GetBytes ());

			DSASignatureFormatter dsa = new DSASignatureFormatter (key);
			dsa.SetHashAlgorithm (hashName);
			byte[] rs = dsa.CreateSignature (hash);

			// split R and S
			byte[] r = new byte [20];
			Buffer.BlockCopy (rs, 0, r, 0, 20);
			byte[] s = new byte [20];
			Buffer.BlockCopy (rs, 20, s, 0, 20);
			ASN1 signature = new ASN1 (0x30);
			signature.Add (new ASN1 (0x02, r));
			signature.Add (new ASN1 (0x02, s));

			// dsaWithSha1 (1 2 840 10040 4 3)
			return Build (tbs, oid, signature.GetBytes ());
		}
Example #7
0
		public bool Sign (string fileName) 
		{
			try {
				Open (fileName);

				HashAlgorithm hash = HashAlgorithm.Create (Hash);
				// 0 to 215 (216) then skip 4 (checksum)

				byte[] digest = GetHash (hash);
				byte[] signature = Header (digest, Hash);
				if (timestamp != null) {
					byte[] ts = Timestamp (signature);
					// add timestamp information inside the current pkcs7 SignedData instance
					// (this is possible because the data isn't yet signed)
					ProcessTimestamp (ts);
				}

				PKCS7.ContentInfo sign = new PKCS7.ContentInfo (signedData);
				sign.Content.Add (pkcs7.ASN1);
				authenticode = sign.ASN1;
				Close ();

				return Save (fileName, authenticode.GetBytes ());
			}
			catch (Exception e) {
				Console.WriteLine (e);
			}
			return false;
		}
		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 ();
		}
		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 ();
		}
		public void ConvertOID_LargeX () 
		{
			ASN1 asn = new ASN1 (0x06, new byte [] { 0xA8, 0x00, 0x00 });
			string oid = ASN1Convert.ToOid (asn);
			Assert.AreEqual ("2.88.0.0", oid, "ToOID");
			Assert.AreEqual (BitConverter.ToString (asn.GetBytes ()),
				BitConverter.ToString (ASN1Convert.FromOid (oid).GetBytes ()), "FromOID");
		}
Example #11
0
			public bool VerifySignature (AsymmetricAlgorithm aa)
			{
				if (aa == null) {
					return false;
				}

				RSAPKCS1SignatureDeformatter r = new RSAPKCS1SignatureDeformatter (aa);
				r.SetHashAlgorithm (hashAlgorithm);
				HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm);

				byte[] signature = signerInfo.Signature;
				byte[] hash = null;

				if (mda) {
					ASN1 asn = new ASN1 (0x31);
					foreach (ASN1 attr in signerInfo.AuthenticatedAttributes)
						asn.Add (attr);

					hash = ha.ComputeHash (asn.GetBytes ());
				} else {
					hash = ha.ComputeHash (contentInfo.Content[0].Value);
				}

				if (hash != null && signature != null) {
					return r.VerifySignature (hash, signature);
				}
				return false;
			}
Example #12
0
            internal ASN1 GetASN1()
            {
                if (this.key == null || this.hashAlgorithm == null)
                {
                    return(null);
                }
                byte[] data = new byte[]
                {
                    this.version
                };
                ASN1 asn = new ASN1(48);

                asn.Add(new ASN1(2, data));
                asn.Add(PKCS7.IssuerAndSerialNumber(this.x509));
                string oid = CryptoConfig.MapNameToOID(this.hashAlgorithm);

                asn.Add(PKCS7.AlgorithmIdentifier(oid));
                ASN1 asn2 = null;

                if (this.authenticatedAttributes.Count > 0)
                {
                    asn2 = asn.Add(new ASN1(160));
                    this.authenticatedAttributes.Sort(new PKCS7.SortedSet());
                    foreach (object obj in this.authenticatedAttributes)
                    {
                        ASN1 asn3 = (ASN1)obj;
                        asn2.Add(asn3);
                    }
                }
                if (this.key is RSA)
                {
                    asn.Add(PKCS7.AlgorithmIdentifier("1.2.840.113549.1.1.1"));
                    if (asn2 != null)
                    {
                        RSAPKCS1SignatureFormatter rsapkcs1SignatureFormatter = new RSAPKCS1SignatureFormatter(this.key);
                        rsapkcs1SignatureFormatter.SetHashAlgorithm(this.hashAlgorithm);
                        byte[] bytes = asn2.GetBytes();
                        bytes[0] = 49;
                        HashAlgorithm hashAlgorithm = HashAlgorithm.Create(this.hashAlgorithm);
                        byte[]        rgbHash       = hashAlgorithm.ComputeHash(bytes);
                        this.signature = rsapkcs1SignatureFormatter.CreateSignature(rgbHash);
                    }
                    asn.Add(new ASN1(4, this.signature));
                    if (this.unauthenticatedAttributes.Count > 0)
                    {
                        ASN1 asn4 = asn.Add(new ASN1(161));
                        this.unauthenticatedAttributes.Sort(new PKCS7.SortedSet());
                        foreach (object obj2 in this.unauthenticatedAttributes)
                        {
                            ASN1 asn5 = (ASN1)obj2;
                            asn4.Add(asn5);
                        }
                    }
                    return(asn);
                }
                if (this.key is DSA)
                {
                    throw new NotImplementedException("not yet");
                }
                throw new CryptographicException("Unknown assymetric algorithm");
            }
Example #13
0
		// Class(60) {
		//   OID(spnego),
		//   Class(A0) {
		//     Class(30) {
		//       Class(A0) {
		//         Class(30) { OID,OID,OID} },
		//       Class(A2) { OctetStream } } } }
		public byte [] ProcessSpnegoInitialContextTokenRequest ()
		{
			Type1Message type1 = new Type1Message (NtlmVersion.Version3);
			type1.Flags = unchecked ((NtlmFlags) 0xE21882B7);
			type1.Domain = "WORKGROUP"; // FIXME: remove it

			ASN1 asn = new ASN1 (0x60);
			ASN1 asn2 = new ASN1 (0xA0);
			ASN1 asn21 = new ASN1 (0x30);
			ASN1 asn211 = new ASN1 (0xA0);
			ASN1 asn2111 = new ASN1 (0x30);
			asn211.Add (asn2111);
			asn2111.Add (ASN1Convert.FromOid (Constants.OidNtlmSsp));
			asn2111.Add (ASN1Convert.FromOid (Constants.OidKerberos5));
			asn2111.Add (ASN1Convert.FromOid (Constants.OidMIT));
			ASN1 asn212 = new ASN1 (0xA2);
			ASN1 asn2121 = new ASN1 (0x4);
			asn2121.Value = type1.GetBytes ();
			asn212.Add (asn2121);
			asn21.Add (asn211);
			asn21.Add (asn212);
			asn2.Add (asn21);
			asn.Add (ASN1Convert.FromOid (Constants.OidSpnego));
			asn.Add (asn2);
			return asn.GetBytes ();
		}
Example #14
0
                /*
		 * SafeContents ::= SEQUENCE OF SafeBag
		 * 
		 * SafeBag ::= SEQUENCE {
		 *	bagId BAG-TYPE.&id ({PKCS12BagSet}),
		 *	bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}),
		 *	bagAttributes SET OF PKCS12Attribute OPTIONAL
		 * }
		 */
		public byte[] GetBytes () 
		{
			// TODO (incomplete)
			ASN1 safeBagSequence = new ASN1 (0x30);

			// Sync Safe Bag list since X509CertificateCollection may be updated
			ArrayList scs = new ArrayList ();
			foreach (SafeBag sb in _safeBags) {
				if (sb.BagOID.Equals (certBag)) {
					ASN1 safeBag = sb.ASN1;
					ASN1 bagValue = safeBag [1];
					PKCS7.ContentInfo cert = new PKCS7.ContentInfo (bagValue.Value);
					scs.Add (new X509Certificate (cert.Content [0].Value));
				}
			}

			ArrayList addcerts = new ArrayList ();
			ArrayList removecerts = new ArrayList ();

			foreach (X509Certificate c in Certificates) {
				bool found = false;

				foreach (X509Certificate lc in scs) {
					if (Compare (c.RawData, lc.RawData)) {
						found = true;
					}
				}

				if (!found) {
					addcerts.Add (c);
				}
			}
			foreach (X509Certificate c in scs) {
				bool found = false;

				foreach (X509Certificate lc in Certificates) {
					if (Compare (c.RawData, lc.RawData)) {
						found = true;
					}
				}

				if (!found) {
					removecerts.Add (c);
				}
			}

			foreach (X509Certificate c in removecerts) {
				RemoveCertificate (c);
			}

			foreach (X509Certificate c in addcerts) {
				AddCertificate (c);
			}
			// Sync done

			if (_safeBags.Count > 0) {
				ASN1 certsSafeBag = new ASN1 (0x30);
				foreach (SafeBag sb in _safeBags) {
					if (sb.BagOID.Equals (certBag)) {
						certsSafeBag.Add (sb.ASN1);
					}
				}

				if (certsSafeBag.Count > 0) {
					byte[] certsSalt = new byte [8];
					RNG.GetBytes (certsSalt);

					ASN1 seqParams = new ASN1 (0x30);
					seqParams.Add (new ASN1 (0x04, certsSalt));
					seqParams.Add (ASN1Convert.FromInt32 (_iterations));

					ASN1 seqPbe = new ASN1 (0x30);
					seqPbe.Add (ASN1Convert.FromOid (pbeWithSHAAnd3KeyTripleDESCBC));
					seqPbe.Add (seqParams);

					byte[] encrypted = Encrypt (pbeWithSHAAnd3KeyTripleDESCBC, certsSalt, _iterations, certsSafeBag.GetBytes ());
					ASN1 encryptedCerts = new ASN1 (0x80, encrypted);

					ASN1 seq = new ASN1 (0x30);
					seq.Add (ASN1Convert.FromOid (PKCS7.Oid.data));
					seq.Add (seqPbe);
					seq.Add (encryptedCerts);

					ASN1 certsVersion = new ASN1 (0x02, new byte [1] { 0x00 });
					ASN1 encData = new ASN1 (0x30);
					encData.Add (certsVersion);
					encData.Add (seq);

					ASN1 certsContent = new ASN1 (0xA0);
					certsContent.Add (encData);

					PKCS7.ContentInfo bag = new PKCS7.ContentInfo (PKCS7.Oid.encryptedData);
					bag.Content = certsContent;
					safeBagSequence.Add (bag.ASN1);
				}
			}

			if (_safeBags.Count > 0) {
				ASN1 safeContents = new ASN1 (0x30);
				foreach (SafeBag sb in _safeBags) {
					if (sb.BagOID.Equals (keyBag) ||
					    sb.BagOID.Equals (pkcs8ShroudedKeyBag)) {
						safeContents.Add (sb.ASN1);
					}
				}
				if (safeContents.Count > 0) {
					ASN1 content = new ASN1 (0xA0);
					content.Add (new ASN1 (0x04, safeContents.GetBytes ()));
				
					PKCS7.ContentInfo keyBag = new PKCS7.ContentInfo (PKCS7.Oid.data);
					keyBag.Content = content;
					safeBagSequence.Add (keyBag.ASN1);
				}
			}


			ASN1 encapsulates = new ASN1 (0x04, safeBagSequence.GetBytes ());
			ASN1 ci = new ASN1 (0xA0);
			ci.Add (encapsulates);
			PKCS7.ContentInfo authSafe = new PKCS7.ContentInfo (PKCS7.Oid.data);
			authSafe.Content = ci;
			
			ASN1 macData = new ASN1 (0x30);
			if (_password != null) {
				// only for password based encryption
				byte[] salt = new byte [20];
				RNG.GetBytes (salt);
				byte[] macValue = MAC (_password, salt, _iterations, authSafe.Content [0].Value);
				ASN1 oidSeq = new ASN1 (0x30);
				oidSeq.Add (ASN1Convert.FromOid ("1.3.14.3.2.26"));	// SHA1
				oidSeq.Add (new ASN1 (0x05));

				ASN1 mac = new ASN1 (0x30);
				mac.Add (oidSeq);
				mac.Add (new ASN1 (0x04, macValue));

				macData.Add (mac);
				macData.Add (new ASN1 (0x04, salt));
				macData.Add (ASN1Convert.FromInt32 (_iterations));
			}
			
			ASN1 version = new ASN1 (0x02, new byte [1] { 0x03 });
			
			ASN1 pfx = new ASN1 (0x30);
			pfx.Add (version);
			pfx.Add (authSafe.ASN1);
			if (macData.Count > 0) {
				// only for password based encryption
				pfx.Add (macData);
			}

			return pfx.GetBytes ();
		}
		public bool Sign (string fileName) 
		{
			string hashAlgorithm = "MD5";
			byte[] file = null;

			using (FileStream fs = new FileStream (fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
				file = new byte [fs.Length];
				fs.Read (file, 0, file.Length);
				fs.Close ();
			}

			// MZ - DOS header
			if (BitConverterLE.ToUInt16 (file, 0) != 0x5A4D)
				return false;

			// find offset of PE header
			int peOffset = BitConverterLE.ToInt32 (file, 60);
			if (peOffset > file.Length)
				return false;

			// PE - NT header
			if (BitConverterLE.ToUInt16 (file, peOffset) != 0x4550)
				return false;

			// IMAGE_DIRECTORY_ENTRY_SECURITY
			int dirSecurityOffset = BitConverterLE.ToInt32 (file, peOffset + 152);
			int dirSecuritySize = BitConverterLE.ToInt32 (file, peOffset + 156);

			if (dirSecuritySize > 8) {
				entry = new byte [dirSecuritySize - 8];
				Buffer.BlockCopy (file, dirSecurityOffset + 8, entry, 0, entry.Length);
			}
			else
				entry = null;

			HashAlgorithm hash = HashAlgorithm.Create (hashAlgorithm);
			// 0 to 215 (216) then skip 4 (checksum)
			int pe = peOffset + 88;
			hash.TransformBlock (file, 0, pe, file, 0);
			pe += 4;
			// 220 to 279 (60) then skip 8 (IMAGE_DIRECTORY_ENTRY_SECURITY)
			hash.TransformBlock (file, pe, 60, file, pe);
			pe += 68;
			// 288 to end of file
			int n = file.Length - pe;
			// minus any authenticode signature (with 8 bytes header)
			if (dirSecurityOffset != 0)
				n -= (dirSecuritySize);
			hash.TransformFinalBlock (file, pe, n);

			//
			byte[] signature = Header (hash.Hash, hashAlgorithm);
			if (timestamp != null) {
				ASN1 tsreq = TimestampRequest (signature);
				WebClient wc = new WebClient ();
				wc.Headers.Add ("Content-Type", "application/octet-stream");
				wc.Headers.Add ("Accept", "application/octet-stream");
				byte[] tsdata = Encoding.ASCII.GetBytes (Convert.ToBase64String (tsreq.GetBytes ()));
				byte[] tsres = wc.UploadData (timestamp.ToString (), tsdata);
				ProcessTimestamp (tsres);
			}
			PKCS7.ContentInfo sign = new PKCS7.ContentInfo (signedData);
			sign.Content.Add (pkcs7.ASN1);
			authenticode = sign.ASN1;

			byte[] asn = authenticode.GetBytes ();
#if DEBUG
			using (FileStream fs = File.Open (fileName + ".sig", FileMode.Create, FileAccess.Write)) {
				fs.Write (asn, 0, asn.Length);
				fs.Close ();
			}
#endif
			// someday I may be sure enough to move this into DEBUG ;-)
			File.Copy (fileName, fileName + ".bak", true);

			using (FileStream fs = File.Open (fileName, FileMode.Create, FileAccess.Write)) {
				int filesize = (dirSecurityOffset == 0) ? file.Length : dirSecurityOffset;
				// IMAGE_DIRECTORY_ENTRY_SECURITY (offset, size)
				byte[] data = BitConverterLE.GetBytes (filesize);
				file [peOffset + 152] = data [0];
				file [peOffset + 153] = data [1];
				file [peOffset + 154] = data [2];
				file [peOffset + 155] = data [3];
				int size = asn.Length + 8;
				// must be a multiple of 8 bytes
				int addsize = (size % 8);
				if (addsize > 0)
					addsize = 8 - addsize;
				size += addsize;
				data = BitConverterLE.GetBytes (size);		// header
				file [peOffset + 156] = data [0];
				file [peOffset + 157] = data [1];
				file [peOffset + 158] = data [2];
				file [peOffset + 159] = data [3];
				fs.Write (file, 0, filesize);
				fs.Write (data, 0, data.Length);		// length (again)
				data = BitConverterLE.GetBytes (0x00020200);	// magic
				fs.Write (data, 0, data.Length);
				fs.Write (asn, 0, asn.Length);
				// fill up
				byte[] fillup = new byte [addsize];
				fs.Write (fillup, 0, fillup.Length);
				fs.Close ();
			}
			return true;
		}
Example #16
0
            internal ASN1 GetASN1()
            {
                if ((key == null) || (hashAlgorithm == null))
                {
                    return(null);
                }
                byte[] ver        = { version };
                ASN1   signerInfo = new ASN1(0x30);

                // version Version -> Version ::= INTEGER
                signerInfo.Add(new ASN1(0x02, ver));
                // issuerAndSerialNumber IssuerAndSerialNumber,
                signerInfo.Add(PKCS7.IssuerAndSerialNumber(x509));
                // digestAlgorithm DigestAlgorithmIdentifier,
                string hashOid = CryptoConfig.MapNameToOID(hashAlgorithm);

                signerInfo.Add(AlgorithmIdentifier(hashOid));
                // authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,
                ASN1 aa = null;

                if (authenticatedAttributes.Count > 0)
                {
                    aa = signerInfo.Add(new ASN1(0xA0));
                    authenticatedAttributes.Sort(new SortedSet());
                    foreach (ASN1 attr in authenticatedAttributes)
                    {
                        aa.Add(attr);
                    }
                }
                // digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
                if (key is RSA)
                {
                    signerInfo.Add(AlgorithmIdentifier(PKCS7.Oid.rsaEncryption));

                    if (aa != null)
                    {
                        // Calculate the signature here; otherwise it must be set from SignedData
                        RSAPKCS1SignatureFormatter r = new RSAPKCS1SignatureFormatter(key);
                        r.SetHashAlgorithm(hashAlgorithm);
                        byte[] tbs = aa.GetBytes();
                        tbs [0] = 0x31;                         // not 0xA0 for signature
                        HashAlgorithm ha      = HashAlgorithm.Create(hashAlgorithm);
                        byte[]        tbsHash = ha.ComputeHash(tbs);
                        signature = r.CreateSignature(tbsHash);
                    }
                }
                else if (key is DSA)
                {
                    throw new NotImplementedException("not yet");
                }
                else
                {
                    throw new CryptographicException("Unknown assymetric algorithm");
                }
                // encryptedDigest EncryptedDigest,
                signerInfo.Add(new ASN1(0x04, signature));
                // unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
                if (unauthenticatedAttributes.Count > 0)
                {
                    ASN1 ua = signerInfo.Add(new ASN1(0xA1));
                    unauthenticatedAttributes.Sort(new SortedSet());
                    foreach (ASN1 attr in unauthenticatedAttributes)
                    {
                        ua.Add(attr);
                    }
                }
                return(signerInfo);
            }
Example #17
0
		// Creates an encrypted PKCS#7 ContentInfo with safeBags as its SafeContents.  Used in GetBytes(), above.
		private PKCS7.ContentInfo EncryptedContentInfo(ASN1 safeBags, string algorithmOid)
		{
			byte[] salt = new byte [8];
			RNG.GetBytes (salt);

			ASN1 seqParams = new ASN1 (0x30);
			seqParams.Add (new ASN1 (0x04, salt));
			seqParams.Add (ASN1Convert.FromInt32 (_iterations));

			ASN1 seqPbe = new ASN1 (0x30);
			seqPbe.Add (ASN1Convert.FromOid (algorithmOid));
			seqPbe.Add (seqParams);

			byte[] encrypted = Encrypt (algorithmOid, salt, _iterations, safeBags.GetBytes ());
			ASN1 encryptedContent = new ASN1 (0x80, encrypted);

			ASN1 seq = new ASN1 (0x30);
			seq.Add (ASN1Convert.FromOid (PKCS7.Oid.data));
			seq.Add (seqPbe);
			seq.Add (encryptedContent);

			ASN1 version = new ASN1 (0x02, new byte [1] { 0x00 });
			ASN1 encData = new ASN1 (0x30);
			encData.Add (version);
			encData.Add (seq);

			ASN1 finalContent = new ASN1 (0xA0);
			finalContent.Add (encData);

			PKCS7.ContentInfo bag = new PKCS7.ContentInfo (PKCS7.Oid.encryptedData);
			bag.Content = finalContent;
			return bag;
		}
		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 ();
		}
		private byte[] GetKeyIdentifier (Mono.Security.X509.X509Certificate x509) 
		{
			// if present in certificate return value of the SubjectKeyIdentifier
			Mono.Security.X509.X509Extension extn = x509.Extensions ["2.5.29.14"];
			if (extn != null) {
				ASN1 bs = new ASN1 (extn.Value.Value);
				return bs.Value;
			}
			// strangely DEPRECATED keyAttributes isn't used here (like KeyUsage)

			// if not then we must calculate the SubjectKeyIdentifier ourselve
			// Note: MS 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 (x509.KeyAlgorithm)));
			// FIXME: does it work for DSA certs (without an 2.5.29.14 extension ?)
			algo.Add (new ASN1 (x509.KeyAlgorithmParameters)); 
			byte[] pubkey = x509.PublicKey;
			byte[] bsvalue = new byte [pubkey.Length + 1]; // add unused bits (0) before the public key
			Array.Copy (pubkey, 0, bsvalue, 1, pubkey.Length);
			subjectPublicKeyInfo.Add (new ASN1 (0x03, bsvalue));
			SHA1 sha = SHA1.Create ();
			return sha.ComputeHash (subjectPublicKeyInfo.GetBytes ());
		}
		internal byte[] Encode ()
		{
			ASN1 ex = new ASN1 (0x04, _subjectKeyIdentifier);
			return ex.GetBytes ();
		}
Example #21
0
		private byte[] Build (ASN1 tbs, string hashoid, byte[] signature) 
		{
			ASN1 builder = new ASN1 (0x30);
			builder.Add (tbs);
			builder.Add (PKCS7.AlgorithmIdentifier (hashoid));
			// first byte of BITSTRING is the number of unused bits in the first byte
			byte[] bitstring = new byte [signature.Length + 1];
			Buffer.BlockCopy (signature, 0, bitstring, 1, signature.Length);
			builder.Add (new ASN1 (0x03, bitstring));
			return builder.GetBytes ();
		}
		internal byte[] Encode ()
		{
			ASN1 ex = new ASN1 (0x30);
			foreach (Oid o in _enhKeyUsage) {
				ex.Add (ASN1Convert.FromOid (o.Value));
			}
			return ex.GetBytes ();
		}
		internal byte[] Encode ()
		{
			// OCTETSTRING (0x04) Of the zero-terminated unicode string
			ASN1 attr = new ASN1 (0x04, Encoding.Unicode.GetBytes (_desc + (char)0));
			return attr.GetBytes ();
		}
Example #24
0
            internal ASN1 GetASN1()
            {
                if (key == null || this.hashAlgorithm == null)
                {
                    return(null);
                }
                byte[] data = new byte[1]
                {
                    version
                };
                ASN1 aSN = new ASN1(48);

                aSN.Add(new ASN1(2, data));
                aSN.Add(IssuerAndSerialNumber(x509));
                string oid = CryptoConfig.MapNameToOID(this.hashAlgorithm);

                aSN.Add(AlgorithmIdentifier(oid));
                ASN1 aSN2 = null;

                if (authenticatedAttributes.Count > 0)
                {
                    aSN2 = aSN.Add(new ASN1(160));
                    authenticatedAttributes.Sort(new SortedSet());
                    foreach (ASN1 authenticatedAttribute in authenticatedAttributes)
                    {
                        aSN2.Add(authenticatedAttribute);
                    }
                }
                if (key is RSA)
                {
                    aSN.Add(AlgorithmIdentifier("1.2.840.113549.1.1.1"));
                    if (aSN2 != null)
                    {
                        RSAPKCS1SignatureFormatter rSAPKCS1SignatureFormatter = new RSAPKCS1SignatureFormatter(key);
                        rSAPKCS1SignatureFormatter.SetHashAlgorithm(this.hashAlgorithm);
                        byte[] bytes = aSN2.GetBytes();
                        bytes[0] = 49;
                        HashAlgorithm hashAlgorithm = HashAlgorithm.Create(this.hashAlgorithm);
                        byte[]        rgbHash       = hashAlgorithm.ComputeHash(bytes);
                        signature = rSAPKCS1SignatureFormatter.CreateSignature(rgbHash);
                    }
                    aSN.Add(new ASN1(4, signature));
                    if (unauthenticatedAttributes.Count > 0)
                    {
                        ASN1 aSN3 = aSN.Add(new ASN1(161));
                        unauthenticatedAttributes.Sort(new SortedSet());
                        {
                            foreach (ASN1 unauthenticatedAttribute in unauthenticatedAttributes)
                            {
                                aSN3.Add(unauthenticatedAttribute);
                            }
                            return(aSN);
                        }
                    }
                    return(aSN);
                }
                if (key is DSA)
                {
                    throw new NotImplementedException("not yet");
                }
                throw new CryptographicException("Unknown assymetric algorithm");
            }
Example #25
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 ();
		}
Example #26
0
		internal byte[] Encode ()
		{
			ASN1 md = new ASN1 (0x04, _messageDigest);
			return md.GetBytes ();
		}
		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 ();
		}
Example #28
-1
		// in case we just want to timestamp the file
		public bool Timestamp (string fileName) 
		{
			try {
				AuthenticodeDeformatter def = new AuthenticodeDeformatter (fileName);
				byte[] signature = def.Signature;
				if (signature != null) {
					Open (fileName);
					PKCS7.ContentInfo ci = new PKCS7.ContentInfo (signature);
					pkcs7 = new PKCS7.SignedData (ci.Content);

					byte[] response = Timestamp (pkcs7.SignerInfo.Signature);
					ASN1 ts = new ASN1 (Convert.FromBase64String (Encoding.ASCII.GetString (response)));
					// insert new certificates and countersignature into the original signature
					ASN1 asn = new ASN1 (signature);
					ASN1 content = asn.Element (1, 0xA0);
					if (content == null)
						return false;

					ASN1 signedData = content.Element (0, 0x30);
					if (signedData == null)
						return false;

					// add the supplied certificates inside our signature
					ASN1 certificates = signedData.Element (3, 0xA0);
					if (certificates == null) {
						certificates = new ASN1 (0xA0);
						signedData.Add (certificates);
					}
					for (int i = 0; i < ts[1][0][3].Count; i++) {
						certificates.Add (ts[1][0][3][i]);
					}

					// add an unauthentified attribute to our signature
					ASN1 signerInfoSet = signedData[signedData.Count - 1];
					ASN1 signerInfo = signerInfoSet[0];
					ASN1 unauthenticated = signerInfo[signerInfo.Count - 1];
					if (unauthenticated.Tag != 0xA1) {
						unauthenticated = new ASN1 (0xA1);
						signerInfo.Add (unauthenticated);
					}
					unauthenticated.Add (Attribute (countersignature, ts[1][0][4][0]));

					return Save (fileName, asn.GetBytes ());
				}
			}
			catch (Exception e) {
				Console.WriteLine (e);
			}
			return false;
		}