// We don't want a dependency on StrongNameManager in Mono.Security.dll
        static public bool IsAssemblyStrongnamed(string assemblyName)
        {
            if (!initialized)
            {
                lock (lockObject)
                {
                    if (!initialized)
                    {
#if NET_2_1
                        // Moonlight cannot depend on machine.config
#else
                        string config = Environment.GetMachineConfigPath();
                        StrongNameManager.LoadConfig(config);
#endif
                        initialized = true;
                    }
                }
            }

            try
            {
                // this doesn't load the assembly (well it unloads it ;)
                // http://weblogs.asp.net/nunitaddin/posts/9991.aspx
                AssemblyName an = AssemblyName.GetAssemblyName(assemblyName);
                if (an == null)
                {
                    return(false);
                }

                byte[] publicKey = StrongNameManager.GetMappedPublicKey(an.GetPublicKeyToken());
                if ((publicKey == null) || (publicKey.Length < 12))
                {
                    // no mapping
                    publicKey = an.GetPublicKey();
                    if ((publicKey == null) || (publicKey.Length < 12))
                    {
                        return(false);
                    }
                }

                // Note: MustVerify is based on the original token (by design). Public key
                // remapping won't affect if the assembly is verified or not.
                if (!StrongNameManager.MustVerify(an))
                {
                    return(true);
                }

                RSA        rsa    = CryptoConvert.FromCapiPublicKeyBlob(publicKey, 12);
                StrongName sn     = new StrongName(rsa);
                bool       result = sn.Verify(assemblyName);
                return(result);
            }
            catch
            {
                // no exception allowed
                return(false);
            }
        }
        public static bool IsAssemblyStrongnamed(string assemblyName)
        {
            if (!StrongName.initialized)
            {
                object obj = StrongName.lockObject;
                lock (obj)
                {
                    if (!StrongName.initialized)
                    {
                        StrongName.initialized = true;
                    }
                }
            }
            bool result;

            try
            {
                AssemblyName assemblyName2 = AssemblyName.GetAssemblyName(assemblyName);
                if (assemblyName2 == null)
                {
                    result = false;
                }
                else
                {
                    byte[] mappedPublicKey = StrongNameManager.GetMappedPublicKey(assemblyName2.GetPublicKeyToken());
                    if (mappedPublicKey == null || mappedPublicKey.Length < 12)
                    {
                        mappedPublicKey = assemblyName2.GetPublicKey();
                        if (mappedPublicKey == null || mappedPublicKey.Length < 12)
                        {
                            return(false);
                        }
                    }
                    if (!StrongNameManager.MustVerify(assemblyName2))
                    {
                        result = true;
                    }
                    else
                    {
                        RSA        rsa        = CryptoConvert.FromCapiPublicKeyBlob(mappedPublicKey, 12);
                        StrongName strongName = new StrongName(rsa);
                        bool       flag       = strongName.Verify(assemblyName);
                        result = flag;
                    }
                }
            }
            catch
            {
                result = false;
            }
            return(result);
        }
        public static bool VerifySignature(byte[] publicKey, int algorithm, byte[] hash, byte[] signature)
        {
            bool result;

            try
            {
                RSA rsa = CryptoConvert.FromCapiPublicKeyBlob(publicKey);
                result = StrongName.Verify(rsa, (AssemblyHashAlgorithm)algorithm, hash, signature);
            }
            catch
            {
                result = false;
            }
            return(result);
        }
Exemple #4
0
        internal AssemblyBuilder(AssemblyName n, string directory, AssemblyBuilderAccess access, bool corlib_internal)
        {
            name        = n.Name;
            this.access = (uint)access;

            // don't call GetCurrentDirectory for Run-only builders (CAS may not like that)
            if (IsSave && (directory == null || directory == String.Empty))
            {
                dir = Directory.GetCurrentDirectory();
            }
            else
            {
                dir = directory;
            }

            /* Set defaults from n */
            if (n.CultureInfo != null)
            {
                culture = n.CultureInfo.Name;
            }
            Version v = n.Version;

            if (v != null)
            {
                version = v.ToString();
            }

            if (n.KeyPair != null)
            {
                // full keypair is available (for signing)
                sn = n.KeyPair.StrongName();
            }
            else
            {
                // public key is available (for delay-signing)
                byte[] pk = n.GetPublicKey();
                if ((pk != null) && (pk.Length > 0))
                {
                    sn = new Mono.Security.StrongName(pk);
                }
            }

            this.corlib_internal = corlib_internal;

            basic_init(this);
        }
        public bool Verify(Stream stream)
        {
            StrongName.StrongNameSignature strongNameSignature = this.StrongHash(stream, StrongName.StrongNameOptions.Signature);
            if (strongNameSignature.Hash == null)
            {
                return(false);
            }
            bool result;

            try
            {
                AssemblyHashAlgorithm algorithm = AssemblyHashAlgorithm.SHA1;
                if (this.tokenAlgorithm == "MD5")
                {
                    algorithm = AssemblyHashAlgorithm.MD5;
                }
                result = StrongName.Verify(this.rsa, algorithm, strongNameSignature.Hash, strongNameSignature.Signature);
            }
            catch (CryptographicException)
            {
                result = false;
            }
            return(result);
        }
        public static int Main(string[] args)
        {
            bool replace = CheckReplace(ref args);

            if (args.Length == 0 || args.Length == 1 && Regex.IsMatch(args[0], @"^/(\?|h|help)$"))
            {
                PrintUsage();
                return -1;
            }
            try
            {
                string assembly = args[0];

                if (!File.Exists(assembly))
                {
                    throw new FileNotFoundException("The file " + args[0] + " doesn't exist!");
                }
                List<string> iconFiles = GetIconFiles(args);
                VerifyIconFiles(iconFiles);

                string strongNameKeyFile = args.Length > 2 ? args[2] : null;
                //Verify that the assembly is signed to begin with. We don't support signing unsigned assemblies,
                //only re-signing them.
                if (strongNameKeyFile != null)
                {
                    using (var stream = new FileStream(assembly, FileMode.Open, FileAccess.Read)) {
                        var signature = new StrongName().StrongHash(stream, StrongName.StrongNameOptions.Signature);
                        if (signature.SignaturePosition == 0 && signature.SignatureLength == 0)
                        {
                            throw new ArgumentException("Assembly is not strong named, InsertIcons can only re-sign assemblies, not sign unsigned assemblies." );
                        }
                    }
                }
                ushort iconMaxId = replace ? (ushort)0 : GetMaxIconId(assembly);

                int groupIconIdCounter = StartIconId;
                foreach (string icoFile in iconFiles)
                {
                    groupIconIdCounter++;
                    IconDirectoryResource newIcon = new IconDirectoryResource(new IconFile(icoFile));
                    newIcon.Name.Id = new IntPtr(groupIconIdCounter);
                    foreach (var icon in newIcon.Icons)
                    {
                        icon.Id = ++iconMaxId;
                    }
                    Console.WriteLine(" {0} {1} inserted into {2}", newIcon.Name.Id, Path.GetFileName(icoFile), Path.GetFileName(assembly));
                    newIcon.SaveTo(assembly);
                }

                if (strongNameKeyFile != null)
                {
                    ResignAssembly(assembly, strongNameKeyFile);
                }
                Console.WriteLine("Successfully inserted {0} icons into {1}", iconFiles.Count, Path.GetFileName(assembly));
                return 0;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("error: {0}", ex.Message);
                return 1;
            }
        }
Exemple #7
0
		internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access, bool corlib_internal)
		{
			is_compiler_context = (access & COMPILER_ACCESS) != 0;

			// remove Mono specific flag to allow enum check to pass
			access &= ~COMPILER_ACCESS;

#if MOONLIGHT
			// only "Run" is supported by Silverlight
			// however SMCS requires more than this but runs outside the CoreCLR sandbox
			if (SecurityManager.SecurityEnabled && (access != AssemblyBuilderAccess.Run))
				throw new ArgumentException ("access");
#endif

			if (!Enum.IsDefined (typeof (AssemblyBuilderAccess), access))
				throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
					"Argument value {0} is not valid.", (int) access),
					"access");

			name = n.Name;
			this.access = (uint)access;
			flags = (uint) n.Flags;

			// don't call GetCurrentDirectory for Run-only builders (CAS may not like that)
			if (IsSave && (directory == null || directory.Length == 0)) {
				dir = Directory.GetCurrentDirectory ();
			} else {
				dir = directory;
			}

			/* Set defaults from n */
			if (n.CultureInfo != null) {
				culture = n.CultureInfo.Name;
				versioninfo_culture = n.CultureInfo.Name;
			}
			Version v = n.Version;
			if (v != null) {
				version = v.ToString ();
			}

			if (n.KeyPair != null) {
				// full keypair is available (for signing)
				sn = n.KeyPair.StrongName ();
			} else {
				// public key is available (for delay-signing)
				byte[] pk = n.GetPublicKey ();
				if ((pk != null) && (pk.Length > 0)) {
					sn = new Mono.Security.StrongName (pk);
				}
			}

			if (sn != null)
				flags |= (uint) AssemblyNameFlags.PublicKey;

			this.corlib_internal = corlib_internal;
			if (sn != null) {
				this.pktoken = new byte[sn.PublicKeyToken.Length * 2];
				int pkti = 0;
				foreach (byte pkb in sn.PublicKeyToken) {
					string part = pkb.ToString("x2");
					this.pktoken[pkti++] = (byte)part[0];
					this.pktoken[pkti++] = (byte)part[1];
				}
			}

			basic_init (this);
		}
 /// <summary>
 /// Loads the update keys from a strong name key files (.snk).
 /// </summary>
 /// <param name="fileName">The file to load.</param>
 /// <returns>The update keys.</returns>
 public static UpdateKeys FromStrongNameKey(string fileName)
 {
     var strongName = new StrongName(File.ReadAllBytes(fileName));
     return new UpdateKeys(strongName.RSA);
 }
Exemple #9
0
		// modified copy from sn
		private static VerificationResult VerifyStrongName (AssemblyName an, string assemblyFile)
		{
			byte [] publicKey = StrongNameManager.GetMappedPublicKey (an.GetPublicKeyToken ());
			if ((publicKey == null) || (publicKey.Length < 12)) {
				// no mapping
				publicKey = an.GetPublicKey ();
				if ((publicKey == null) || (publicKey.Length < 12))
					return VerificationResult.WeakNamed;
			}

			// Note: MustVerify is based on the original token (by design). Public key
			// remapping won't affect if the assembly is verified or not.
			if (StrongNameManager.MustVerify (an)) {
				RSA rsa = CryptoConvert.FromCapiPublicKeyBlob (publicKey, 12);
				StrongName sn = new StrongName (rsa);
				if (sn.Verify (assemblyFile)) {
					return VerificationResult.StrongNamed;
				} else {
					return VerificationResult.DelaySigned;
				}
			} else {
				return VerificationResult.Skipped;
			}
		}
		public void BadKey () 
		{
			byte[] bad = new byte [0]; 
			sn = new StrongName (bad); 
		}
		public void StrongName_ByteNull () 
		{
			byte[] data = null;
			sn = new StrongName (data); 
		}
		public void FromKey ()
		{
			StrongName sn1 = new StrongName (test);
			StrongName sn2 = new StrongName (sn1.RSA);
			AssertEquals ("key.RSA", sn1.RSA.ToXmlString (true), sn2.RSA.ToXmlString (true));
			AssertEquals ("key.PublicKey", sn1.PublicKey, sn2.PublicKey);
			AssertEquals ("key.PublicKeyToken", sn1.PublicKeyToken, sn2.PublicKeyToken);
		}
Exemple #13
0
		internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access, bool corlib_internal)
		{
			/* This is obsolete now, as mcs doesn't use SRE any more */
			if ((access & COMPILER_ACCESS) != 0)
				throw new NotImplementedException ("COMPILER_ACCESS is no longer supperted, use a newer mcs.");

			if (!Enum.IsDefined (typeof (AssemblyBuilderAccess), access))
				throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
					"Argument value {0} is not valid.", (int) access),
					"access");

			name = n.Name;
			this.access = (uint)access;
			flags = (uint) n.Flags;

			// don't call GetCurrentDirectory for Run-only builders (CAS may not like that)
			if (IsSave && (directory == null || directory.Length == 0)) {
				dir = Directory.GetCurrentDirectory ();
			} else {
				dir = directory;
			}

			/* Set defaults from n */
			if (n.CultureInfo != null) {
				culture = n.CultureInfo.Name;
				versioninfo_culture = n.CultureInfo.Name;
			}
			Version v = n.Version;
			if (v != null) {
				version = v.ToString ();
			}

			if (n.KeyPair != null) {
				// full keypair is available (for signing)
				sn = n.KeyPair.StrongName ();
			} else {
				// public key is available (for delay-signing)
				byte[] pk = n.GetPublicKey ();
				if ((pk != null) && (pk.Length > 0)) {
					sn = new Mono.Security.StrongName (pk);
				}
			}

			if (sn != null)
				flags |= (uint) AssemblyNameFlags.PublicKey;

			this.corlib_internal = corlib_internal;
			if (sn != null) {
				this.pktoken = new byte[sn.PublicKeyToken.Length * 2];
				int pkti = 0;
				foreach (byte pkb in sn.PublicKeyToken) {
					string part = pkb.ToString("x2");
					this.pktoken[pkti++] = (byte)part[0];
					this.pktoken[pkti++] = (byte)part[1];
				}
			}

			basic_init (this);
		}
		// We don't want a dependency on StrongNameManager in Mono.Security.dll
		static public bool IsAssemblyStrongnamed (string assemblyName) 
		{
			if (!initialized) {
				lock (lockObject) {
					if (!initialized) {
						string config = Environment.GetMachineConfigPath ();
						StrongNameManager.LoadConfig (config);
						initialized = true;
					}
				}
			}

			try {
				// this doesn't load the assembly (well it unloads it ;)
				// http://weblogs.asp.net/nunitaddin/posts/9991.aspx
				AssemblyName an = AssemblyName.GetAssemblyName (assemblyName);
				if (an == null)
					return false;

				byte[] publicKey = StrongNameManager.GetMappedPublicKey (an.GetPublicKeyToken ());
				if ((publicKey == null) || (publicKey.Length < 12)) {
					// no mapping
					publicKey = an.GetPublicKey ();
					if ((publicKey == null) || (publicKey.Length < 12))
						return false;
				}

				// Note: MustVerify is based on the original token (by design). Public key
				// remapping won't affect if the assembly is verified or not.
				if (!StrongNameManager.MustVerify (an)) {
					return true;
				}

				RSA rsa = CryptoConvert.FromCapiPublicKeyBlob (publicKey, 12);
				StrongName sn = new StrongName (rsa);
				bool result = sn.Verify (assemblyName);
				return result;
			}
			catch {
				// no exception allowed
				return false;
			}
		}
Exemple #15
0
        internal AssemblyBuilder(AssemblyName n, string directory, AssemblyBuilderAccess access, bool corlib_internal)
        {
#if BOOTSTRAP_WITH_OLDLIB
            is_compiler_context = true;
#else
            is_compiler_context = (access & COMPILER_ACCESS) != 0;
#endif

            // remove Mono specific flag to allow enum check to pass
            access &= ~COMPILER_ACCESS;

#if NET_2_1 && !MONOTOUCH
            // only "Run" is supported by Silverlight
            // however SMCS requires more than this but runs outside the CoreCLR sandbox
            if (SecurityManager.SecurityEnabled && (access != AssemblyBuilderAccess.Run))
            {
                throw new ArgumentException("access");
            }
#endif

#if NET_2_0
            if (!Enum.IsDefined(typeof(AssemblyBuilderAccess), access))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
                                                          "Argument value {0} is not valid.", (int)access),
                                            "access");
            }
#endif

#if NET_4_0
            if ((access & AssemblyBuilderAccess.RunAndCollect) == AssemblyBuilderAccess.RunAndCollect)
            {
                throw new NotSupportedException("RunAndCollect not yet supported.");
            }
#endif

            name        = n.Name;
            this.access = (uint)access;
            flags       = (uint)n.Flags;

            // don't call GetCurrentDirectory for Run-only builders (CAS may not like that)
            if (IsSave && (directory == null || directory.Length == 0))
            {
                dir = Directory.GetCurrentDirectory();
            }
            else
            {
                dir = directory;
            }

            /* Set defaults from n */
            if (n.CultureInfo != null)
            {
                culture             = n.CultureInfo.Name;
                versioninfo_culture = n.CultureInfo.Name;
            }
            Version v = n.Version;
            if (v != null)
            {
                version = v.ToString();
            }

            if (n.KeyPair != null)
            {
                // full keypair is available (for signing)
                sn = n.KeyPair.StrongName();
            }
            else
            {
                // public key is available (for delay-signing)
                byte[] pk = n.GetPublicKey();
                if ((pk != null) && (pk.Length > 0))
                {
                    sn = new Mono.Security.StrongName(pk);
                }
            }

            if (sn != null)
            {
                flags |= (uint)AssemblyNameFlags.PublicKey;
            }

            this.corlib_internal = corlib_internal;
            if (sn != null)
            {
                this.pktoken = new byte[sn.PublicKeyToken.Length * 2];
                int pkti = 0;
                foreach (byte pkb in sn.PublicKeyToken)
                {
                    string part = pkb.ToString("x2");
                    this.pktoken[pkti++] = (byte)part[0];
                    this.pktoken[pkti++] = (byte)part[1];
                }
            }

            basic_init(this);
        }
Exemple #16
0
		public void ECMA () 
		{
			byte[] ecma = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; 
			sn = new StrongName (ecma);
			Assert.IsTrue (!sn.CanSign, "CanSign");
		}
Exemple #17
0
		public void SetUp () 
		{
			Signed = Path.Combine (Path.GetTempPath (), "hellosigned.exe");
			Delay = Path.Combine (Path.GetTempPath (), "hellodelay.exe");

			sn = new StrongName (key);
			// write hellosigned.exe to disk
			FileStream fs = File.OpenWrite (Signed);
			fs.Write (signedData, 0, signedData.Length);
			fs.Close ();


			// write hellodelay.exe to disk
			fs = File.OpenWrite (Delay);
			fs.Write (delayData, 0, delayData.Length);
			fs.Close ();
		}
Exemple #18
0
		public void FromKey ()
		{
			StrongName sn1 = new StrongName (test);
			StrongName sn2 = new StrongName (sn1.RSA);
			Assert.AreEqual (sn1.RSA.ToXmlString (true), sn2.RSA.ToXmlString (true), "key.RSA");
			Assert.AreEqual (sn1.PublicKey, sn2.PublicKey, "key.PublicKey");
			Assert.AreEqual (sn1.PublicKeyToken, sn2.PublicKeyToken, "key.PublicKeyToken");
		}
Exemple #19
0
        internal AssemblyBuilder(AssemblyName n, string directory, AssemblyBuilderAccess access, bool corlib_internal)
        {
            /* This is obsolete now, as mcs doesn't use SRE any more */
            if ((access & COMPILER_ACCESS) != 0)
            {
                throw new NotImplementedException("COMPILER_ACCESS is no longer supperted, use a newer mcs.");
            }

            if (!Enum.IsDefined(typeof(AssemblyBuilderAccess), access))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
                                                          "Argument value {0} is not valid.", (int)access),
                                            "access");
            }

            name        = n.Name;
            this.access = (uint)access;
            flags       = (uint)n.Flags;

            // don't call GetCurrentDirectory for Run-only builders (CAS may not like that)
            if (IsSave && (directory == null || directory.Length == 0))
            {
                dir = Directory.GetCurrentDirectory();
            }
            else
            {
                dir = directory;
            }

            /* Set defaults from n */
            if (n.CultureInfo != null)
            {
                culture             = n.CultureInfo.Name;
                versioninfo_culture = n.CultureInfo.Name;
            }
            Version v = n.Version;

            if (v != null)
            {
                version = v.ToString();
            }

            if (n.KeyPair != null)
            {
                // full keypair is available (for signing)
                sn = n.KeyPair.StrongName();
            }
            else
            {
                // public key is available (for delay-signing)
                byte[] pk = n.GetPublicKey();
                if ((pk != null) && (pk.Length > 0))
                {
                    sn = new Mono.Security.StrongName(pk);
                }
            }

            if (sn != null)
            {
                flags |= (uint)AssemblyNameFlags.PublicKey;
            }

            this.corlib_internal = corlib_internal;
            if (sn != null)
            {
                this.pktoken = new byte[sn.PublicKeyToken.Length * 2];
                int pkti = 0;
                foreach (byte pkb in sn.PublicKeyToken)
                {
                    string part = pkb.ToString("x2");
                    this.pktoken[pkti++] = (byte)part[0];
                    this.pktoken[pkti++] = (byte)part[1];
                }
            }

            basic_init(this);
        }
Exemple #20
0
		static bool ReSign (string assemblyName, RSA key, bool quiet) 
		{
			// this doesn't load the assembly (well it unloads it ;)
			// http://weblogs.asp.net/nunitaddin/posts/9991.aspx
			AssemblyName an = null;
			try {
				an = AssemblyName.GetAssemblyName (assemblyName);
			}
			catch {
			}
			if (an == null) {
				Console.WriteLine ("Unable to load assembly: {0}", assemblyName);
				return false;
			}

			StrongName sign = new StrongName (key);
			byte[] token = an.GetPublicKeyToken ();

			// first, try to compare using a mapped public key (e.g. ECMA)
			bool same = Compare (sign.PublicKey, StrongNameManager.GetMappedPublicKey (token));
			if (!same) {
				// second, try to compare using the assembly public key
				same = Compare (sign.PublicKey, an.GetPublicKey ());
				if (!same) {
					// third (and last) chance, try to compare public key token
					same = Compare (sign.PublicKeyToken, token);
				}
			}

			if (same) {
				bool signed = sign.Sign (assemblyName);
				if (!quiet || !signed) {
					Console.WriteLine (signed ? "Assembly {0} signed." : "Couldn't sign the assembly {0}.", 
							   assemblyName);
				}
				return signed;
			}
			
			Console.WriteLine ("Couldn't sign the assembly {0} with this key pair.", assemblyName);
			return false;
		}
		public void FromBuffer ()
		{
			StrongName sn = new StrongName (test);
			AssertEquals ("buffer.RSA", "<RSAKeyValue><Modulus>y6T/+EoARJMHW0ilpCdn+VbTffWxb1xu187/9Q+S2DwPyZ9LTNKrZgwaYmG4FPWEEH1HJxrxwh8AlD6oTz8CCcnPGKxKVFkubpIbEyvQCSTr22gUjVXXKHc2pfcCeOuNXS9kAOjv2tqpsiDbIsu9mnxfYysHWMDBqA4rxghyvT0=</Modulus><Exponent>AQAB</Exponent><P>6qYUEleRY+Wzyk7xN05UwWRna37U2aQnq2Y2VVyJeceDZPU1u1GYdQmFQw5XgvxKwWx9DAfNh1iSyLe0YmrAcw==</P><Q>3iy1IDIkPrRWBFrCAUhpUNn4/ICiVXTT7KjuEXkGr0+1Cx/V+o3eoVIo/9x2Q3IaxMbQDSa8hisIFunz/iuPjw==</Q><DP>2BouIBpfvzX8mBSOGNZePmG+0YRUeUCyfCs9XO5Fek9h1mfynVpvY1JqVbBuria2nl7Q53SEN+M+A/cT/RO9uw==</DP><DQ>pjma1ljNh2CTTrS8nAsaSJSc1gZD7l33RQRrAgWju7yN/qG2DbzhSZ9X7355uSKA5qK8/Gnz+QnvBn3JwGvE/w==</DQ><InverseQ>3U67bp3lPExfGoiTRvRyHhNtyJs6hAq/Uj7wSHKLHNoLG20kwZux8BwZKpPBBA0bQjkLUiRv9PYs18El/45/wA==</InverseQ><D>bPVOg5FMjWRBhmTbQ3ZWGkGLjRR9KEFDiTJXHs6DWjDgnZceWe9KB6KoJ0Vzkbs/Ovdcr56qBZxC2g6gTS5ALvogBYH2PrUftr4flh/z4qgOrAYCQkTecfHAGIGEldEeF1FItMbqmQa6WzVPVp4tn/+q3PAVmZqrs6/X9EARH10=</D></RSAKeyValue>", sn.RSA.ToXmlString (true));
			AssertEquals ("buffer.PublicKey", testPublicKey, sn.PublicKey);
			AssertEquals ("buffer.PublicKeyToken", testPublicKeyToken, sn.PublicKeyToken);
		}
Exemple #22
0
		static int Verify (string assemblyName, bool forceVerification, bool quiet) 
		{
			// this doesn't load the assembly (well it unloads it ;)
			// http://weblogs.asp.net/nunitaddin/posts/9991.aspx
			AssemblyName an = null;
			try {
				an = AssemblyName.GetAssemblyName (assemblyName);
			}
			catch {
			}
			if (an == null) {
				Console.WriteLine ("Unable to load assembly: {0}", assemblyName);
				return 2;
			}

			byte[] publicKey = StrongNameManager.GetMappedPublicKey (an.GetPublicKeyToken ());
			if ((publicKey == null) || (publicKey.Length < 12)) {
				// no mapping
				publicKey = an.GetPublicKey ();
				if ((publicKey == null) || (publicKey.Length < 12)) {
					Console.WriteLine ("{0} is not a strongly named assembly.", assemblyName);
					return 2;
				}
			}

			// Note: MustVerify is based on the original token (by design). Public key
			// remapping won't affect if the assembly is verified or not.
			if (forceVerification || StrongNameManager.MustVerify (an)) {
				RSA rsa = CryptoConvert.FromCapiPublicKeyBlob (publicKey, 12);
				StrongName sn = new StrongName (rsa);
				if (sn.Verify (assemblyName)) {
					if (!quiet)
						Console.WriteLine ("Assembly {0} is strongnamed.", assemblyName);
					return 0;
				}
				else {
					Console.WriteLine ("Assembly {0} is delay-signed but not strongnamed", assemblyName);
					return 1;
				}
			}
			else {
				Console.WriteLine ("Assembly {0} is strongnamed (verification skipped).", assemblyName);
				return 0;
			}
		}
		public void SetUp () 
		{
			sn = new StrongName (key);
			// write hellosigned.exe to disk
			FileStream fs = File.OpenWrite (Signed);
			fs.Write (signedData, 0, signedData.Length);
			fs.Close ();
			// write hellodelay.exe to disk
			fs = File.OpenWrite (Delay);
			fs.Write (delayData, 0, delayData.Length);
			fs.Close ();
		}
Exemple #24
0
		static int Process (string[] args)
		{
			int i = 0;
			string param = args [i];
			bool quiet = ((param == "-quiet") || (param == "-q"));
			if (quiet)
				i++;
			else
				Header();

			LoadConfig (quiet);

			StrongName sn = null;
			AssemblyName an = null;
			RSACryptoServiceProvider rsa = null;
			CspParameters csp = new CspParameters ();
			csp.ProviderName = defaultCSP;

			switch (args [i++]) {
				case "-c":
					// Change global CSP provider options
					defaultCSP = args [i];
					return SaveConfig ();
				case "-d":
					// Delete specified key container
					csp.KeyContainerName = args [i];
					rsa = new RSACryptoServiceProvider (csp);
					rsa.PersistKeyInCsp = false;
					if (!quiet)
						Console.WriteLine ("Keypair in container {0} has been deleted", args [i]);
					break;
				case "-D":
					StrongName a1 = new StrongName ();
					byte[] h1 = a1.Hash (args [i++]);
					StrongName a2 = new StrongName ();
					byte[] h2 = a2.Hash (args [i++]);
					if (Compare (h1, h2)) {
						Console.WriteLine ("Both assembly are identical (same digest for metadata)");
						// TODO: if equals then compare signatures
					}
					else
						Console.WriteLine ("Assemblies are not identical (different digest for metadata)");
					break;
				case "-e":
					// Export public key from assembly
					an = AssemblyName.GetAssemblyName (args [i++]);
					WriteToFile (args[i], an.GetPublicKey ());
					if (!quiet)
						Console.WriteLine ("Public Key extracted to file {0}", args [i]);
					break;
				case "-i":
					// import keypair from SNK to container
					sn = new StrongName (ReadFromFile (args [i++]));
					csp.KeyContainerName = args [i];
					rsa = new RSACryptoServiceProvider (csp);
					rsa.ImportParameters (sn.RSA.ExportParameters (true));
					break;
				case "-k":
					// Create a new strong name key pair
					// (a new RSA keypair automagically if none is present)
					int size = 1024;
					if (i < args.Length + 2) {
						try {
							size = Int32.Parse (args[i++]);
						}
						catch {
							// oops, that wasn't a valid key size (assume 1024 bits)
							i--;
						}
					}
					sn = new StrongName (size);
					WriteToFile (args[i], CryptoConvert.ToCapiKeyBlob (sn.RSA, true));
					if (!quiet)
						Console.WriteLine ("A new {0} bits strong name keypair has been generated in file '{1}'.", size, args [i]);
					break;
				case "-m":
					Console.WriteLine ("Unimplemented option");
					break;
				case "-o":
					byte[] infileD = ReadFromFile (args [i++]);
					WriteCSVToFile (args [i], infileD, "D");
					if (!quiet)
						Console.WriteLine ("Output CSV file is {0} (decimal format)", args [i]);
					break;
				case "-oh":
					byte[] infileX2 = ReadFromFile (args [i++]);
					WriteCSVToFile (args [i], infileX2, "X2");
					if (!quiet)
						Console.WriteLine ("Output CVS file is {0} (hexadecimal format)", args [i]);
					break;
				case "-p":
					// Extract public key from SNK or PKCS#12/PFX file
					sn = new StrongName (GetKeyFromFile (args [i++]));
					WriteToFile (args[i], sn.PublicKey);
					if (!quiet)
						Console.WriteLine ("Public Key extracted to file {0}", args [i]);
					break;
				case "-pc":
					// Extract public key from container
					csp.KeyContainerName = args [i++];
					rsa = new RSACryptoServiceProvider (csp);
					sn = new StrongName (rsa);
					WriteToFile (args[i], sn.PublicKey);
					if (!quiet)
						Console.WriteLine ("Public Key extracted to file {0}", args [i]);
					break;
				case "-R":
					string filename = args [i++];
					if (! ReSign (filename, GetKeyFromFile (args [i]), quiet))
						return 1;
					break;
				case "-Rc":
					filename = args [i++];
					csp.KeyContainerName = args [i];
					rsa = new RSACryptoServiceProvider (csp);
					if (! ReSign (filename, rsa, quiet))
						return 1;
					break;
				case "-t":
					// Show public key token from file
					sn = new StrongName (ReadFromFile (args [i]));
					// note: ignore quiet
					Console.WriteLine ("Public Key Token: " + ToString (sn.PublicKeyToken), Environment.NewLine);
					break;
				case "-tp":
					// Show public key and public key token from assembly
					sn = new StrongName (ReadFromFile (args [i]));
					// note: ignore quiet
					Console.WriteLine ("Public Key:" + ToString (sn.PublicKey));
					Console.WriteLine ("{0}Public Key Token: " + ToString (sn.PublicKeyToken), Environment.NewLine);
					break;
				case "-T":
					// Show public key token from assembly
					an = AssemblyName.GetAssemblyName (args [i++]);
					// note: ignore quiet
					byte [] pkt = an.GetPublicKeyToken ();
					if (pkt == null) {
						Console.WriteLine ("{0} does not represent a strongly named assembly.", args [i - 1]);
					} else {
						Console.WriteLine ("Public Key Token: " + ToString (pkt));
					}
					break;
				case "-Tp":
					// Show public key and public key token from assembly
					an = AssemblyName.GetAssemblyName (args [i++]);
					byte [] token = an.GetPublicKeyToken ();
					if (token == null) {
						Console.WriteLine ("{0} does not represent a strongly named assembly.", args [i - 1]);
					} else {
						Console.WriteLine ("Public Key:" + ToString (an.GetPublicKey ()));
						Console.WriteLine ("{0}Public Key Token: " + ToString (token), Environment.NewLine);
					}
					break;
				case "-v":
					filename = args [i++];
					return Verify (filename, false, quiet);
				case "-vf":
					filename = args [i++];
					return Verify (filename, true, quiet);	// force verification
				case "-Vl":
					Console.WriteLine (new StrongNameManager ().ToString ());
					break;
				case "-Vr":
					Console.WriteLine ("Unimplemented option");
					break;
				case "-Vu":
					Console.WriteLine ("Unimplemented option");
					break;
				case "-Vx":
					// we must remove <verificationSettings> from each config files
					Console.WriteLine ("Unimplemented option");
					break;
				case "-?":
				case "-h":
					Help ((i < args.Length) ? args [i] : null);
					break;
				default:
					if (!quiet)
						Console.WriteLine ("Unknown option {0}", args [i-1]);
					return 1;
			}
			return 0;
		}
		public void StrongName_RSANull () 
		{
			RSA rsa = null;
			sn = new StrongName (rsa); 
		}
Exemple #26
0
			private void LoadKey ()
			{
				if (keycontainer) {
					CspParameters csp = new CspParameters ();
					csp.KeyContainerName = keyname;
					RSACryptoServiceProvider rsa = new RSACryptoServiceProvider (csp);
					sn = new StrongName (rsa);
				} else {
					byte[] data = null;
					using (FileStream fs = File.OpenRead (keyname)) {
						data = new byte [fs.Length];
						fs.Read (data, 0, data.Length);
						fs.Close ();
					}
					sn = new StrongName (data);
				}
			}
		public void ECMA () 
		{
			byte[] ecma = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; 
			sn = new StrongName (ecma);
			Assert ("CanSign", !sn.CanSign);
		}
 public Factory(string key_filename)
 {
     strong_name = new Mono.Security.StrongName (ReadFromFile (key_filename));
 }
Exemple #29
0
		private static Assembly LoadAndVerifyAssemblyInternal(byte[] assemblyData)
		{
			Assembly assembly = Assembly.Load(assemblyData);
			byte[] publicKey = assembly.GetName().GetPublicKey();
			if (publicKey == null || publicKey.Length == 0)
			{
				return null;
			}
			RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider();
			rSACryptoServiceProvider.ImportCspBlob(publicKey);
			StrongName strongName = new StrongName(rSACryptoServiceProvider);
			Assembly result;
			using (MemoryStream memoryStream = new MemoryStream(assemblyData))
			{
				if (strongName.Verify(memoryStream))
				{
					Security._verifiedAssemblies.Add(assembly);
					result = assembly;
				}
				else
				{
					result = null;
				}
			}
			return result;
		}
Exemple #30
0
 /// <summary>
 /// Loads the update keys from a byte array containing the public key data.
 /// </summary>
 /// <param name="publicKey">The data to load.</param>
 /// <returns>The update keys.</returns>
 public static UpdateKeys FromPublicKey(IEnumerable<byte> publicKey)
 {
     var strongName = new StrongName(publicKey.ToArray());
     return new UpdateKeys(strongName.RSA);
 }