public BasicSymmetricCipherCsp(int algId, CipherMode cipherMode, int blockSizeInBytes, byte[] key, bool addNoSaltFlag, byte[]?iv, bool encrypting, int feedbackSize, int paddingSizeInBytes) : base(cipherMode.GetCipherIv(iv), blockSizeInBytes, paddingSizeInBytes) { _encrypting = encrypting; _hProvider = AcquireSafeProviderHandle(); _hKey = ImportCspBlob(_hProvider, algId, key, addNoSaltFlag); SetKeyParameter(_hKey, CryptGetKeyParamQueryType.KP_MODE, (int)cipherMode); if (cipherMode == CipherMode.CFB) { SetKeyParameter(_hKey, CryptGetKeyParamQueryType.KP_MODE_BITS, feedbackSize); } byte[]? currentIv = cipherMode.GetCipherIv(iv); if (currentIv != null) { SetKeyParameter(_hKey, CryptGetKeyParamQueryType.KP_IV, currentIv); } if (algId == CapiHelper.CALG_RC2) { SetKeyParameter(_hKey, CryptGetKeyParamQueryType.KP_EFFECTIVE_KEYLEN, key.Length * 8); } }
public DSACryptoServiceProvider(int dwKeySize, CspParameters?parameters) { if (dwKeySize < 0) { throw new ArgumentOutOfRangeException(nameof(dwKeySize), SR.ArgumentOutOfRange_NeedNonNegNum); } _parameters = CapiHelper.SaveCspParameters( CapiHelper.CspAlgorithmType.Dss, parameters, s_useMachineKeyStore, out _randomKeyContainer); _keySize = dwKeySize; _sha1 = SHA1.Create(); // If this is not a random container we generate, create it eagerly // in the constructor so we can report any errors now. if (!_randomKeyContainer) { // Force-read the SafeKeyHandle property, which will summon it into existence. SafeCapiKeyHandle localHandle = SafeKeyHandle; Debug.Assert(localHandle != null); } }
internal static void SetKeyParameter(SafeCapiKeyHandle key, KeyParameter parameter, int value) { Contract.Requires(key != null); Contract.Requires(parameter == KeyParameter.Mode || parameter == KeyParameter.ModeBits); SetKeyParameter(key, parameter, BitConverter.GetBytes(value)); }
public override ICryptoTransform CreateEncryptor(byte[] key, byte[] iv) { if (key == null) { throw new ArgumentNullException("key"); } if (!base.ValidKeySize(key.Length * 8)) { throw new ArgumentException(System.SR.GetString("Cryptography_InvalidKeySize"), "key"); } if ((iv != null) && ((iv.Length * 8) != base.BlockSizeValue)) { throw new ArgumentException(System.SR.GetString("Cryptography_InvalidIVSize"), "iv"); } byte[] buffer = (byte[])key.Clone(); byte[] buffer2 = null; if (iv != null) { buffer2 = (byte[])iv.Clone(); } using (SafeCapiKeyHandle handle = CapiNative.ImportSymmetricKey(this.m_cspHandle, GetAlgorithmId(buffer.Length * 8), buffer)) { return(this.CreateEncryptor(handle, buffer2)); } }
public static extern bool CryptEncrypt(SafeCapiKeyHandle hKey, SafeCapiHashHandle hHash, [MarshalAs(UnmanagedType.Bool)] bool Final, int dwFlags, IntPtr pbData, // BYTE * [In, Out] ref int pdwDataLen, int dwBufLen);
private static SafeCapiKeyHandle SetupKey(SafeCapiKeyHandle key, byte[] iv, CipherMode cipherMode, int feedbackSize) { Contract.Requires(key != null); Contract.Requires(cipherMode == CipherMode.ECB || iv != null); Contract.Requires(0 <= feedbackSize); Contract.Ensures(Contract.Result <SafeCapiKeyHandle>() != null && !Contract.Result <SafeCapiKeyHandle>().IsInvalid&& !Contract.Result <SafeCapiKeyHandle>().IsClosed); // Make a copy of the key so that we don't modify the properties of the caller's copy SafeCapiKeyHandle encryptionKey = key.Duplicate(); // Setup the cipher mode first CapiNative.SetKeyParameter(encryptionKey, CapiNative.KeyParameter.Mode, (int)cipherMode); // If we're not in ECB mode then setup the IV if (cipherMode != CipherMode.ECB) { CapiNative.SetKeyParameter(encryptionKey, CapiNative.KeyParameter.IV, iv); } // OFB and CFB require a feedback loop size if (cipherMode == CipherMode.CFB || cipherMode == CipherMode.OFB) { CapiNative.SetKeyParameter(encryptionKey, CapiNative.KeyParameter.ModeBits, feedbackSize); } return(encryptionKey); }
internal static void SetKeyParameter(SafeCapiKeyHandle key, KeyParameter parameter, byte[] value) { if (!UnsafeNativeMethods.CryptSetKeyParam(key, parameter, value, 0)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } }
public override ICryptoTransform CreateEncryptor(byte[] key, byte[] iv) { Contract.Ensures(Contract.Result <ICryptoTransform>() != null); if (key == null) { throw new ArgumentNullException("key"); } if (!ValidKeySize(key.Length * 8)) { throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidKeySize), "key"); } if (iv != null && iv.Length * 8 != BlockSizeValue) { throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidIVSize), "iv"); } byte[] keyCopy = (byte[])key.Clone(); byte[] ivCopy = null; if (iv != null) { ivCopy = (byte[])iv.Clone(); } using (SafeCapiKeyHandle importedKey = CapiNative.ImportSymmetricKey(m_cspHandle, GetAlgorithmId(keyCopy.Length * 8), keyCopy)) { return(CreateEncryptor(importedKey, ivCopy)); } }
public override void GenerateKey() { Contract.Ensures(m_key != null && !m_key.IsInvalid & !m_key.IsClosed); Contract.Assert(m_cspHandle != null); SafeCapiKeyHandle key = null; RuntimeHelpers.PrepareConstrainedRegions(); try { if (!CapiNative.UnsafeNativeMethods.CryptGenKey(m_cspHandle, GetAlgorithmId(KeySizeValue), CapiNative.KeyFlags.Exportable, out key)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } finally { if (key != null && !key.IsInvalid) { key.SetParentCsp(m_cspHandle); } } if (m_key != null) { m_key.Dispose(); } m_key = key; }
internal static unsafe SafeCapiKeyHandle ImportSymmetricKey(SafeCspHandle provider, AlgorithmId algorithm, byte[] key) { int num = (Marshal.SizeOf(typeof(BLOBHEADER)) + Marshal.SizeOf(typeof(int))) + key.Length; byte[] dst = new byte[num]; fixed(byte *numRef = dst) { BLOBHEADER *blobheaderPtr = (BLOBHEADER *)numRef; blobheaderPtr->bType = KeyBlobType.PlainText; blobheaderPtr->bVersion = 2; blobheaderPtr->reserved = 0; blobheaderPtr->aiKeyAlg = algorithm; int *numPtr = (int *)(numRef + Marshal.SizeOf(blobheaderPtr[0])); numPtr[0] = key.Length; } Buffer.BlockCopy(key, 0, dst, Marshal.SizeOf(typeof(BLOBHEADER)) + Marshal.SizeOf(typeof(int)), key.Length); SafeCapiKeyHandle phKey = null; if (!UnsafeNativeMethods.CryptImportKey(provider, dst, dst.Length, SafeCapiKeyHandle.InvalidHandle, KeyFlags.Exportable, out phKey)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } return(phKey); }
internal static byte[] ExportSymmetricKey(SafeCapiKeyHandle key) { Contract.Requires(key != null); Contract.Ensures(Contract.Result <byte[]>() != null && Contract.Result <byte[]>().Length > 0); // // Figure out how big the key blob is, and export it // int keySize = 0; if (!UnsafeNativeMethods.CryptExportKey(key, SafeCapiKeyHandle.InvalidHandle, (int)KeyBlobType.PlainText, 0, null, ref keySize)) { int error = Marshal.GetLastWin32Error(); if (error != (int)ErrorCode.MoreData) { throw new CryptographicException(error); } } byte[] keyBlob = new byte[keySize]; if (!UnsafeNativeMethods.CryptExportKey(key, SafeCapiKeyHandle.InvalidHandle, (int)KeyBlobType.PlainText, 0, keyBlob, ref keySize)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } // // Strip the headers from the key to access the raw data // // A PLAINTEXTBLOB is laid out as follows: // BLOBHEADER hdr // DWORD cbKeySize // BYTE rbgKeyData[] // int keyDataOffset = Marshal.SizeOf(typeof(BLOBHEADER)) + Marshal.SizeOf(typeof(int)); Debug.Assert(keyBlob.Length > keyDataOffset, "Key blob is in an unexpected format."); int keyLength = BitConverter.ToInt32(keyBlob, Marshal.SizeOf(typeof(BLOBHEADER))); Debug.Assert(keyLength > 0, "Unexpected key length."); Debug.Assert(keyBlob.Length >= keyDataOffset + keyLength, "Key blob is in an unexpected format."); byte[] keyData = new byte[keyLength]; Buffer.BlockCopy(keyBlob, keyDataOffset, keyData, 0, keyData.Length); return(keyData); }
public CapiSymmetricAlgorithm(int blockSize, int feedbackSize, SafeCspHandle provider, SafeCapiKeyHandle key, byte[] iv, CipherMode cipherMode, PaddingMode paddingMode, EncryptionMode encryptionMode) { this.m_blockSize = blockSize; this.m_encryptionMode = encryptionMode; this.m_paddingMode = paddingMode; this.m_provider = provider.Duplicate(); this.m_key = SetupKey(key, ProcessIV(iv, blockSize, cipherMode), cipherMode, feedbackSize); }
internal static void SetKeyParameter(SafeCapiKeyHandle key, KeyParameter parameter, byte[] value) { Contract.Requires(key != null && !key.IsInvalid && !key.IsClosed); Contract.Requires(value != null); if (!UnsafeNativeMethods.CryptSetKeyParam(key, parameter, value, 0)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } }
public override void GenerateKey() { SafeCapiKeyHandle phKey = null; if (!CapiNative.UnsafeNativeMethods.CryptGenKey(this.m_cspHandle, GetAlgorithmId(base.KeySizeValue), CapiNative.KeyFlags.Exportable, out phKey)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } if (this.m_key != null) { this.m_key.Dispose(); } this.m_key = phKey; }
private ICryptoTransform CreateEncryptor(SafeCapiKeyHandle key, byte[] iv) { Contract.Requires(key != null); Contract.Ensures(Contract.Result <ICryptoTransform>() != null); return(new CapiSymmetricAlgorithm(BlockSizeValue, FeedbackSizeValue, m_cspHandle, key, iv, Mode, PaddingValue, EncryptionMode.Encrypt)); }
private static SafeCapiKeyHandle SetupKey(SafeCapiKeyHandle key, byte[] iv, CipherMode cipherMode, int feedbackSize) { SafeCapiKeyHandle handle = key.Duplicate(); CapiNative.SetKeyParameter(handle, CapiNative.KeyParameter.Mode, (int)cipherMode); if (cipherMode != CipherMode.ECB) { CapiNative.SetKeyParameter(handle, CapiNative.KeyParameter.IV, iv); } if ((cipherMode == CipherMode.CFB) || (cipherMode == CipherMode.OFB)) { CapiNative.SetKeyParameter(handle, CapiNative.KeyParameter.ModeBits, feedbackSize); } return(handle); }
public CapiSymmetricAlgorithm(int blockSize, int feedbackSize, SafeCspHandle provider, SafeCapiKeyHandle key, byte[] iv, CipherMode cipherMode, PaddingMode paddingMode, EncryptionMode encryptionMode) { Contract.Requires(0 < blockSize && blockSize % 8 == 0); Contract.Requires(0 <= feedbackSize); Contract.Requires(provider != null && !provider.IsInvalid && !provider.IsClosed); Contract.Requires(key != null && !key.IsInvalid && !key.IsClosed); Contract.Ensures(m_provider != null && !m_provider.IsInvalid && !m_provider.IsClosed); m_blockSize = blockSize; m_encryptionMode = encryptionMode; m_paddingMode = paddingMode; m_provider = provider.Duplicate(); m_key = SetupKey(key, ProcessIV(iv, blockSize, cipherMode), cipherMode, feedbackSize); }
protected override void Dispose(bool disposing) { if (disposing) { SafeCapiKeyHandle hKey = _hKey; if (hKey != null) { _hKey = null !; hKey.Dispose(); } SafeProvHandle hProvider = _hProvider; if (hProvider != null) { _hProvider = null !; hProvider.Dispose(); } } base.Dispose(disposing); }
internal static byte[] ExportSymmetricKey(SafeCapiKeyHandle key) { int pdwDataLen = 0; if (!UnsafeNativeMethods.CryptExportKey(key, SafeCapiKeyHandle.InvalidHandle, 8, 0, null, ref pdwDataLen)) { int hr = Marshal.GetLastWin32Error(); if (hr != 0xea) { throw new CryptographicException(hr); } } byte[] pbData = new byte[pdwDataLen]; if (!UnsafeNativeMethods.CryptExportKey(key, SafeCapiKeyHandle.InvalidHandle, 8, 0, pbData, ref pdwDataLen)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } int srcOffset = Marshal.SizeOf(typeof(BLOBHEADER)) + Marshal.SizeOf(typeof(int)); byte[] dst = new byte[BitConverter.ToInt32(pbData, Marshal.SizeOf(typeof(BLOBHEADER)))]; Buffer.BlockCopy(pbData, srcOffset, dst, 0, dst.Length); return(dst); }
private RSACryptoServiceProvider(int keySize, CspParameters?parameters, bool useDefaultKeySize) { if (keySize < 0) { throw new ArgumentOutOfRangeException("dwKeySize", "ArgumentOutOfRange_NeedNonNegNum"); } _parameters = CapiHelper.SaveCspParameters( CapiHelper.CspAlgorithmType.Rsa, parameters, s_useMachineKeyStore, out _randomKeyContainer); _keySize = useDefaultKeySize ? 1024 : keySize; // If this is not a random container we generate, create it eagerly // in the constructor so we can report any errors now. if (!_randomKeyContainer) { // Force-read the SafeKeyHandle property, which will summon it into existence. SafeCapiKeyHandle localHandle = SafeKeyHandle; Debug.Assert(localHandle != null); } }
public static extern bool CryptCreateHash(SafeCspHandle hProv, AlgorithmId Algid, SafeCapiKeyHandle hKey, int dwFlags, [Out] out SafeCapiHashHandle phHash);
public static extern bool CryptGenKey(SafeCspHandle hProv, CapiNative.AlgorithmId Algid, CapiNative.KeyFlags dwFlags, out SafeCapiKeyHandle phKey);
internal static void SetKeyParameter(SafeCapiKeyHandle key, KeyParameter parameter, int value) { SetKeyParameter(key, parameter, BitConverter.GetBytes(value)); }
public static extern bool CryptDuplicateKey(SafeCapiKeyHandle hKey, IntPtr pdwReserved, int dwFlags, [Out] out SafeCapiKeyHandle phKey);
private ICryptoTransform CreateDecryptor(SafeCapiKeyHandle key, byte[] iv) { return(new CapiSymmetricAlgorithm(base.BlockSizeValue, base.FeedbackSizeValue, this.m_cspHandle, key, iv, this.Mode, base.PaddingValue, EncryptionMode.Decrypt)); }
public static extern bool CryptExportKey(SafeCapiKeyHandle hKey, SafeCapiKeyHandle hExpKey, int dwBlobType, // (int)KeyBlobType int dwExportFlags, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbData, [In, Out] ref int pdwDataLen);
internal static SafeCapiKeyHandle ImportSymmetricKey(SafeCspHandle provider, AlgorithmId algorithm, byte[] key) { Contract.Requires(provider != null); Contract.Requires(((int)algorithm & (int)AlgorithmClass.DataEncryption) == (int)AlgorithmClass.DataEncryption); Contract.Requires(key != null); Contract.Ensures(Contract.Result <SafeCapiKeyHandle>() != null && !Contract.Result <SafeCapiKeyHandle>().IsInvalid&& !Contract.Result <SafeCapiKeyHandle>().IsClosed); // // Setup a PLAINTEXTKEYBLOB (v2) which has the following format: // BLOBHEADER hdr // DWORD cbKeySize // BYTE rbgKeyData[] // int blobSize = Marshal.SizeOf(typeof(BLOBHEADER)) + Marshal.SizeOf(typeof(int)) + key.Length; byte[] keyBlob = new byte[blobSize]; unsafe { fixed(byte *pBlob = keyBlob) { BLOBHEADER *pHeader = (BLOBHEADER *)pBlob; pHeader->bType = KeyBlobType.PlainText; pHeader->bVersion = 2; pHeader->reserved = 0; pHeader->aiKeyAlg = algorithm; int *pSize = (int *)(pBlob + Marshal.SizeOf(*pHeader)); *pSize = key.Length; } } Buffer.BlockCopy(key, 0, keyBlob, Marshal.SizeOf(typeof(BLOBHEADER)) + Marshal.SizeOf(typeof(int)), key.Length); // Import the PLAINTEXTKEYBLOB into the CSP SafeCapiKeyHandle importedKey = null; RuntimeHelpers.PrepareConstrainedRegions(); try { if (!UnsafeNativeMethods.CryptImportKey(provider, keyBlob, keyBlob.Length, SafeCapiKeyHandle.InvalidHandle, KeyFlags.Exportable, out importedKey)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } finally { if (importedKey != null && !importedKey.IsInvalid) { importedKey.SetParentCsp(provider); } } return(importedKey); }
public static extern bool CryptGenKey(SafeCspHandle hProv, AlgorithmId Algid, KeyFlags dwFlags, [Out] out SafeCapiKeyHandle phKey);
public static extern bool CryptSetKeyParam(SafeCapiKeyHandle hKey, KeyParameter dwParam, [MarshalAs(UnmanagedType.LPArray)] byte[] pbData, int dwFlags);
public static extern bool CryptImportKey(SafeCspHandle hProv, [MarshalAs(UnmanagedType.LPArray)] byte[] pbData, int dwDataLen, SafeCapiKeyHandle hPubKey, KeyFlags dwFlags, [Out] out SafeCapiKeyHandle phKey);