/// <summary> /// Get the public key from a key pair blob /// </summary> /// <exception cref="ArgumentNullException"> /// If <paramref name="keyPair"/> is null /// </exception> /// <exception cref="InvalidOperationException"> /// If the key could not be extracted /// </exception> /// <param name="keyPair">key blob to get the public key from</param> /// <returns>public key blob</returns> public static byte[] ExtractPublicKeyFromKeyPair(byte[] keyPair) { if (keyPair == null) { throw new ArgumentNullException("keyPair"); } // extract the public key portion of the blob IntPtr publicKeyBuffer = IntPtr.Zero; try { int publicKeyBlobSize = 0; if (!StrongNameNative.StrongNameGetPublicKey( null, keyPair, keyPair.Length, out publicKeyBuffer, out publicKeyBlobSize)) { Marshal.ThrowExceptionForHR(StrongNameNative.StrongNameErrorInfo()); } // copy the key out of unmanaged memory, and return it byte[] publicKeyBlob = new byte[publicKeyBlobSize]; Marshal.Copy(publicKeyBuffer, publicKeyBlob, 0, publicKeyBlobSize); return(publicKeyBlob); } finally { if (publicKeyBuffer != IntPtr.Zero) { StrongNameNative.StrongNameFreeBuffer(publicKeyBuffer); } } }
/// <summary> /// Get the public key from a key container /// </summary> /// <exception cref="ArgumentNullException"> /// If <paramref name="keyContainer"/> is null /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="keyContainer"/> is empty /// </exception> /// <exception cref="InvalidOperationException"> /// If the key could not be extracted /// </exception> /// <param name="keyContainer">key container to get the public key from</param> /// <returns>public key blob</returns> public static byte[] ExtractPublicKeyFromKeyContainer(string keyContainerName) { if (string.IsNullOrEmpty(keyContainerName)) { throw new ArgumentNullOrEmptyException("keyContainerName"); } // extract the public key portion of the blob IntPtr publicKeyBuffer = IntPtr.Zero; try { int publicKeyBlobSize = 0; if (!StrongNameNative.StrongNameGetPublicKey( keyContainerName, null, 0, out publicKeyBuffer, out publicKeyBlobSize)) { Marshal.ThrowExceptionForHR(StrongNameNative.StrongNameErrorInfo()); } // copy the key out of unmanaged memory, and return it byte[] publicKeyBlob = new byte[publicKeyBlobSize]; Marshal.Copy(publicKeyBuffer, publicKeyBlob, 0, publicKeyBlobSize); return(publicKeyBlob); } finally { if (publicKeyBuffer != IntPtr.Zero) { StrongNameNative.StrongNameFreeBuffer(publicKeyBuffer); } } }