public static CngKey Create(CngAlgorithm algorithm, string keyName, CngKeyCreationParameters creationParameters) { if (algorithm == null) { throw new ArgumentNullException("algorithm"); } if (creationParameters == null) { creationParameters = new CngKeyCreationParameters(); } if (!NCryptNative.NCryptSupported) { throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported")); } if (keyName != null) { KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Create) { ProviderName = creationParameters.Provider.Provider }; KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); permission.AccessEntries.Add(accessEntry); permission.Demand(); } SafeNCryptProviderHandle provider = NCryptNative.OpenStorageProvider(creationParameters.Provider.Provider); SafeNCryptKeyHandle keyHandle = NCryptNative.CreatePersistedKey(provider, algorithm.Algorithm, keyName, creationParameters.KeyCreationOptions); SetKeyProperties(keyHandle, creationParameters); NCryptNative.FinalizeKey(keyHandle); CngKey key = new CngKey(provider, keyHandle); if (keyName == null) { key.IsEphemeral = true; } return key; }
[System.Security.SecurityCritical] // auto-generated internal CspKeyContainerInfo (CspParameters parameters, bool randomKeyContainer) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open); kp.AccessEntries.Add(entry); kp.Demand(); m_parameters = new CspParameters(parameters); if (m_parameters.KeyNumber == -1) { if (m_parameters.ProviderType == Constants.PROV_RSA_FULL || m_parameters.ProviderType == Constants.PROV_RSA_AES) m_parameters.KeyNumber = Constants.AT_KEYEXCHANGE; else if (m_parameters.ProviderType == Constants.PROV_DSS_DH) m_parameters.KeyNumber = Constants.AT_SIGNATURE; } m_randomKeyContainer = randomKeyContainer; }
internal CspKeyContainerInfo(CspParameters parameters, bool randomKeyContainer) { KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open); permission.AccessEntries.Add(accessEntry); permission.Demand(); this.m_parameters = new CspParameters(parameters); if (this.m_parameters.KeyNumber == -1) { if ((this.m_parameters.ProviderType == 1) || (this.m_parameters.ProviderType == 0x18)) { this.m_parameters.KeyNumber = 1; } else if (this.m_parameters.ProviderType == 13) { this.m_parameters.KeyNumber = 2; } } this.m_randomKeyContainer = randomKeyContainer; }
public byte[] Decrypt(byte[] rgb, bool fOAEP) { if (rgb == null) { throw new ArgumentNullException("rgb"); } this.GetKeyPair(); if (rgb.Length > (this.KeySize / 8)) { throw new CryptographicException(Environment.GetResourceString("Cryptography_Padding_DecDataTooBig", new object[] { this.KeySize / 8 })); } if (!this.CspKeyContainerInfo.RandomlyGenerated) { KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(this._parameters, KeyContainerPermissionFlags.Decrypt); permission.AccessEntries.Add(accessEntry); permission.Demand(); } byte[] o = null; DecryptKey(this._safeKeyHandle, rgb, rgb.Length, fOAEP, JitHelpers.GetObjectHandleOnStack<byte[]>(ref o)); return o; }
[System.Security.SecuritySafeCritical] // auto-generated private void LoadCertificateFromBlob (byte[] rawData, object password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyOrNullArray"), "rawData"); Contract.EndContractBlock(); X509ContentType contentType = X509Utils.MapContentType(X509Utils._QueryCertBlobType(rawData)); #if !FEATURE_CORECLR && !FEATURE_PAL if (contentType == X509ContentType.Pkcs12 && (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create); kp.Demand(); } #endif // !FEATURE_CORECLR && !FEATURE_PAL uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags); IntPtr szPassword = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { szPassword = X509Utils.PasswordToHGlobalUni(password); X509Utils._LoadCertFromBlob(rawData, szPassword, dwFlags, #if FEATURE_CORECLR false, #else // FEATURE_CORECLR (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == 0 ? false : true, #endif // FEATURE_CORECLR else ref m_safeCertContext); } finally { if (szPassword != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(szPassword); } }
private void CounterSign(CmsSigner signer) { CspParameters parameters = new CspParameters(); if (!System.Security.Cryptography.X509Certificates.X509Utils.GetPrivateKeyInfo(System.Security.Cryptography.X509Certificates.X509Utils.GetCertContext(signer.Certificate), ref parameters)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Sign | KeyContainerPermissionFlags.Open); permission.AccessEntries.Add(accessEntry); permission.Demand(); uint dwIndex = (uint) PkcsUtils.GetSignerIndex(this.m_signedCms.GetCryptMsgHandle(), this, 0); System.Security.Cryptography.SafeLocalAllocHandle handle = System.Security.Cryptography.CAPI.LocalAlloc(0x40, new IntPtr(Marshal.SizeOf(typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_ENCODE_INFO)))); System.Security.Cryptography.CAPI.CMSG_SIGNER_ENCODE_INFO structure = PkcsUtils.CreateSignerEncodeInfo(signer); try { Marshal.StructureToPtr(structure, handle.DangerousGetHandle(), false); if (!System.Security.Cryptography.CAPI.CryptMsgCountersign(this.m_signedCms.GetCryptMsgHandle(), dwIndex, 1, handle.DangerousGetHandle())) { throw new CryptographicException(Marshal.GetLastWin32Error()); } this.m_signedCms.ReopenToDecode(); } finally { Marshal.DestroyStructure(handle.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_ENCODE_INFO)); handle.Dispose(); structure.Dispose(); } PkcsUtils.AddCertsToMessage(this.m_signedCms.GetCryptMsgHandle(), this.m_signedCms.Certificates, PkcsUtils.CreateBagOfCertificates(signer)); }
SafeCertStoreHandle PFXImportCertStore( [In] uint dwObjectType, [In] object pvObject, [In] string szPassword, [In] uint dwFlags, [In] bool persistKeyContainers) { if (pvObject == null) throw new ArgumentNullException("pvObject"); byte[] pbData = null; if (dwObjectType == CERT_QUERY_OBJECT_FILE) { pbData = File.ReadAllBytes((string)pvObject); } else { pbData = (byte[]) pvObject; } #if !FEATURE_CORESYSTEM if (persistKeyContainers) { // // Right now, we always demand KeyContainerPermission regardless of whether the PFX contains a private key or not. // We could avoid that by looping through the certs in the store and find out whether there are actually private keys. // if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create); kp.Demand(); } } #endif SafeCertStoreHandle safeCertStoreHandle = SafeCertStoreHandle.InvalidHandle; GCHandle handle = GCHandle.Alloc(pbData, GCHandleType.Pinned); IntPtr ptr = handle.AddrOfPinnedObject(); try { CRYPTOAPI_BLOB certBlob; certBlob.cbData = (uint) pbData.Length; certBlob.pbData = ptr; safeCertStoreHandle = CAPIMethods.PFXImportCertStore(new IntPtr(&certBlob), szPassword, dwFlags); } finally { if (handle.IsAllocated) handle.Free(); } if (!safeCertStoreHandle.IsInvalid) { // // If the user did not want us to persist private keys, then we should loop through all // the certificates in the collection and set our custom CERT_DELETE_KEYSET_PROP_ID property // so the key container will be deleted when the cert contexts will go away. // if (persistKeyContainers == false) { IntPtr pEnumContext = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, IntPtr.Zero); while (pEnumContext != IntPtr.Zero) { CAPI.CRYPTOAPI_BLOB blob = new CAPI.CRYPTOAPI_BLOB(); if (!CAPI.CertSetCertificateContextProperty(pEnumContext, CERT_DELETE_KEYSET_PROP_ID, CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG, // we don't want this property to be persisted. new IntPtr(&blob))) throw new CryptographicException(Marshal.GetLastWin32Error()); pEnumContext = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, pEnumContext); } } } return safeCertStoreHandle; }
[System.Security.SecuritySafeCritical] // auto-generated public byte [] Decrypt(byte[] rgb, bool fOAEP) { if (rgb == null) throw new ArgumentNullException("rgb"); Contract.EndContractBlock(); GetKeyPair(); // size check -- must be at most the modulus size if (rgb.Length > (KeySize / 8)) throw new CryptographicException(Environment.GetResourceString("Cryptography_Padding_DecDataTooBig", KeySize / 8)); if (!CspKeyContainerInfo.RandomlyGenerated) { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Decrypt); kp.AccessEntries.Add(entry); kp.Demand(); } } byte[] decryptedKey = null; DecryptKey(_safeKeyHandle, rgb, rgb.Length, fOAEP, JitHelpers.GetObjectHandleOnStack(ref decryptedKey)); return decryptedKey; }
[System.Security.SecuritySafeCritical] // auto-generated public override void ImportParameters(RSAParameters parameters) { // Free the current key handle if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed) { _safeKeyHandle.Dispose(); _safeKeyHandle = null; } RSACspObject rsaCspObject = RSAStructToObject(parameters); _safeKeyHandle = SafeKeyHandle.InvalidHandle; if (IsPublic(parameters)) { // Use our CRYPT_VERIFYCONTEXT handle, CRYPT_EXPORTABLE is not applicable to public only keys, so pass false Utils._ImportKey(Utils.StaticProvHandle, Constants.CALG_RSA_KEYX, (CspProviderFlags) 0, rsaCspObject, ref _safeKeyHandle); } else { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Import); kp.AccessEntries.Add(entry); kp.Demand(); } if (_safeProvHandle == null) _safeProvHandle = Utils.CreateProvHandle(_parameters, _randomKeyContainer); // Now, import the key into the CSP; _ImportKey will check for failures. Utils._ImportKey(_safeProvHandle, Constants.CALG_RSA_KEYX, _parameters.Flags, rsaCspObject, ref _safeKeyHandle); } }
[System.Security.SecurityCritical] // auto-generated internal static void ImportCspBlobHelper (CspAlgorithmType keyType, byte[] keyBlob, bool publicOnly, ref CspParameters parameters, bool randomKeyContainer, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) { // Free the current key handle if (safeKeyHandle != null && !safeKeyHandle.IsClosed) safeKeyHandle.Dispose(); safeKeyHandle = SafeKeyHandle.InvalidHandle; if (publicOnly) { parameters.KeyNumber = Utils._ImportCspBlob(keyBlob, keyType == CspAlgorithmType.Dss ? Utils.StaticDssProvHandle : Utils.StaticProvHandle, (CspProviderFlags) 0, ref safeKeyHandle); } else { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Import); kp.AccessEntries.Add(entry); kp.Demand(); } if (safeProvHandle == null) safeProvHandle = Utils.CreateProvHandle(parameters, randomKeyContainer); parameters.KeyNumber = Utils._ImportCspBlob(keyBlob, safeProvHandle, parameters.Flags, ref safeKeyHandle); } }
public static CngKey Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { Contract.Ensures(Contract.Result<CngKey>() != null); if (keyName == null) { throw new ArgumentNullException("keyName"); } 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)); } // Ensure the user has access to the key name KeyContainerPermissionAccessEntry access = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Open); access.ProviderName = provider.Provider; KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); permission.AccessEntries.Add(access); permission.Demand(); // Open the key SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider); SafeNCryptKeyHandle keyHandle = NCryptNative.OpenKey(kspHandle, keyName, openOptions); return new CngKey(kspHandle, keyHandle); }
public static CngKey Create(CngAlgorithm algorithm, string keyName, CngKeyCreationParameters creationParameters) { Contract.Ensures(Contract.Result<CngKey>() != null); if (algorithm == null) { throw new ArgumentNullException("algorithm"); } if (creationParameters == null) { creationParameters = new CngKeyCreationParameters(); } // Make sure that NCrypt is supported on this platform if (!NCryptNative.NCryptSupported) { throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported)); } // If we're not creating an ephemeral key, then we need to ensure the user has access to the key name if (keyName != null) { KeyContainerPermissionAccessEntry access = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Create); access.ProviderName = creationParameters.Provider.Provider; KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); permission.AccessEntries.Add(access); permission.Demand(); } // // Create the native handles representing the new key, setup the creation parameters on it, and // finalize it for use. // SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(creationParameters.Provider.Provider); SafeNCryptKeyHandle keyHandle = NCryptNative.CreatePersistedKey(kspHandle, algorithm.Algorithm, keyName, creationParameters.KeyCreationOptions); SetKeyProperties(keyHandle, creationParameters); NCryptNative.FinalizeKey(keyHandle); CngKey key = new CngKey(kspHandle, keyHandle); // No name translates to an ephemeral key if (keyName == null) { key.IsEphemeral = true; } return key; }
private byte[] SignHash(byte[] hash) { if (hash == null) { throw ExceptionUtility.ArgumentNull("hash"); } if (hash.Length != 32) { throw ExceptionUtility.ArgumentOutOfRange("hash", Resources.InvalidHashSize); } if (IsPublicKeyOnly) { throw ExceptionUtility.CryptographicException(Resources.NoPrivateKey); } GetKeyPair(); if (!CspKeyContainerInfo.RandomlyGenerated) { var keyContainerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); var keyContainerAccessEntry = new KeyContainerPermissionAccessEntry(_providerParameters, KeyContainerPermissionFlags.Sign); keyContainerPermission.AccessEntries.Add(keyContainerAccessEntry); keyContainerPermission.Demand(); } return CryptoApiHelper.SignValue(_providerHandle, _providerParameters.KeyNumber, hash); }
private static SafeProvHandleImpl CreateProviderHandle(CspParameters providerParams, bool randomKeyContainer) { SafeProvHandleImpl propvoderHandle = null; var keyContainerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); try { propvoderHandle = CryptoApiHelper.OpenProvider(providerParams); } catch (Exception exception) { var errorCode = Marshal.GetHRForException(exception); if (errorCode != 0) { if (((providerParams.Flags & CspProviderFlags.UseExistingKey) != CspProviderFlags.NoFlags) || ((errorCode != Constants.NTE_KEYSET_NOT_DEF) && (errorCode != Constants.NTE_BAD_KEYSET) && (errorCode != Constants.SCARD_W_CANCELLED_BY_USER))) { throw ExceptionUtility.CryptographicException(errorCode); } if (!randomKeyContainer) { var containerAccessEntry = new KeyContainerPermissionAccessEntry(providerParams, KeyContainerPermissionFlags.Create); keyContainerPermission.AccessEntries.Add(containerAccessEntry); keyContainerPermission.Demand(); } propvoderHandle = CryptoApiHelper.CreateProvider(providerParams); return propvoderHandle; } } if (!randomKeyContainer) { var containerAccessEntry = new KeyContainerPermissionAccessEntry(providerParams, KeyContainerPermissionFlags.Open); keyContainerPermission.AccessEntries.Add(containerAccessEntry); keyContainerPermission.Demand(); } return propvoderHandle; }
private unsafe void CounterSign (CmsSigner signer) { // Sanity check. Debug.Assert(signer != null); // CspParameters parameters = new CspParameters(); if (X509Utils.GetPrivateKeyInfo(X509Utils.GetCertContext(signer.Certificate), ref parameters) == false) throw new CryptographicException(Marshal.GetLastWin32Error()); KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Sign); kp.AccessEntries.Add(entry); kp.Demand(); // Get the signer's index. uint index = (uint) PkcsUtils.GetSignerIndex(m_signedCms.GetCryptMsgHandle(), this, 0); // Create CMSG_SIGNER_ENCODE_INFO structure. SafeLocalAllocHandle pSignerEncodeInfo = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)))); CAPI.CMSG_SIGNER_ENCODE_INFO signerEncodeInfo = PkcsUtils.CreateSignerEncodeInfo(signer); try { // Marshal to unmanaged memory. Marshal.StructureToPtr(signerEncodeInfo, pSignerEncodeInfo.DangerousGetHandle(), false); // Counter sign. if (!CAPI.CryptMsgCountersign(m_signedCms.GetCryptMsgHandle(), index, 1, pSignerEncodeInfo.DangerousGetHandle())) throw new CryptographicException(Marshal.GetLastWin32Error()); // CAPI requires that the messge be re-encoded if any unauthenticated // attribute has been added. So, let's re-open it to decode to work // around this limitation. m_signedCms.ReopenToDecode(); } finally { Marshal.DestroyStructure(pSignerEncodeInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)); pSignerEncodeInfo.Dispose(); // and don't forget to dispose of resources allocated for the structure. signerEncodeInfo.Dispose(); } // Finally, add certs to bag of certs. PkcsUtils.AddCertsToMessage(m_signedCms.GetCryptMsgHandle(), m_signedCms.Certificates, PkcsUtils.CreateBagOfCertificates(signer)); return; }
[System.Security.SecurityCritical] // auto-generated internal static byte[] ExportCspBlobHelper (bool includePrivateParameters, CspParameters parameters, SafeKeyHandle safeKeyHandle) { if (includePrivateParameters) { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Export); kp.AccessEntries.Add(entry); kp.Demand(); } } byte[] blob = null; Utils.ExportCspBlob(safeKeyHandle, includePrivateParameters ? Constants.PRIVATEKEYBLOB : Constants.PUBLICKEYBLOB, JitHelpers.GetObjectHandleOnStack(ref blob)); return blob; }
internal static void GetKeyPairHelper (CspAlgorithmType keyType, CspParameters parameters, bool randomKeyContainer, int dwKeySize, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) { SafeProvHandle TempFetchedProvHandle = Utils.CreateProvHandle(parameters, randomKeyContainer); #if FEATURE_MACL // If the user wanted to set the security descriptor on the provider context, apply it now. if (parameters.CryptoKeySecurity != null) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.ChangeAcl); kp.AccessEntries.Add(entry); kp.Demand(); SetKeySetSecurityInfo(TempFetchedProvHandle, parameters.CryptoKeySecurity, parameters.CryptoKeySecurity.ChangedAccessControlSections); } #endif //FEATURE_MACL #if FEATURE_X509_SECURESTRINGS // If the user wanted to specify a PIN or HWND for a smart card CSP, apply those settings now. if (parameters.ParentWindowHandle != IntPtr.Zero) SetProviderParameter(TempFetchedProvHandle, parameters.KeyNumber, Constants.CLR_PP_CLIENT_HWND, parameters.ParentWindowHandle); else if (parameters.KeyPassword != null) { IntPtr szPassword = Marshal.SecureStringToCoTaskMemAnsi(parameters.KeyPassword); try { SetProviderParameter(TempFetchedProvHandle, parameters.KeyNumber, Constants.CLR_PP_PIN, szPassword); } finally { if (szPassword != IntPtr.Zero) Marshal.ZeroFreeCoTaskMemAnsi(szPassword); } } #endif //FEATURE_X509_SECURESTRINGS safeProvHandle = TempFetchedProvHandle; // If the key already exists, use it, else generate a new one SafeKeyHandle TempFetchedKeyHandle = SafeKeyHandle.InvalidHandle; int hr = Utils._GetUserKey(safeProvHandle, parameters.KeyNumber, ref TempFetchedKeyHandle); if (hr != Constants.S_OK) { if ((parameters.Flags & CspProviderFlags.UseExistingKey) != 0 || hr != Constants.NTE_NO_KEY) throw new CryptographicException(hr); // _GenerateKey will check for failures and throw an exception Utils._GenerateKey(safeProvHandle, parameters.KeyNumber, parameters.Flags, dwKeySize, ref TempFetchedKeyHandle); } // check that this is indeed an RSA/DSS key. byte[] algid = (byte[]) Utils._GetKeyParameter(TempFetchedKeyHandle, Constants.CLR_ALGID); int dwAlgId = (algid[0] | (algid[1] << 8) | (algid[2] << 16) | (algid[3] << 24)); if ((keyType == CspAlgorithmType.Rsa && dwAlgId != Constants.CALG_RSA_KEYX && dwAlgId != Constants.CALG_RSA_SIGN) || (keyType == CspAlgorithmType.Dss && dwAlgId != Constants.CALG_DSS_SIGN)) { TempFetchedKeyHandle.Dispose(); throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_WrongKeySpec")); } safeKeyHandle = TempFetchedKeyHandle; }
public void ComputeSignature (CmsSigner signer, bool silent) { if (signer == null) throw new ArgumentNullException("signer"); if (ContentInfo.Content.Length == 0) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_Empty_Content")); if (SubjectIdentifierType.NoSignature == signer.SignerIdentifierType) { if (m_safeCryptMsgHandle != null && !m_safeCryptMsgHandle.IsInvalid) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_No_Signature_First_Signer")); // First signer. Sign(signer, silent); return; } if (signer.Certificate == null) { if (silent) throw new InvalidOperationException(SecurityResources.GetResourceString("Cryptography_Cms_RecipientCertificateNotFound")); else signer.Certificate = PkcsUtils.SelectSignerCertificate(); } if (!signer.Certificate.HasPrivateKey) throw new CryptographicException(CAPI.NTE_NO_KEY); // CspParameters parameters = new CspParameters(); if (X509Utils.GetPrivateKeyInfo(X509Utils.GetCertContext(signer.Certificate), ref parameters) == false) throw new CryptographicException(SafeGetLastWin32Error()); KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Sign); kp.AccessEntries.Add(entry); kp.Demand(); if (m_safeCryptMsgHandle == null || m_safeCryptMsgHandle.IsInvalid) { // First signer. Sign(signer, silent); } else { // Co-signing. CoSign(signer, silent); } }
[System.Security.SecuritySafeCritical] // auto-generated public override RSAParameters ExportParameters (bool includePrivateParameters) { GetKeyPair(); if (includePrivateParameters) { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Export); kp.AccessEntries.Add(entry); kp.Demand(); } } RSACspObject rsaCspObject = new RSACspObject(); int blobType = includePrivateParameters ? Constants.PRIVATEKEYBLOB : Constants.PUBLICKEYBLOB; // _ExportKey will check for failures and throw an exception Utils._ExportKey(_safeKeyHandle, blobType, rsaCspObject); return RSAObjectToStruct(rsaCspObject); }
internal static bool CryptAcquireContext([In, Out] ref System.Security.Cryptography.SafeCryptProvHandle hCryptProv, [In, MarshalAs(UnmanagedType.LPStr)] string pwszContainer, [In, MarshalAs(UnmanagedType.LPStr)] string pwszProvider, [In] uint dwProvType, [In] uint dwFlags) { CspParameters parameters = new CspParameters { ProviderName = pwszProvider, KeyContainerName = pwszContainer, ProviderType = (int) dwProvType, KeyNumber = -1, Flags = ((dwFlags & 0x20) == 0x20) ? CspProviderFlags.UseMachineKeyStore : CspProviderFlags.NoFlags }; KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open); permission.AccessEntries.Add(accessEntry); permission.Demand(); bool flag = CAPIUnsafe.CryptAcquireContext(ref hCryptProv, pwszContainer, pwszProvider, dwProvType, dwFlags); if (!flag && (Marshal.GetLastWin32Error() == -2146893802)) { flag = CAPIUnsafe.CryptAcquireContext(ref hCryptProv, pwszContainer, pwszProvider, dwProvType, dwFlags | 8); } return flag; }
internal byte[] SignHash(byte[] rgbHash, int calgHash) { Contract.Requires(rgbHash != null); GetKeyPair(); if (!CspKeyContainerInfo.RandomlyGenerated) { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Sign); kp.AccessEntries.Add(entry); kp.Demand(); } } return Utils.SignValue(_safeKeyHandle, _parameters.KeyNumber, Constants.CALG_RSA_SIGN, calgHash, rgbHash); }
private void CounterSign(CmsSigner signer) { CspParameters parameters = new CspParameters(); if (!X509Utils.GetPrivateKeyInfo(X509Utils.GetCertContext(signer.Certificate), ref parameters)) throw new CryptographicException(Marshal.GetLastWin32Error()); KeyContainerPermission containerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Sign); containerPermission.AccessEntries.Add(accessEntry); containerPermission.Demand(); uint dwIndex = (uint)PkcsUtils.GetSignerIndex(this.m_signedCms.GetCryptMsgHandle(), this, 0); SafeLocalAllocHandle localAllocHandle = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)))); CAPI.CMSG_SIGNER_ENCODE_INFO signerEncodeInfo = PkcsUtils.CreateSignerEncodeInfo(signer); try { Marshal.StructureToPtr((object)signerEncodeInfo, localAllocHandle.DangerousGetHandle(), false); if (!CAPI.CryptMsgCountersign(this.m_signedCms.GetCryptMsgHandle(), dwIndex, 1U, localAllocHandle.DangerousGetHandle())) throw new CryptographicException(Marshal.GetLastWin32Error()); this.m_signedCms.ReopenToDecode(); } finally { Marshal.DestroyStructure(localAllocHandle.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)); localAllocHandle.Dispose(); signerEncodeInfo.Dispose(); } int num = (int)PkcsUtils.AddCertsToMessage(this.m_signedCms.GetCryptMsgHandle(), this.m_signedCms.Certificates, PkcsUtils.CreateBagOfCertificates(signer)); }
bool CryptAcquireContext( [In,Out] ref SafeCryptProvHandle hCryptProv, [In] [MarshalAs(UnmanagedType.LPStr)] string pwszContainer, [In] [MarshalAs(UnmanagedType.LPStr)] string pwszProvider, [In] uint dwProvType, [In] uint dwFlags) { CspParameters parameters = new CspParameters(); parameters.ProviderName = pwszProvider; parameters.KeyContainerName = pwszContainer; parameters.ProviderType = (int) dwProvType; parameters.KeyNumber = -1; parameters.Flags = (CspProviderFlags) ((dwFlags & CAPI.CRYPT_MACHINE_KEYSET) == CAPI.CRYPT_MACHINE_KEYSET ? CspProviderFlags.UseMachineKeyStore : 0); #if !FEATURE_CORESYSTEM if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open); kp.AccessEntries.Add(entry); kp.Demand(); } #endif bool rc = CAPIMethods.CryptAcquireContext(ref hCryptProv, pwszContainer, pwszProvider, dwProvType, dwFlags); if (!rc && Marshal.GetLastWin32Error() == CAPI.NTE_BAD_KEYSET) { rc = CAPIMethods.CryptAcquireContext(ref hCryptProv, pwszContainer, pwszProvider, dwProvType, dwFlags | CAPI.CRYPT_NEWKEYSET); } return rc; }
public void ComputeSignature(CmsSigner signer, bool silent) { if (signer == null) throw new ArgumentNullException("signer"); if (this.ContentInfo.Content.Length == 0) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_Empty_Content")); if (SubjectIdentifierType.NoSignature == signer.SignerIdentifierType) { if (this.m_safeCryptMsgHandle != null && !this.m_safeCryptMsgHandle.IsInvalid) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_No_Signature_First_Signer")); this.Sign(signer, silent); } else { if (signer.Certificate == null) { if (silent) throw new InvalidOperationException(SecurityResources.GetResourceString("Cryptography_Cms_RecipientCertificateNotFound")); signer.Certificate = PkcsUtils.SelectSignerCertificate(); } if (!signer.Certificate.HasPrivateKey) throw new CryptographicException(-2146893811); CspParameters parameters = new CspParameters(); if (!X509Utils.GetPrivateKeyInfo(X509Utils.GetCertContext(signer.Certificate), ref parameters)) throw new CryptographicException(SignedCms.SafeGetLastWin32Error()); KeyContainerPermission containerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Sign); containerPermission.AccessEntries.Add(accessEntry); containerPermission.Demand(); if (this.m_safeCryptMsgHandle == null || this.m_safeCryptMsgHandle.IsInvalid) this.Sign(signer, silent); else this.CoSign(signer, silent); } }
bool PFXExportCertStore( [In] SafeCertStoreHandle hCertStore, [In,Out] IntPtr pPFX, [In] string szPassword, [In] uint dwFlags) { if (hCertStore == null) throw new ArgumentNullException("hCertStore"); if (hCertStore.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "hCertStore"); #if !FEATURE_CORESYSTEM // // Right now, we always demand KeyContainerPermission regardless of whether the PFX contains a private key or not. // We could avoid that by looping through the certs in the store and find out whether there are actually private keys. // if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Export); kp.Demand(); } #endif return CAPIMethods.PFXExportCertStore(hCertStore, pPFX, szPassword, dwFlags); }
[System.Security.SecuritySafeCritical] // auto-generated public override DSAParameters ExportParameters (bool includePrivateParameters) { GetKeyPair(); if (includePrivateParameters) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Export); kp.AccessEntries.Add(entry); kp.Demand(); } DSACspObject dsaCspObject = new DSACspObject(); int blobType = includePrivateParameters ? Constants.PRIVATEKEYBLOB : Constants.PUBLICKEYBLOB; // _ExportKey will check for failures and throw an exception Utils._ExportKey(_safeKeyHandle, blobType, dsaCspObject); return DSAObjectToStruct(dsaCspObject); }
[System.Security.SecurityCritical] // auto-generated private byte[] ExportHelper (X509ContentType contentType, object password) { switch(contentType) { case X509ContentType.Cert: break; #if FEATURE_CORECLR case (X509ContentType)0x02 /* X509ContentType.SerializedCert */: case (X509ContentType)0x03 /* X509ContentType.Pkcs12 */: throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType"), new NotSupportedException()); #else // FEATURE_CORECLR case X509ContentType.SerializedCert: break; #if !FEATURE_PAL case X509ContentType.Pkcs12: KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Export); kp.Demand(); break; #endif // !FEATURE_PAL #endif // FEATURE_CORECLR else default: throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType")); } #if !FEATURE_CORECLR IntPtr szPassword = IntPtr.Zero; byte[] encodedRawData = null; SafeCertStoreHandle safeCertStoreHandle = X509Utils.ExportCertToMemoryStore(this); RuntimeHelpers.PrepareConstrainedRegions(); try { szPassword = X509Utils.PasswordToHGlobalUni(password); encodedRawData = X509Utils._ExportCertificatesToBlob(safeCertStoreHandle, contentType, szPassword); } finally { if (szPassword != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(szPassword); safeCertStoreHandle.Dispose(); } if (encodedRawData == null) throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_ExportFailed")); return encodedRawData; #else // !FEATURE_CORECLR return RawData; #endif // !FEATURE_CORECLR }
[System.Security.SecuritySafeCritical] // auto-generated public byte[] SignHash(byte[] rgbHash, string str) { if (rgbHash == null) throw new ArgumentNullException("rgbHash"); Contract.EndContractBlock(); if (PublicOnly) throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_NoPrivateKey")); int calgHash = X509Utils.NameOrOidToAlgId(str, OidGroup.HashAlgorithm); if (rgbHash.Length != _sha1.HashSize / 8) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidHashSize", "SHA1", _sha1.HashSize / 8)); GetKeyPair(); if (!CspKeyContainerInfo.RandomlyGenerated) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Sign); kp.AccessEntries.Add(entry); kp.Demand(); } return Utils.SignValue(_safeKeyHandle, _parameters.KeyNumber, Constants.CALG_DSS_SIGN, calgHash, rgbHash); }
private void LoadCertificateFromFile (string fileName, object password, X509KeyStorageFlags keyStorageFlags) { if (fileName == null) throw new ArgumentNullException("fileName"); Contract.EndContractBlock(); string fullPath = Path.GetFullPathInternal(fileName); new FileIOPermission (FileIOPermissionAccess.Read, fullPath).Demand(); X509ContentType contentType = X509Utils.MapContentType(X509Utils._QueryCertFileType(fileName)); #if !FEATURE_CORECLR && !FEATURE_PAL if (contentType == X509ContentType.Pkcs12 && (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create); kp.Demand(); } #endif // !FEATURE_CORECLR && !FEATURE_PAL uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags); IntPtr szPassword = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { szPassword = X509Utils.PasswordToHGlobalUni(password); X509Utils._LoadCertFromFile(fileName, szPassword, dwFlags, #if FEATURE_CORECLR false, #else // FEATURE_CORECLR (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == 0 ? false : true, #endif // FEATURE_CORECLR else ref m_safeCertContext); } finally { if (szPassword != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(szPassword); } }
internal static SafeProvHandle CreateProvHandle (CspParameters parameters, bool randomKeyContainer) { SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle; int hr = Utils._OpenCSP(parameters, 0, ref safeProvHandle); KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); if (hr != Constants.S_OK) { // If UseExistingKey flag is used and the key container does not exist // throw an exception without attempting to create the container. if ((parameters.Flags & CspProviderFlags.UseExistingKey) != 0 || (hr != Constants.NTE_KEYSET_NOT_DEF && hr != Constants.NTE_BAD_KEYSET && hr != Constants.NTE_FILENOTFOUND)) throw new CryptographicException(hr); if (!randomKeyContainer) { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Create); kp.AccessEntries.Add(entry); kp.Demand(); } } Utils._CreateCSP(parameters, randomKeyContainer, ref safeProvHandle); } else { if (!randomKeyContainer) { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open); kp.AccessEntries.Add(entry); kp.Demand(); } } } return safeProvHandle; }