internal ECDiffieHellmanCngPublicKey(CngKey key) : base(key.Export(CngKeyBlobFormat.EccPublicBlob))
 {
     this.m_format = CngKeyBlobFormat.EccPublicBlob;
     new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
     this.m_key = CngKey.Open(key.Handle, key.IsEphemeral ? CngKeyHandleOpenOptions.EphemeralKey : CngKeyHandleOpenOptions.None);
     CodeAccessPermission.RevertAssert();
 }
Exemplo n.º 2
0
        /// <summary>
        /// Create a CNG Key and form as string.
        /// </summary>
        /// <param name="ca">The Algorithm.</param>
        /// <param name="cbf">The CNG Key Blob Format.</param>
        /// <returns>The key.</returns>
        public string GenerateCngKeyAsString(CngAlgorithm ca, CngKeyBlobFormat cbf)
        {
            CngKey ck = GenerateCngKey(ca);

            byte[] b = ck.Export(cbf);

            string[] s = new string[b.Length];

            int i = 0;

            foreach (byte v in b)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(v);

                s[i] = sb.ToString();
            }

            StringBuilder strb = new StringBuilder();

            foreach (string st in s)
            {
                strb.Append(st);
                strb.Append(',');
            }

            return(strb.ToString());
        }
Exemplo n.º 3
0
        private static byte[] ExportKeyBlob(SafeBCryptKeyHandle bCryptKeyHandle, CngKeyBlobFormat blobFormat)
        {
#if NETNATIVE
            // BCryptExportKey() not in the UWP api list.
            throw new PlatformNotSupportedException();
#else
            string blobFormatString = blobFormat.Format;

            int      numBytesNeeded = 0;
            NTSTATUS ntStatus       = Interop.BCrypt.BCryptExportKey(bCryptKeyHandle, IntPtr.Zero, blobFormatString, null, 0, out numBytesNeeded, 0);
            if (ntStatus != NTSTATUS.STATUS_SUCCESS)
            {
                throw new CryptographicException(Interop.mincore.GetMessage((int)ntStatus));
            }

            byte[] keyBlob = new byte[numBytesNeeded];
            ntStatus = Interop.BCrypt.BCryptExportKey(bCryptKeyHandle, IntPtr.Zero, blobFormatString, keyBlob, keyBlob.Length, out numBytesNeeded, 0);
            if (ntStatus != NTSTATUS.STATUS_SUCCESS)
            {
                throw new CryptographicException(Interop.mincore.GetMessage((int)ntStatus));
            }

            Array.Resize(ref keyBlob, numBytesNeeded);
            return(keyBlob);
#endif //NETNATIVE
        }
Exemplo n.º 4
0
        internal static CngKey Import(byte[] keyBlob, string curveName, CngKeyBlobFormat format, CngProvider provider)
        {
            if (keyBlob == null)
                throw new ArgumentNullException(nameof(keyBlob));
            if (format == null)
                throw new ArgumentNullException(nameof(format));
            if (provider == null)
                throw new ArgumentNullException(nameof(provider));

            SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider();
            SafeNCryptKeyHandle keyHandle = null;
            ErrorCode errorCode;
            
            if (curveName == null)
            {
                errorCode = Interop.NCrypt.NCryptImportKey(providerHandle, IntPtr.Zero, format.Format, IntPtr.Zero, out keyHandle, keyBlob, keyBlob.Length, 0);
                if (errorCode != ErrorCode.ERROR_SUCCESS)
                {
                    throw errorCode.ToCryptographicException();
                }
            }
            else
            {
#if !NETNATIVE
                keyHandle = ECCng.ImportKeyBlob(format.Format, keyBlob, curveName, providerHandle);
#endif //!NETNATIVE
            }

            CngKey key = new CngKey(providerHandle, keyHandle);

            // We can't tell directly if an OpaqueTransport blob imported as an ephemeral key or not
            key.IsEphemeral = format != CngKeyBlobFormat.OpaqueTransportBlob;

            return key;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Create a CNG Key and form as string, then export as a file.
        /// </summary>
        /// <param name="ca">The Algorithm.</param>
        /// <param name="cbf">The CNG Key Blob Format.</param>
        public void GenerateAndExportAsFile(string path, CngAlgorithm ca, CngKeyBlobFormat cbf)
        {
            StreamWriter sw = new StreamWriter(path);

            sw.Write(GenerateCngKeyAsString(ca, cbf));

            sw.Close();
        }
Exemplo n.º 6
0
        private byte[] ExportKeyBlob(bool includePrivateParameters)
        {
            // Use generic blob type for multiple version support
            CngKeyBlobFormat blobFormat = includePrivateParameters ?
                                          CngKeyBlobFormat.GenericPrivateBlob :
                                          CngKeyBlobFormat.GenericPublicBlob;

            return(Key.Export(blobFormat));
        }
Exemplo n.º 7
0
        internal static CngKey ImportKeyBlob(byte[] ecBlob, string curveName, bool includePrivateParameters)
        {
            CngKeyBlobFormat blobFormat = includePrivateParameters ? CngKeyBlobFormat.EccPrivateBlob : CngKeyBlobFormat.EccPublicBlob;
            CngKey           newKey     = CngKey.Import(ecBlob, curveName, blobFormat);

            newKey.ExportPolicy |= CngExportPolicies.AllowPlaintextExport;

            return(newKey);
        }
Exemplo n.º 8
0
        private void ImportKeyBlob(byte[] rsaBlob, bool includePrivate)
        {
            CngKeyBlobFormat blobFormat = includePrivate ? s_rsaPrivateBlob : s_rsaPublicBlob;

            CngKey newKey = CngKey.Import(rsaBlob, blobFormat);

            newKey.ExportPolicy |= CngExportPolicies.AllowPlaintextExport;

            Key = newKey;
        }
Exemplo n.º 9
0
 private static ECDsa DecodeECDsaPublicKey(CertificatePal certificatePal)
 {
     using (SafeBCryptKeyHandle bCryptKeyHandle = ImportPublicKeyInfo(certificatePal.CertContext))
     {
         CngKeyBlobFormat blobFormat = CngKeyBlobFormat.EccPublicBlob;
         byte[]           keyBlob    = ExportKeyBlob(bCryptKeyHandle, blobFormat);
         using (CngKey cngKey = CngKey.Import(keyBlob, blobFormat))
         {
             return(new ECDsaCng(cngKey));
         }
     }
 }
        private void ImportKeyBlob(byte[] dsaBlob, bool includePrivate)
        {
            // Use generic blob type for multiple version support
            CngKeyBlobFormat blobFormat = includePrivate ?
                CngKeyBlobFormat.GenericPrivateBlob :
                CngKeyBlobFormat.GenericPublicBlob;

            CngKey newKey = CngKey.Import(dsaBlob, blobFormat);
            newKey.ExportPolicy |= CngExportPolicies.AllowPlaintextExport;

            Key = newKey;
        }
        public static ECDsa GetECDsaPublicKey(this X509Certificate2 certificate)
        {
            if (LocalAppContextSwitches.UseLegacyPublicKeyBehavior)
            {
                return(LegacyGetECDsaPublicKey(certificate));
            }

            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }
            if (!IsECDsa(certificate))
            {
                return(null);
            }

            using (SafeCertContextHandle safeCertContext = X509Native.GetCertificateContext(certificate))
                using (SafeBCryptKeyHandle bcryptKeyHandle = ImportPublicKeyInfo(safeCertContext))
                {
                    if (bcryptKeyHandle.IsInvalid)
                    {
                        throw new CryptographicException("SR.GetString(SR.Cryptography_OpenInvalidHandle)");
                    }

                    string curveName = GetCurveName(bcryptKeyHandle);

                    if (curveName == null)
                    {
                        CngKeyBlobFormat blobFormat = HasExplicitParameters(bcryptKeyHandle) ?
                                                      CngKeyBlobFormat.EccFullPublicBlob : CngKeyBlobFormat.EccPublicBlob;

                        byte[] keyBlob = BCryptNative.ExportBCryptKey(bcryptKeyHandle, blobFormat.Format);
                        using (CngKey key = CngKey.Import(keyBlob, blobFormat))
                        {
                            return(new ECDsaCng(key));
                        }
                    }
                    else
                    {
                        CngKeyBlobFormat blobFormat = CngKeyBlobFormat.EccPublicBlob;
                        byte[]           keyBlob    = BCryptNative.ExportBCryptKey(bcryptKeyHandle, blobFormat.Format);
                        ECParameters     ecparams   = new ECParameters();
                        ExportNamedCurveParameters(ref ecparams, keyBlob, false);
                        ecparams.Curve = ECCurve.CreateFromFriendlyName(curveName);
                        ECDsaCng ecdsa = new ECDsaCng();
                        ecdsa.ImportParameters(ecparams);

                        return(ecdsa);
                    }
                }
        }
        private static PrivateKeyAlgorithmAndBytes AttemptToResolvePrivateKeyFromUserCertificate(X509Certificate2 userCertificate)
        {
            if (!userCertificate.HasPrivateKey)
            {
                throw new InvalidOperationException("In-memory certificate must have a private key assigned to it");
            }

#if (!NET45 && !NETSTANDARD1_3)
            const CngExportPolicies requiredPrivateKeyExportPolicies = CngExportPolicies.AllowPlaintextExport;
            CngKeyBlobFormat        exportFormat = CngKeyBlobFormat.Pkcs8PrivateBlob;

#if (!NET46)
            DSACng dsaCng = userCertificate.GetDSAPrivateKey() as DSACng;
            if (dsaCng != null)
            {
                using (dsaCng)
                {
                    if (!dsaCng.Key.ExportPolicy.HasFlag(requiredPrivateKeyExportPolicies))
                    {
                        throw new InvalidOperationException("In-memory certificate must be marked as exportable when importing to be used");
                    }

                    return(new PrivateKeyAlgorithmAndBytes(
                               PrivateKeyAlgorithm.DSA,
                               dsaCng.Key.Export(exportFormat)));
                }
            }
#endif

            RSACng rsaCng = userCertificate.GetRSAPrivateKey() as RSACng;
            if (rsaCng != null)
            {
                using (rsaCng)
                {
                    if (!rsaCng.Key.ExportPolicy.HasFlag(requiredPrivateKeyExportPolicies))
                    {
                        throw new InvalidOperationException("In-memory certificate must be marked as exportable when importing to be used");
                    }

                    return(new PrivateKeyAlgorithmAndBytes(
                               PrivateKeyAlgorithm.RSA,
                               rsaCng.Key.Export(exportFormat)));
                }
            }
#endif

            throw new InvalidOperationException("In-memory certificate has an unknown type of private key and cannot be used");
        }
        public static ECDiffieHellmanPublicKey FromByteArray(byte[] publicKeyBlob, CngKeyBlobFormat format) {
            if (publicKeyBlob == null) {
                throw new ArgumentNullException("publicKeyBlob");
            }
            if (format == null) {
                throw new ArgumentNullException("format");
            }

            using (CngKey imported = CngKey.Import(publicKeyBlob, format)) {
                if (imported.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) {
                    throw new ArgumentException(SR.GetString(SR.Cryptography_ArgECDHRequiresECDHKey));
                }

                return new ECDiffieHellmanCngPublicKey(imported);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        ///     Export the key out of the KSP
        /// </summary>
        public byte[] Export(CngKeyBlobFormat format)
        {
            if (format == null)
                throw new ArgumentNullException("format");

            int numBytesRequired;
            ErrorCode errorCode = Interop.NCrypt.NCryptExportKey(_keyHandle, IntPtr.Zero, format.Format, IntPtr.Zero, null, 0, out numBytesRequired, 0);
            if (errorCode != ErrorCode.ERROR_SUCCESS)
                throw errorCode.ToCryptographicException();

            byte[] buffer = new byte[numBytesRequired];
            errorCode = Interop.NCrypt.NCryptExportKey(_keyHandle, IntPtr.Zero, format.Format, IntPtr.Zero, buffer, numBytesRequired, out numBytesRequired, 0);
            if (errorCode != ErrorCode.ERROR_SUCCESS)
                throw errorCode.ToCryptographicException();

            return buffer;
        }
Exemplo n.º 15
0
        /// <summary>
        ///     Export the key out of the KSP
        /// </summary>
        public byte[] Export(CngKeyBlobFormat format)
        {
            if (format == null)
                throw new ArgumentNullException(nameof(format));

            int numBytesNeeded;
            ErrorCode errorCode = Interop.NCrypt.NCryptExportKey(_keyHandle, IntPtr.Zero, format.Format, IntPtr.Zero, null, 0, out numBytesNeeded, 0);
            if (errorCode != ErrorCode.ERROR_SUCCESS)
                throw errorCode.ToCryptographicException();

            byte[] buffer = new byte[numBytesNeeded];
            errorCode = Interop.NCrypt.NCryptExportKey(_keyHandle, IntPtr.Zero, format.Format, IntPtr.Zero, buffer, buffer.Length, out numBytesNeeded, 0);
            if (errorCode != ErrorCode.ERROR_SUCCESS)
                throw errorCode.ToCryptographicException();

            Array.Resize(ref buffer, numBytesNeeded);
            return buffer;
        }
Exemplo n.º 16
0
        private static byte[] ExportKeyBlob(SafeBCryptKeyHandle bCryptKeyHandle, CngKeyBlobFormat blobFormat)
        {
            throw new CryptographicException("Not implemented");
            // string blobFormatString = blobFormat.Format;

            // int numBytesNeeded = 0;
            // NTSTATUS ntStatus = Interop.BCrypt.BCryptExportKey(bCryptKeyHandle, IntPtr.Zero, blobFormatString, null, 0, out numBytesNeeded, 0);
            // if (ntStatus != NTSTATUS.STATUS_SUCCESS)
            //     throw new CryptographicException(Interop.Kernel32.GetMessage((int)ntStatus));

            // byte[] keyBlob = new byte[numBytesNeeded];
            // ntStatus = Interop.BCrypt.BCryptExportKey(bCryptKeyHandle, IntPtr.Zero, blobFormatString, keyBlob, keyBlob.Length, out numBytesNeeded, 0);
            // if (ntStatus != NTSTATUS.STATUS_SUCCESS)
            //     throw new CryptographicException(Interop.Kernel32.GetMessage((int)ntStatus));

            // Array.Resize(ref keyBlob, numBytesNeeded);
            // return keyBlob;
        }
        /// <inheritdoc/>
        public ICryptographicKey ImportPublicKey(byte[] keyBlob, CryptographicPublicKeyBlobType blobType)
        {
            Requires.NotNull(keyBlob, nameof(keyBlob));

            CngKeyBlobFormat format = GetPlatformKeyBlobType(blobType);
            CngKey?          key;

            try
            {
                key = CngKey.Import(keyBlob, format);
            }
            catch (NotImplementedException ex)
            {
                throw new PlatformNotSupportedException($"CngKey.Import(byte[], {format}) threw an exception.", ex);
            }

            return(new CngCryptographicKey(key, null, this.Algorithm));
        }
Exemplo n.º 18
0
        private void ExportKey()
        {
            CngKeyBlobFormat format = isPrivate ? CngKeyBlobFormat.EccPrivateBlob : CngKeyBlobFormat.EccPublicBlob;

            byte[] blob   = key.Export(format);
            byte[] length = new[] { blob[4], blob[5], blob[6], blob[7] };

            int partSize  = BitConverter.ToInt32(length, 0);
            int partCount = isPrivate ? 24 : 16;

            byte[][] keyParts = Arrays.Slice(Arrays.RightmostBits(blob, partSize * partCount), partSize);

            x = keyParts[0];
            y = keyParts[1];

            if (isPrivate)
            {
                d = keyParts[2];
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Hydrate a public key from a blob
        /// </summary>
        public static ECDiffieHellmanPublicKey FromByteArray(byte[] publicKeyBlob, CngKeyBlobFormat format)
        {
            if (publicKeyBlob == null)
            {
                throw new ArgumentNullException(nameof(publicKeyBlob));
            }
            if (format == null)
            {
                throw new ArgumentNullException(nameof(format));
            }

            // Verify that the key can import successfully, because we did in the past.
            using (CngKey imported = CngKey.Import(publicKeyBlob, format))
            {
                if (imported.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman)
                {
                    throw new ArgumentException(SR.Cryptography_ArgECDHRequiresECDHKey);
                }

                return(new ECDiffieHellmanCngPublicKey(publicKeyBlob, null, format));
            }
        }
Exemplo n.º 20
0
        public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format, CngProvider provider)
        {
            if (keyBlob == null)
                throw new ArgumentNullException("keyBlob");
            if (format == null)
                throw new ArgumentNullException("format");
            if (provider == null)
                throw new ArgumentNullException("provider");

            SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider();
            SafeNCryptKeyHandle keyHandle;
            ErrorCode errorCode = Interop.NCrypt.NCryptImportKey(providerHandle, IntPtr.Zero, format.Format, IntPtr.Zero, out keyHandle, keyBlob, keyBlob.Length, 0);
            if (errorCode != ErrorCode.ERROR_SUCCESS)
                throw errorCode.ToCryptographicException();

            CngKey key = new CngKey(providerHandle, keyHandle);

            // We can't tell directly if an OpaqueTransport blob imported as an ephemeral key or not
            key.IsEphemeral = format != CngKeyBlobFormat.OpaqueTransportBlob;

            return key;
        }
Exemplo n.º 21
0
        private static byte[] ExportKeyBlob(SafeBCryptKeyHandle bCryptKeyHandle, CngKeyBlobFormat blobFormat)
        {
            string blobFormatString = blobFormat.Format;

            int      numBytesNeeded;
            NTSTATUS ntStatus = Interop.BCrypt.BCryptExportKey(bCryptKeyHandle, IntPtr.Zero, blobFormatString, null, 0, out numBytesNeeded, 0);

            if (ntStatus != NTSTATUS.STATUS_SUCCESS)
            {
                throw new CryptographicException(Interop.Kernel32.GetMessage((int)ntStatus));
            }

            byte[] keyBlob = new byte[numBytesNeeded];
            ntStatus = Interop.BCrypt.BCryptExportKey(bCryptKeyHandle, IntPtr.Zero, blobFormatString, keyBlob, keyBlob.Length, out numBytesNeeded, 0);
            if (ntStatus != NTSTATUS.STATUS_SUCCESS)
            {
                throw new CryptographicException(Interop.Kernel32.GetMessage((int)ntStatus));
            }

            Array.Resize(ref keyBlob, numBytesNeeded);
            return(keyBlob);
        }
        internal ECDiffieHellmanCngPublicKey(CngKey key) : base(key.Export(CngKeyBlobFormat.EccPublicBlob)) {
            Contract.Requires(key != null && key.AlgorithmGroup == CngAlgorithmGroup.ECDiffieHellman);
            Contract.Ensures(m_format != null);

            m_format = CngKeyBlobFormat.EccPublicBlob;

            //
            // We need to make a copy of the key to prevent the situation where the ECDiffieHellmanCng algorithm
            // object is disposed (this disposing its key) before the ECDiffieHellmanCngPublic key is disposed.
            //
            // Accessing the handle in partial trust is safe because we're not exposing it back out to user code
            //

            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();

            // This looks odd, but .Handle returns a duplicate, so we need to dispose it
            using (SafeNCryptKeyHandle importKey = key.Handle) {
                m_key = CngKey.Open(importKey, key.IsEphemeral ? CngKeyHandleOpenOptions.EphemeralKey : CngKeyHandleOpenOptions.None);
            }

            CodeAccessPermission.RevertAssert();
        }
Exemplo n.º 23
0
        /// <summary>
        /// Imports a key from file.
        /// </summary>
        /// <param name="keyPath">Path to key.</param>
        /// <param name="kbF">The CNG Key Blob Format.</param>
        /// <returns>The key.</returns>
        public CngKey ImportKeyFromFile(string keyPath, CngKeyBlobFormat kbF)
        {
            StreamReader sr = new StreamReader(keyPath);

            string keyBlockStr = sr.ReadToEnd();

            sr.Close();

            string[] keyBlockStrArray = keyBlockStr.Split(',');

            byte[] keyBlock = new byte[keyBlockStrArray.Length];

            int i = 0;

            foreach (string item in keyBlockStrArray)
            {
                keyBlock[i] = byte.Parse(item);
                i++;
            }

            CngKey ck = CngKey.Import(keyBlock, kbF);

            return(ck);
        }
 public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format, CngProvider provider)
 {
     if (keyBlob == null)
     {
         throw new ArgumentNullException("keyBlob");
     }
     if (format == null)
     {
         throw new ArgumentNullException("format");
     }
     if (provider == null)
     {
         throw new ArgumentNullException("provider");
     }
     if (!NCryptNative.NCryptSupported)
     {
         throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported"));
     }
     if ((format != CngKeyBlobFormat.EccPublicBlob) && (format != CngKeyBlobFormat.GenericPublicBlob))
     {
         new KeyContainerPermission(KeyContainerPermissionFlags.Import).Demand();
     }
     SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider);
     return new CngKey(kspHandle, NCryptNative.ImportKey(kspHandle, keyBlob, format.Format)) { IsEphemeral = format != CngKeyBlobFormat.OpaqueTransportBlob };
 }
Exemplo n.º 25
0
        internal static byte[] ExportFullKeyBlob(CngKey key, bool includePrivateParameters)
        {
            CngKeyBlobFormat blobFormat = includePrivateParameters ? CngKeyBlobFormat.EccFullPrivateBlob : CngKeyBlobFormat.EccFullPublicBlob;

            return(key.Export(blobFormat));
        }
Exemplo n.º 26
0
        private static byte[] ExportKeyBlob(SafeBCryptKeyHandle bCryptKeyHandle, CngKeyBlobFormat blobFormat)
        {
#if NETNATIVE
            // BCryptExportKey() not in the UWP api list.
            throw new PlatformNotSupportedException();
#else
            string blobFormatString = blobFormat.Format;

            int numBytesNeeded = 0;
            NTSTATUS ntStatus = Interop.BCrypt.BCryptExportKey(bCryptKeyHandle, IntPtr.Zero, blobFormatString, null, 0, out numBytesNeeded, 0);
            if (ntStatus != NTSTATUS.STATUS_SUCCESS)
                throw new CryptographicException(Interop.mincore.GetMessage((int)ntStatus));

            byte[] keyBlob = new byte[numBytesNeeded];
            ntStatus = Interop.BCrypt.BCryptExportKey(bCryptKeyHandle, IntPtr.Zero, blobFormatString, keyBlob, keyBlob.Length, out numBytesNeeded, 0);
            if (ntStatus != NTSTATUS.STATUS_SUCCESS)
                throw new CryptographicException(Interop.mincore.GetMessage((int)ntStatus));

            Array.Resize(ref keyBlob, numBytesNeeded);
            return keyBlob;
#endif //NETNATIVE
        }
Exemplo n.º 27
0
 public byte[] Export(CngKeyBlobFormat format) {
     throw new NotImplementedException ();
 }
Exemplo n.º 28
0
 public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format, CngProvider provider) {
     throw new NotImplementedException ();
 }
Exemplo n.º 29
0
 public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format, CngProvider provider)
 {
     return Import(keyBlob, null, format, provider);
 }
Exemplo n.º 30
0
        //
        // Import factory methods
        //

        public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format)
        {
            return Import(keyBlob, format, provider: CngProvider.MicrosoftSoftwareKeyStorageProvider);
        }
Exemplo n.º 31
0
        public static unsafe byte[] ForceExport(this CngKey key, CngKeyBlobFormat format)
        {
            if ((key.ExportPolicy & CngExportPolicies.AllowPlaintextExport) != 0)
            {
                return(key.Export(format));
            }

            // The key is not exportable, lets hack. Thanks @bartonjs
            // https://stackoverflow.com/questions/57269726/x509certificate2-import-with-ncrypt-allow-plaintext-export-flag
            // https://stackoverflow.com/questions/55236230/export-private-key-pkcs8-of-cng-rsa-certificate-with-oldschool-net

            string blobType = "PKCS8_PRIVATEKEY";

            try
            {
                byte[] exported;

                fixed(byte *oidPtr = CryptNativeHelpers.PKCS12_3DES_OID)
                {
                    var salt      = ByteHelper.GetRandom(CryptNativeHelpers.NCrypt.PbeParams.RgbSaltSize);
                    var pbeParams = new CryptNativeHelpers.NCrypt.PbeParams();

                    pbeParams.Params.iIterations = 1;
                    pbeParams.Params.cbSalt      = salt.Length;
                    Marshal.Copy(salt, 0, (IntPtr)pbeParams.rgbSalt, salt.Length);

                    var buffers = stackalloc CryptNativeHelpers.NCrypt.NCryptBuffer[3];

                    buffers[0] = new CryptNativeHelpers.NCrypt.NCryptBuffer
                    {
                        BufferType = CryptNativeHelpers.NCrypt.BufferType.PkcsSecret,
                        cbBuffer   = 0,
                        pvBuffer   = IntPtr.Zero,
                    };
                    buffers[1] = new CryptNativeHelpers.NCrypt.NCryptBuffer
                    {
                        BufferType = CryptNativeHelpers.NCrypt.BufferType.PkcsAlgOid,
                        cbBuffer   = CryptNativeHelpers.PKCS12_3DES_OID.Length,
                        pvBuffer   = (IntPtr)oidPtr,
                    };
                    buffers[2] = new CryptNativeHelpers.NCrypt.NCryptBuffer
                    {
                        BufferType = CryptNativeHelpers.NCrypt.BufferType.PkcsAlgParam,
                        cbBuffer   = sizeof(CryptNativeHelpers.NCrypt.PbeParams),
                        pvBuffer   = (IntPtr)(&pbeParams),
                    };
                    var desc = new CryptNativeHelpers.NCrypt.NCryptBufferDesc
                    {
                        cBuffers  = 3,
                        pBuffers  = (IntPtr)buffers,
                        ulVersion = 0,
                    };

                    if (CryptNativeHelpers.NCrypt.NCryptExportKey(key.Handle, IntPtr.Zero, blobType, ref desc, null, 0, out int bytesNeeded, 0) != 0)
                    {
                        return(null);
                    }

                    exported = new byte[bytesNeeded];
                    if (CryptNativeHelpers.NCrypt.NCryptExportKey(key.Handle, IntPtr.Zero, blobType, ref desc, exported, exported.Length, out bytesNeeded, 0) != 0)
                    {
                        return(null);
                    }
                }

                fixed(char *keyNamePtr = key.KeyName)
                fixed(byte *blobPtr = exported)
                {
                    var buffers = stackalloc CryptNativeHelpers.NCrypt.NCryptBuffer[2];

                    buffers[0] = new CryptNativeHelpers.NCrypt.NCryptBuffer
                    {
                        BufferType = CryptNativeHelpers.NCrypt.BufferType.PkcsSecret,
                        cbBuffer   = 0,
                        pvBuffer   = IntPtr.Zero,
                    };
                    buffers[1] = new CryptNativeHelpers.NCrypt.NCryptBuffer
                    {
                        BufferType = CryptNativeHelpers.NCrypt.BufferType.PkcsName,
                        cbBuffer   = checked (2 * (key.KeyName.Length + 1)),
                        pvBuffer   = new IntPtr(keyNamePtr),
                    };
                    var desc = new CryptNativeHelpers.NCrypt.NCryptBufferDesc
                    {
                        cBuffers  = 2,
                        pBuffers  = (IntPtr)buffers,
                        ulVersion = 0,
                    };

                    SafeNCryptKeyHandle keyHandle;

                    if (CryptNativeHelpers.NCrypt.NCryptImportKey(key.ProviderHandle, IntPtr.Zero, blobType, ref desc, out keyHandle, new IntPtr(blobPtr), exported.Length,
                                                                  CryptNativeHelpers.NCrypt.NCryptImportFlags.NCRYPT_OVERWRITE_KEY_FLAG | CryptNativeHelpers.NCrypt.NCryptImportFlags.NCRYPT_DO_NOT_FINALIZE_FLAG) != 0)
                    {
                        keyHandle.Dispose();
                        return(null);
                    }

                    using (keyHandle)
                        using (CngKey cngKey = CngKey.Open(keyHandle, CngKeyHandleOpenOptions.None))
                        {
                            cngKey.SetProperty(new CngProperty("Export Policy", BitConverter.GetBytes((int)CngExportPolicies.AllowPlaintextExport), CngPropertyOptions.Persist));

                            if (CryptNativeHelpers.NCrypt.NCryptFinalizeKey(keyHandle, 0) != 0)
                            {
                                return(null);
                            }

                            return(cngKey.Export(format));
                        }
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemplo n.º 32
0
 /// <summary>
 /// Wrap a CNG key
 /// </summary>
 internal ECDiffieHellmanCngPublicKey(byte[] keyBlob, string curveName, CngKeyBlobFormat format) : base(keyBlob)
 {
     _format = format;
     // Can be null for P256, P384, P521, or an explicit blob
     _curveName = curveName;
 }
Exemplo n.º 33
0
        bool IKeyManagementDriver.LoadKeyBlob(int session, IntPtr pKey, int keyLen, KeyType keyType, KeyAttribute keyAttrib, out int hKey)
        {
            bool bRet = false;

            hKey = -1;

            try
            {
                SessionData             ctx    = ((SessionDriver)this.Hal.Session).GetSessionCtx(session);
                CryptokiObjectMgrDriver objMgr = (CryptokiObjectMgrDriver)Hal.CryptokiObjectMgr;

                byte[] keyData = new byte[keyLen];

                Marshal.Copy(pKey, keyData, 0, keyLen);

                if (keyAttrib == KeyAttribute.Secret)
                {
                    SecretKey key = new SecretKey(keyLen * 8, keyData);

                    hKey = ctx.ObjectCtx.AddObject(CryptokiObjectType.Key, new KeyData(keyData, key));

                    bRet = true;
                }
                else
                {
                    switch (keyType)
                    {
                    case KeyType.RSA:
                        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                        rsa.ImportCspBlob(keyData);

                        hKey = ctx.ObjectCtx.AddObject(CryptokiObjectType.Key, new KeyData(rsa.ExportCspBlob(0 != (keyAttrib & KeyAttribute.Private)), rsa));

                        bRet = true;
                        break;

                    case KeyType.DSA:
                        DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
                        dsa.ImportCspBlob(keyData);

                        hKey = ctx.ObjectCtx.AddObject(CryptokiObjectType.Key, new KeyData(dsa.ExportCspBlob(0 != (keyAttrib & KeyAttribute.Private)), dsa));

                        bRet = true;
                        break;

                    case KeyType.ECDSA:
                    {
                        CngKeyBlobFormat fmt = (0 == (keyAttrib & KeyAttribute.Private)) ? CngKeyBlobFormat.EccPublicBlob : CngKeyBlobFormat.EccPrivateBlob;

                        CngKey   key = CngKey.Import(keyData, fmt);
                        ECDsaCng ec  = new ECDsaCng(key);

                        hKey = ctx.ObjectCtx.AddObject(CryptokiObjectType.Key, new KeyData(ec.Key.Export(fmt), ec));
                        bRet = true;
                    }
                    break;

                    case KeyType.DH:
                    {
                        CngKeyBlobFormat fmt = (0 == (keyAttrib & KeyAttribute.Private)) ? CngKeyBlobFormat.EccPublicBlob : CngKeyBlobFormat.EccPrivateBlob;
                        CngKey           key = CngKey.Import(keyData, fmt);

                        ECDiffieHellmanCng ecdh = new ECDiffieHellmanCng(key);

                        hKey = ctx.ObjectCtx.AddObject(CryptokiObjectType.Key, new KeyData(ecdh.Key.Export(fmt), ecdh));
                        bRet = true;
                    }
                    break;
                    }
                }
            }
            catch
            {
                return(false);
            }

            return(bRet);
        }
Exemplo n.º 34
0
        public byte[] Export(CngKeyBlobFormat format) {
            Contract.Assert(m_keyHandle != null);

            if (format == null) {
                throw new ArgumentNullException("format");
            }

            KeyContainerPermission permission = BuildKeyContainerPermission(KeyContainerPermissionFlags.Export);
            if (permission != null) {
                permission.Demand();
            }

            return NCryptNative.ExportKey(m_keyHandle, format.Format);
        }
    public static ECDiffieHellmanPublicKey FromByteArray(byte[] publicKeyBlob, CngKeyBlobFormat format)
    {
      Contract.Ensures(Contract.Result<System.Security.Cryptography.ECDiffieHellmanPublicKey>() != null);

      return default(ECDiffieHellmanPublicKey);
    }
Exemplo n.º 36
0
        //
        // Import factory methods
        //

        public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format) {
            Contract.Ensures(Contract.Result<CngKey>() != null);
            return Import(keyBlob, format, CngProvider.MicrosoftSoftwareKeyStorageProvider);
        }
Exemplo n.º 37
0
 /// <summary>キー・マテリアルを派生</summary>
 /// <param name="exchangeKeyOfPartner">相方の交換鍵</param>
 /// <param name="ckbf">CngKeyBlobFormat</param>
 public void DeriveKeyMaterial(byte[] exchangeKeyOfPartner, CngKeyBlobFormat ckbf)
 {
     // 交換鍵から、暗号化に使用する秘密鍵を生成
     this._privateKey = ((ECDiffieHellmanCng)this._asa).
                        DeriveKeyMaterial(CngKey.Import(exchangeKeyOfPartner, ckbf));
 }
Exemplo n.º 38
0
 public ECDiffieHellmanAgreement(ECDiffieHellmanKeyDerivationFunction function, CngAlgorithm algorithm, CngKeyBlobFormat format)
 {
     this.keyDerivationFunction = function;
     this.algorithm = algorithm;
     this.keyBlobFormat = format;
 }
Exemplo n.º 39
0
 internal static CngKey Import(byte[] keyBlob, string curveName, CngKeyBlobFormat format)
 {
     return Import(keyBlob, curveName, format, provider: CngProvider.MicrosoftSoftwareKeyStorageProvider);
 }
    public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format)
    {
      Contract.Ensures(Contract.Result<System.Security.Cryptography.CngKey>() != null);

      return default(CngKey);
    }
Exemplo n.º 41
0
        public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format, CngProvider provider) {
            Contract.Ensures(Contract.Result<CngKey>() != null);

            if (keyBlob == null) {
                throw new ArgumentNullException("keyBlob"); 
            }
            if (format == null) {
                throw new ArgumentNullException("format");
            }
            if (provider == null) {
                throw new ArgumentNullException("provider");
            }

            // Make sure that NCrypt is supported on this platform
            if (!NCryptNative.NCryptSupported) {
                throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
            }

            // If we don't know for sure that the key will be ephemeral, then we need to demand Import
            // permission.  Since we won't know the name of the key until it's too late, we demand a full Import
            // rather than one scoped to the key.
            bool safeKeyImport = format == CngKeyBlobFormat.EccPublicBlob ||
                                 format == CngKeyBlobFormat.GenericPublicBlob;

            if (!safeKeyImport) {
                new KeyContainerPermission(KeyContainerPermissionFlags.Import).Demand();
            }

            // Import the key into the KSP
            SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider);
            SafeNCryptKeyHandle keyHandle = NCryptNative.ImportKey(kspHandle, keyBlob, format.Format);

            // Prepare the key for use
            CngKey key = new CngKey(kspHandle, keyHandle);
            
            // We can't tell directly if an OpaqueTransport blob imported as an ephemeral key or not
            key.IsEphemeral = format != CngKeyBlobFormat.OpaqueTransportBlob;

            return key;
        }
    public byte[] Export(CngKeyBlobFormat format)
    {
      Contract.Ensures(Contract.Result<byte[]>() != null);

      return default(byte[]);
    }