100 {
103 {
104 global::Interop.NCrypt.NCryptBuffer* ptr = stackalloc global::Interop.NCrypt.NCryptBuffer[3];
105 global::Interop.NCrypt.PBE_PARAMS pBE_PARAMS = default(global::Interop.NCrypt.PBE_PARAMS);
106 Span<byte> data = new Span<byte>(pBE_PARAMS.rgbSalt, 8);
107 RandomNumberGenerator.Fill(data);
108 pBE_PARAMS.Params.cbSalt = data.Length;
109 pBE_PARAMS.Params.iIterations = kdfCount;
110 *ptr = new global::Interop.NCrypt.NCryptBuffer
111 {
112 BufferType = global::Interop.NCrypt.BufferType.PkcsSecret,
113 cbBuffer = checked(2 * (password.
Length + 1)),
114 pvBuffer = safeUnicodeStringHandle.DangerousGetHandle()
115 };
116 if (ptr->pvBuffer ==
IntPtr.Zero)
117 {
118 ptr->cbBuffer = 0;
119 }
120 ptr[1] = new global::Interop.NCrypt.NCryptBuffer
121 {
122 BufferType = global::Interop.NCrypt.BufferType.PkcsAlgOid,
125 };
126 ptr[2] = new global::Interop.NCrypt.NCryptBuffer
127 {
128 BufferType = global::Interop.NCrypt.BufferType.PkcsAlgParam,
129 cbBuffer = sizeof(global::Interop.NCrypt.PBE_PARAMS),
130 pvBuffer = (IntPtr)(&pBE_PARAMS)
131 };
132 global::Interop.NCrypt.NCryptBufferDesc nCryptBufferDesc = default(global::Interop.NCrypt.NCryptBufferDesc);
133 nCryptBufferDesc.cBuffers = 3;
134 nCryptBufferDesc.pBuffers = (
IntPtr)ptr;
135 nCryptBufferDesc.ulVersion = 0;
136 global::Interop.NCrypt.NCryptBufferDesc pParameterList = nCryptBufferDesc;
137 global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptExportKey(keyHandle,
IntPtr.Zero,
"PKCS8_PRIVATEKEY", ref pParameterList, ref
MemoryMarshal.GetReference(
default(Span<byte>)), 0, out var pcbResult, 0);
138 if (errorCode != 0)
139 {
140 throw errorCode.ToCryptographicException();
141 }
142 allocated = null;
143 if (allocate)
144 {
145 allocated = new byte[pcbResult];
147 }
149 {
150 bytesWritten = 0;
151 return false;
152 }
154 if (errorCode != 0)
155 {
156 throw errorCode.ToCryptographicException();
157 }
159 {
160 byte[]
array =
new byte[pcbResult];
162 CryptographicOperations.ZeroMemory(allocated.AsSpan(0, pcbResult));
164 }
165 bytesWritten = pcbResult;
166 return true;
167 }
168 }
static readonly byte[] s_pkcs12TripleDesOidBytes