Пример #1
0
        /// <summary>
        /// Generate a key pair blob
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="keySize"/> is not positive
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// If the key could not be generated
        /// </exception>
        /// <param name="keySize">size, in bits, of the key to generate</param>
        /// <returns>generated key pair blob</returns>
        public static byte[] GenerateKeyPair(int keySize)
        {
            if (keySize <= 0)
            {
                throw new ArgumentOutOfRangeException("keySize");
            }

            // variables that hold the unmanaged key
            IntPtr keyBlob       = IntPtr.Zero;
            long   generatedSize = 0;

            try
            {
                // create the key
                if (!StrongNameNative.StrongNameKeyGenEx(
                        null, StrongNameKeyGenFlags.None, (int)keySize,
                        out keyBlob, out generatedSize))
                {
                    Marshal.ThrowExceptionForHR(StrongNameNative.StrongNameErrorInfo());
                }

                // make sure the key size makes sense
                if (generatedSize <= 0 || generatedSize > int.MaxValue)
                {
                    throw new InvalidOperationException();
                }

                // get the key into managed memory
                byte[] key = new byte[generatedSize];
                Marshal.Copy(keyBlob, key, 0, (int)generatedSize);
                return(key);
            }
            finally
            {
                // release the unmanaged memory the key resides in
                if (keyBlob != IntPtr.Zero)
                {
                    StrongNameNative.StrongNameFreeBuffer(keyBlob);
                }
            }
        }