【发布时间】:2019-12-30 20:59:01
【问题描述】:
我有一些工作 C# 代码可以处理一些 Windows API 调用(基于 my Get-CertificatePath.ps1 PowerShell script),但 F# 版本失败。我确定我遗漏了一些东西,很可能是一个属性,但我无法弄清楚。
有没有办法让 F# 版本正常工作?
keyname.csx
使用microsoft-build-tools Chocolatey 包中的csi.exe 运行。
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
public static class CryptoApi
{
[DllImport("crypt32.dll")]
internal static extern SafeNCryptKeyHandle CertDuplicateCertificateContext(IntPtr certContext); // CERT_CONTEXT *
[DllImport("crypt32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool
CryptAcquireCertificatePrivateKey(SafeNCryptKeyHandle pCert,
uint dwFlags,
IntPtr pvReserved, // void *
[Out] out SafeNCryptKeyHandle phCryptProvOrNCryptKey,
[Out] out int dwKeySpec,
[Out, MarshalAs(UnmanagedType.Bool)] out bool pfCallerFreeProvOrNCryptKey);
[SecurityCritical]
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
public static string GetCngUniqueKeyContainerName(X509Certificate2 certificate)
{
SafeNCryptKeyHandle privateKey = null;
int keySpec = 0;
bool freeKey = true;
CryptAcquireCertificatePrivateKey(CertDuplicateCertificateContext(certificate.Handle),
0x00040000, // AcquireOnlyNCryptKeys
IntPtr.Zero, out privateKey, out keySpec, out freeKey);
return CngKey.Open(privateKey, CngKeyHandleOpenOptions.None).UniqueName;
}
}
X509Certificate2 getMyCert(string subject)
{
using(var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.OpenExistingOnly);
var certs = store.Certificates.Find(X509FindType.FindBySubjectName, subject, false);
Console.WriteLine("found {0} certs", certs.Count);
store.Close();
return certs[0];
}
}
var cert = getMyCert("localhost");
Console.WriteLine("private key? {0}", cert.HasPrivateKey);
Console.WriteLine("key name: {0}", CryptoApi.GetCngUniqueKeyContainerName(cert));
输出是:
found 1 certs
private key? True
key name: 32fd60███████████████████████████████████-████-████-████-████████████
keyname.fsx
使用 dotnet fsi 运行(版本 3.1.100;Chocolatey 包 dotnetcore 在此发布时)。
#load ".paket/load/netstandard2.1/System.Security.Cryptography.Cng.fsx"
#load ".paket/load/netstandard2.1/System.Security.Cryptography.X509Certificates.fsx"
open System
open System.Diagnostics.CodeAnalysis
open System.Runtime.ConstrainedExecution
open System.Runtime.InteropServices
open System.Security
open System.Security.Cryptography
open System.Security.Cryptography.X509Certificates
open System.Security.Permissions
open Microsoft.Win32.SafeHandles
type CryptoApi () =
[<DllImport("crypt32.dll", CallingConvention = CallingConvention.Cdecl)>]
static extern SafeNCryptKeyHandle internal CertDuplicateCertificateContext(IntPtr certContext) // CERT_CONTEXT *
[<DllImport("crypt32.dll", CallingConvention = CallingConvention.Cdecl, SetLastError = true)>]
static extern [<MarshalAs(UnmanagedType.Bool)>] bool internal
CryptAcquireCertificatePrivateKey(SafeNCryptKeyHandle pCert,
uint32 dwFlags,
IntPtr pvReserved, // void *
SafeNCryptKeyHandle& phCryptProvOrNCryptKey,
int& dwKeySpec,
[<MarshalAs(UnmanagedType.Bool)>] bool& pfCallerFreeProvOrNCryptKey)
[<SecurityCritical>]
[<SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)>]
static member GetCngUniqueKeyContainerName (certificate : X509Certificate2) =
let mutable privateKey : SafeNCryptKeyHandle = null
let mutable keySpec = 0
let mutable freeKey = true
CryptAcquireCertificatePrivateKey(CertDuplicateCertificateContext(certificate.Handle),
0x00040000u, // AcquireOnlyNCryptKeys
IntPtr.Zero, &privateKey, &keySpec, &freeKey) |> ignore
CngKey.Open(privateKey, CngKeyHandleOpenOptions.None).UniqueName
let getMyCert subject =
use store = new X509Store(StoreName.My, StoreLocation.CurrentUser)
store.Open(OpenFlags.OpenExistingOnly)
let certs = store.Certificates.Find(X509FindType.FindBySubjectName, subject, false)
printfn "found %d certs" certs.Count
store.Close()
certs.[0]
let cert = getMyCert "localhost"
printfn "private key? %b" cert.HasPrivateKey
CryptoApi.GetCngUniqueKeyContainerName(cert) |> printfn "%s"
输出是:
found 1 certs
private key? true
System.ArgumentNullException: SafeHandle cannot be null. (Parameter 'pHandle')
at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
at System.StubHelpers.StubHelpers.AddToCleanupList(CleanupWorkListElement& pCleanupWorkList, SafeHandle handle)
at FSI_0003.CryptoApi.CryptAcquireCertificatePrivateKey(SafeNCryptKeyHandle pCert, UInt32 dwFlags, IntPtr pvReserved, SafeNCryptKeyHandle& phCryptProvOrNCryptKey, Int32& dwKeySpec, Boolean& pfCallerFreeProvOrNCryptKey)
at FSI_0003.CryptoApi.GetCngUniqueKeyContainerName(X509Certificate2 certificate)
at <StartupCode$FSI_0003>.$FSI_0003.main@()
Stopped due to error
paket.dependencies
这是上述 .fsx 文件运行所必需的,然后运行 paket install。
generate_load_scripts: true
source https://api.nuget.org/v3/index.json
storage: none
framework: netcore3.0, netstandard2.0, netstandard2.1
nuget System.Security.Cryptography.Cng
nuget System.Security.Cryptography.X509Certificates
编辑:初始化let mutable privateKey = new SafeNCryptKeyHandle () 似乎可以解决问题。
【问题讨论】:
-
&privateKey/&keySpec/&freeKey是否正确匹配SafeNCryptKeyHandle&/int&/bool&类型?请参考文档上的类型对应:docs.microsoft.com/en-us/dotnet/fsharp/language-reference/… -
@DrakeWu-MSFT 是的,至少它们彼此匹配(否则 F# 将无法编译),但我想确认声明是否准确映射到 WinAPI C++ 声明。 pinvoke.net/default.aspx/…