Example #1
0
        public void KeyContainer()
        {
            if (!NativeMethodsShared.IsWindows)
            {
                return; // "Key container is not supported, except under Windows"
            }

            var t = new ResolveComReference.TlbImp();

            t.TypeLibName = "FakeTlb.tlb";
            string badParameterValue  = "badKeyContainer";
            string goodParameterValue = "myKeyContainer";

            try
            {
                t.ToolPath = Path.GetTempPath();

                Assert.Null(t.KeyContainer); // "KeyContainer should be null by default");
                CommandLine.ValidateNoParameterStartsWith(
                    t,
                    @"/keycontainer:",
                    false /* no response file */);

                t.KeyContainer = badParameterValue;
                Assert.Equal(badParameterValue, t.KeyContainer); // "New KeyContainer value should be set"
                CommandLine.ValidateHasParameter(t, @"/keycontainer:" + badParameterValue, false /* no response file */);
                Utilities.ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "AxTlbBaseTask.StrongNameUtils.NoKeyPairInContainer", t.KeyContainer);
                // ensure the key does not exist in the CSP
                StrongNameHelpers.StrongNameKeyDelete(goodParameterValue);

                IntPtr publicKeyBlob     = IntPtr.Zero;
                int    publicKeyBlobSize = 0;

                // add key to CSP
                if (StrongNameHelpers.StrongNameKeyGen(goodParameterValue, 1 /* leave key registered */, out publicKeyBlob, out publicKeyBlobSize) && publicKeyBlob != IntPtr.Zero)
                {
                    StrongNameHelpers.StrongNameFreeBuffer(publicKeyBlob);

                    t.KeyContainer = goodParameterValue;
                    Assert.Equal(goodParameterValue, t.KeyContainer); // "New KeyContainer value should be set"
                    CommandLine.ValidateHasParameter(t, @"/keycontainer:" + goodParameterValue, false /* no response file */);
                    Utilities.ExecuteTaskAndVerifyLogDoesNotContainErrorFromResource(t, "AxTlbBaseTask.StrongNameUtils.NoKeyPairInContainer", t.KeyContainer);
                }
                else
                {
                    Assert.True(false, "Key container could not be created (perhaps you are not running as admin).");
                }
            }
            finally
            {
                // remove key from CSP
                StrongNameHelpers.StrongNameKeyDelete(goodParameterValue);

                // get rid of the generated temp file
                if (goodParameterValue != null)
                {
                    File.Delete(goodParameterValue);
                }
            }
        }
Example #2
0
 private unsafe byte[] ComputePublicKey()
 {
     byte[] dest = (byte[])null;
     RuntimeHelpers.PrepareConstrainedRegions();
     try
     {
     }
     finally
     {
         IntPtr ppbPublicKeyBlob = IntPtr.Zero;
         int    pcbPublicKeyBlob = 0;
         try
         {
             if (!(!this._keyPairExported ? StrongNameHelpers.StrongNameGetPublicKey(this._keyPairContainer, (byte[])null, 0, out ppbPublicKeyBlob, out pcbPublicKeyBlob) : StrongNameHelpers.StrongNameGetPublicKey((string)null, this._keyPairArray, this._keyPairArray.Length, out ppbPublicKeyBlob, out pcbPublicKeyBlob)))
             {
                 throw new ArgumentException(Environment.GetResourceString("Argument_StrongNameGetPublicKey"));
             }
             dest = new byte[pcbPublicKeyBlob];
             Buffer.Memcpy(dest, 0, (byte *)ppbPublicKeyBlob.ToPointer(), 0, pcbPublicKeyBlob);
         }
         finally
         {
             if (ppbPublicKeyBlob != IntPtr.Zero)
             {
                 StrongNameHelpers.StrongNameFreeBuffer(ppbPublicKeyBlob);
             }
         }
     }
     return(dest);
 }
Example #3
0
        internal static bool GenerateStrongNameFile(string filename)
        {
            // variables that hold the unmanaged key
            IntPtr keyBlob       = IntPtr.Zero;
            int    generatedSize = 0;

            // create the key
            bool createdKey = StrongNameHelpers.StrongNameKeyGen(null,
                                                                 0 /*No flags. 1 is to save the key in the key container */,
                                                                 out keyBlob, out generatedSize);

            // if there was a problem, translate it and report it
            if (!createdKey || keyBlob == IntPtr.Zero)
            {
                throw Marshal.GetExceptionForHR(StrongNameHelpers.StrongNameErrorInfo());
            }

            try {
                Debug.Assert(keyBlob != IntPtr.Zero);

                // make sure the key size makes sense
                Debug.Assert(generatedSize > 0 && generatedSize <= Int32.MaxValue);
                if (generatedSize <= 0 || generatedSize > Int32.MaxValue)
                {
                    throw new InvalidOperationException(SR.GetString(SR.Browser_InvalidStrongNameKey));
                }

                // get the key into managed memory
                byte[] key = new byte[generatedSize];
                Marshal.Copy(keyBlob, key, 0, (int)generatedSize);

                // write the key to the specified file
                using (FileStream snkStream = new FileStream(filename, FileMode.Create, FileAccess.Write)) {
                    using (BinaryWriter snkWriter = new BinaryWriter(snkStream)) {
                        snkWriter.Write(key);
                    }
                }
            }
            finally {
                // release the unmanaged memory the key resides in
                if (keyBlob != IntPtr.Zero)
                {
                    StrongNameHelpers.StrongNameFreeBuffer(keyBlob);
                }
            }

            return(true);
        }
        [System.Security.SecurityCritical]  // auto-generated
        private unsafe byte[] ComputePublicKey()
        {
            byte[] publicKey = null;

            // Make sure pbPublicKey is not leaked with async exceptions
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
            }
            finally
            {
                IntPtr pbPublicKey = IntPtr.Zero;
                int    cbPublicKey = 0;

                try
                {
                    bool result;
                    if (_keyPairExported)
                    {
                        result = StrongNameHelpers.StrongNameGetPublicKey(null, _keyPairArray, _keyPairArray.Length,
                                                                          out pbPublicKey, out cbPublicKey);
                    }
                    else
                    {
                        result = StrongNameHelpers.StrongNameGetPublicKey(_keyPairContainer, null, 0,
                                                                          out pbPublicKey, out cbPublicKey);
                    }
                    if (!result)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_StrongNameGetPublicKey"));
                    }

                    publicKey = new byte[cbPublicKey];
                    Buffer.Memcpy(publicKey, 0, (byte *)(pbPublicKey.ToPointer()), 0, cbPublicKey);
                }
                finally
                {
                    if (pbPublicKey != IntPtr.Zero)
                    {
                        StrongNameHelpers.StrongNameFreeBuffer(pbPublicKey);
                    }
                }
            }
            return(publicKey);
        }
Example #5
0
 private unsafe byte[] ComputePublicKey()
 {
     byte[] dest = null;
     RuntimeHelpers.PrepareConstrainedRegions();
     try
     {
     }
     finally
     {
         IntPtr zero             = IntPtr.Zero;
         int    pcbPublicKeyBlob = 0;
         try
         {
             bool flag;
             if (this._keyPairExported)
             {
                 flag = StrongNameHelpers.StrongNameGetPublicKey(null, this._keyPairArray, this._keyPairArray.Length, out zero, out pcbPublicKeyBlob);
             }
             else
             {
                 flag = StrongNameHelpers.StrongNameGetPublicKey(this._keyPairContainer, (byte[])null, 0, out zero, out pcbPublicKeyBlob);
             }
             if (!flag)
             {
                 throw new ArgumentException(Environment.GetResourceString("Argument_StrongNameGetPublicKey"));
             }
             dest = new byte[pcbPublicKeyBlob];
             Buffer.memcpy((byte *)zero.ToPointer(), 0, dest, 0, pcbPublicKeyBlob);
         }
         finally
         {
             if (zero != IntPtr.Zero)
             {
                 StrongNameHelpers.StrongNameFreeBuffer(zero);
             }
         }
     }
     return(dest);
 }
Example #6
0
        private bool ResolveAssemblyKey()
        {
            bool pfxSuccess = true;

            if (!string.IsNullOrEmpty(KeyFile))
            {
                string keyFileExtension = String.Empty;
                try
                {
                    keyFileExtension = Path.GetExtension(KeyFile);
                }
                catch (ArgumentException ex)
                {
                    Log.LogErrorWithCodeFromResources("ResolveKeySource.InvalidKeyName", KeyFile, ex.Message);
                    pfxSuccess = false;
                }
                if (pfxSuccess)
                {
                    if (0 != String.Compare(keyFileExtension, pfxFileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        ResolvedKeyFile = KeyFile;
                    }
                    else
                    {
#if FEATURE_PFX_SIGNING
                        pfxSuccess = false;
                        // it is .pfx file. It is being imported into key container with name = "VS_KEY_<MD5 check sum of the encrypted file>"
                        FileStream fs = null;
                        try
                        {
                            string currentUserName = Environment.UserDomainName + "\\" + Environment.UserName;
                            // we use the curent user name to randomize the associated container name, i.e different user on the same machine will export to different keys
                            // this is because SNAPI by default will create keys in "per-machine" crypto store (visible for all the user) but will set the permission such only
                            // creator will be able to use it. This will make imposible for other user both to sign or export the key again (since they also can not delete that key).
                            // Now different users will use different container name. We use ToLower(invariant) because this is what the native equivalent of this function (Create new key, or VC++ import-er).
                            // use as well and we want to keep the hash (and key container name the same) otherwise user could be prompt for a password twice.
                            byte[] userNameBytes = System.Text.Encoding.Unicode.GetBytes(currentUserName.ToLower(CultureInfo.InvariantCulture));
                            fs = File.OpenRead(KeyFile);
                            int fileLength = (int)fs.Length;
                            var keyBytes   = new byte[fileLength];
                            fs.Read(keyBytes, 0, fileLength);

                            UInt64 hash = HashFromBlob(keyBytes);
                            hash ^= HashFromBlob(userNameBytes); // modify it with the username hash, so each user would get different hash for the same key

                            string hashedContainerName = pfxFileContainerPrefix + hash.ToString("X016", CultureInfo.InvariantCulture);

                            if (StrongNameHelpers.StrongNameGetPublicKey(hashedContainerName, IntPtr.Zero, 0, out IntPtr publicKeyBlob, out _) && publicKeyBlob != IntPtr.Zero)
                            {
                                StrongNameHelpers.StrongNameFreeBuffer(publicKeyBlob);
                                pfxSuccess = true;
                            }
                            else
                            {
                                Log.LogErrorWithCodeFromResources("ResolveKeySource.KeyFileForSignAssemblyNotImported", KeyFile, hashedContainerName);
                                Log.LogErrorWithCodeFromResources("ResolveKeySource.KeyImportError", KeyFile);
                            }
                            if (pfxSuccess)
                            {
                                ResolvedKeyContainer = hashedContainerName;
                            }
                        }