本文整理汇总了C#中SafeKeyHandle类的典型用法代码示例。如果您正苦于以下问题:C# SafeKeyHandle类的具体用法?C# SafeKeyHandle怎么用?C# SafeKeyHandle使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SafeKeyHandle类属于命名空间,在下文中一共展示了SafeKeyHandle类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: UncheckedTransformFinalBlock
protected sealed override byte[] UncheckedTransformFinalBlock(SafeKeyHandle hKey, byte[] currentIv, byte[] inputBuffer, int inputOffset, int inputCount)
{
byte[] paddedBlock = PadBlock(inputBuffer, inputOffset, inputCount);
byte[] output = new byte[paddedBlock.Length];
hKey.BCryptEncrypt(paddedBlock, 0, paddedBlock.Length, currentIv, output, 0, output.Length);
return output;
}
示例2: NCryptCreatePersistedKey
public static extern SECURITY_STATUS NCryptCreatePersistedKey(
SafeProviderHandle hProvider,
out SafeKeyHandle phKey,
string pszAlgId,
string pszKeyName = null,
LegacyKeySpec dwLegacyKeySpec = LegacyKeySpec.None,
NCryptCreatePersistedKeyFlags dwFlags = NCryptCreatePersistedKeyFlags.None);
示例3: UncheckedTransformBlock
protected sealed override int UncheckedTransformBlock(SafeKeyHandle hKey, byte[] currentIv, byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
//
// If we're decrypting, it's possible to be called with the last blocks of the data, and then
// have TransformFinalBlock called with an empty array. Since we don't know if this is the case,
// we won't decrypt the last block of the input until either TransformBlock or
// TransformFinalBlock is next called.
//
// We don't need to do this for PaddingMode.None because there is no padding to strip, and
// we also don't do this for PaddingMode.Zeros since there is no way for us to tell if the
// zeros at the end of a block are part of the plaintext or the padding.
//
int decryptedBytes = 0;
if (DepaddingRequired)
{
// If we have data saved from a previous call, decrypt that into the output first
if (_heldoverCipher != null)
{
int depadDecryptLength = DecryptInPlace(hKey, currentIv, _heldoverCipher, 0, _heldoverCipher.Length);
Buffer.BlockCopy(_heldoverCipher, 0, outputBuffer, outputOffset, depadDecryptLength);
Array.Clear(_heldoverCipher, 0, _heldoverCipher.Length);
outputOffset += depadDecryptLength;
decryptedBytes += depadDecryptLength;
}
else
{
_heldoverCipher = new byte[InputBlockSize];
}
// Copy the last block of the input buffer into the depad buffer
Debug.Assert(inputCount >= _heldoverCipher.Length, "inputCount >= _heldoverCipher.Length");
Buffer.BlockCopy(inputBuffer,
inputOffset + inputCount - _heldoverCipher.Length,
_heldoverCipher,
0,
_heldoverCipher.Length);
inputCount -= _heldoverCipher.Length;
Debug.Assert(inputCount % InputBlockSize == 0, "Did not remove whole blocks for depadding");
}
// If after reserving the depad buffer there's still data to decrypt, make a copy of that in the output buffer to work on.
if (inputCount > 0)
{
Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount);
decryptedBytes += DecryptInPlace(hKey, currentIv, outputBuffer, outputOffset, inputCount);
}
return decryptedBytes;
}
示例4: Dispose
protected override void Dispose(bool disposing)
{
if (disposing)
{
SafeKeyHandle hKey = _hKey;
_hKey = null;
if (hKey != null)
{
hKey.Dispose();
}
byte[] currentIv = _currentIv;
_currentIv = null;
if (currentIv != null)
{
Array.Clear(currentIv, 0, currentIv.Length);
}
}
base.Dispose(disposing);
}
示例5: Dispose
protected override void Dispose(bool disposing)
{
if (disposing)
{
SafeKeyHandle hKey = _hKey;
_hKey = null;
if (hKey != null)
{
hKey.Dispose();
}
SafeProvHandle hProvider = _hProvider;
_hProvider = null;
if (hProvider != null)
{
hProvider.Dispose();
}
}
base.Dispose(disposing);
}
示例6: BCryptExportKey
public static byte[] BCryptExportKey(SafeKeyHandle key, SafeKeyHandle exportKey, string blobType)
{
int lengthRequired;
exportKey = exportKey ?? SafeKeyHandle.NullHandle;
BCryptExportKey(
key,
exportKey,
blobType,
null,
0,
out lengthRequired,
0).ThrowOnError();
byte[] keyBuffer = new byte[lengthRequired];
BCryptExportKey(
key,
exportKey,
AsymmetricKeyBlobTypes.EccPublic,
keyBuffer,
keyBuffer.Length,
out lengthRequired,
0).ThrowOnError();
return keyBuffer;
}
示例7: ImportKeyBlob
/// <summary>
/// Helper for Import CSP
/// </summary>
internal static void ImportKeyBlob(SafeProvHandle saveProvHandle, CspProviderFlags flags, byte[] keyBlob, out SafeKeyHandle safeKeyHandle)
{
// Compat note: This isn't the same check as the one done by the CLR _ImportCspBlob QCall,
// but this does match the desktop CLR behavior and the only scenarios it
// affects are cases where a corrupt blob is passed in.
bool isPublic = keyBlob.Length > 0 && keyBlob[0] == CapiHelper.PUBLICKEYBLOB;
int dwCapiFlags = MapCspKeyFlags((int)flags);
if (isPublic)
{
dwCapiFlags &= ~(int)(CryptGenKeyFlags.CRYPT_EXPORTABLE);
}
SafeKeyHandle hKey;
if (!Interop.CryptImportKey(saveProvHandle, keyBlob, keyBlob.Length, SafeKeyHandle.InvalidHandle, dwCapiFlags, out hKey))
{
int hr = Marshal.GetHRForLastWin32Error();
hKey.Dispose();
throw hr.ToCryptographicException();
}
hKey.PublicOnly = isPublic;
safeKeyHandle = hKey;
return;
}
示例8: DecryptKey
//---------------------------------------------------------------------------------------
//
// Decrypt a symmetric key using the private key in pKeyContext
//
// Arguments:
// pKeyContext - private key used for decrypting pbEncryptedKey
// pbEncryptedKey - [in] encrypted symmetric key
// cbEncryptedKey - size, in bytes, of pbEncryptedKey
// fOAEP - TRUE to use OAEP padding, FALSE to use PKCS #1 type 2 padding
// ohRetDecryptedKey - [out] decrypted key
//
// Notes:
// pbEncryptedKey is byte-reversed from the format that CAPI expects. This is for compatibility with
// previous CLR versions and other RSA implementations.
//
// This method is the target of the System.Security.Cryptography.RSACryptoServiceProvider.DecryptKey QCall
//
// static
internal static void DecryptKey(SafeKeyHandle safeKeyHandle, byte[] encryptedData, int encryptedDataLength, bool fOAEP, out byte[] decryptedData)
{
VerifyValidHandle(safeKeyHandle);
if (null == encryptedData)
{
throw new CryptographicException(SR.Format(SR.Argument_InvalidValue, "Encrypted Data is null"));
}
if (encryptedDataLength < 0)
{
throw new CryptographicException(SR.Format(SR.Argument_InvalidValue, "Encrypted data length is less than 0"));
}
byte[] dataTobeDecrypted = new byte[encryptedDataLength];
Buffer.BlockCopy(encryptedData, 0, dataTobeDecrypted, 0, encryptedDataLength);
Array.Reverse(dataTobeDecrypted); //ToDO: Check is this is really needed? To be confirmed with tests
int dwFlags = fOAEP ? (int)CryptDecryptFlags.CRYPT_OAEP : 0;
int decryptedDataLength = encryptedDataLength;
if (!Interop.CryptDecrypt(safeKeyHandle, SafeHashHandle.InvalidHandle, true, dwFlags, dataTobeDecrypted, ref decryptedDataLength))
{
int ErrCode = GetErrorCode();
// If we're using OAEP mode and we received an NTE_BAD_FLAGS error, then OAEP is not supported on
// this platform (XP+ only). Throw a generic cryptographic exception if we failed to decrypt OAEP
// padded data in order to prevent a chosen ciphertext attack. We will allow NTE_BAD_KEY out, since
// that error does not relate to the padding. Otherwise just throw a cryptographic exception based on
// the error code.
if ((uint)((uint)dwFlags & (uint)CryptDecryptFlags.CRYPT_OAEP) == (uint)CryptDecryptFlags.CRYPT_OAEP &&
(uint)ErrCode != (uint)CryptKeyError.NTE_BAD_KEY)
{
if ((uint)ErrCode == (uint)CryptKeyError.NTE_BAD_FLAGS)
{
throw new CryptographicException("Cryptography_OAEP_XPPlus_Only");
}
else
{
throw new CryptographicException("Cryptography_OAEPDecoding");
}
}
else
{
throw new CryptographicException(SR.Format(SR.CryptDecrypt_Failed, Convert.ToString(ErrCode)));
}
}
decryptedData = new byte[decryptedDataLength];
Buffer.BlockCopy(dataTobeDecrypted, 0, decryptedData, 0, decryptedDataLength);
return;
}
示例9: EncryptKey
//---------------------------------------------------------------------------------------
//
// Encrypt a symmetric key using the public key in pKeyContext
//
// Arguments:
// safeKeyHandle [in] Key handle
// pbKey - [in] symmetric key to encrypt
// cbKey - size, in bytes, of pbKey
// fOAEP - TRUE to use OAEP padding, FALSE to use PKCS #1 type 2 padding
// ohRetEncryptedKey - [out] byte array holding the encrypted key
//
// Notes:
// The returned value in ohRetEncryptedKey is byte-reversed from the version CAPI gives us. This is for
// compatibility with previous releases of the CLR and other RSA implementations.
//
internal static void EncryptKey(SafeKeyHandle safeKeyHandle, byte[] pbKey, int cbKey, bool foep, ref byte[] pbEncryptedKey)
{
VerifyValidHandle(safeKeyHandle);
if (null == pbKey)
{
throw new CryptographicException(SR.Format(SR.Argument_InvalidValue, "pbKey is null"));
}
if (cbKey < 0)
{
throw new CryptographicException(SR.Format(SR.Argument_InvalidValue, "cbKey is less than 0"));
}
int dwEncryptFlags = foep ? (int)CryptDecryptFlags.CRYPT_OAEP : 0;
// Figure out how big the encrypted key will be
int cbEncryptedKey = cbKey;
if (!Interop.CryptEncrypt(safeKeyHandle, SafeHashHandle.InvalidHandle, true, dwEncryptFlags, null, ref cbEncryptedKey, cbEncryptedKey))
{
throw new CryptographicException(SR.Format(SR.CryptEncrypt_Failed, Convert.ToString(GetErrorCode())));
}
// pbData is an in/out buffer for CryptEncrypt. allocate space for the encrypted key, and copy the
// plaintext key into that space. Since encrypted keys will have padding applied, the size of the encrypted
// key should always be larger than the plaintext key, so use that to determine the buffer size.
Debug.Assert(cbEncryptedKey >= cbKey);
pbEncryptedKey = new byte[cbEncryptedKey];
Buffer.BlockCopy(pbKey, 0, pbEncryptedKey, 0, cbKey);
// Encrypt for real - the last parameter is the total size of the in/out buffer, while the second to last
// parameter specifies the size of the plaintext to encrypt.
if (!Interop.CryptEncrypt(safeKeyHandle, SafeHashHandle.InvalidHandle, true, dwEncryptFlags, pbEncryptedKey, ref cbKey, cbEncryptedKey))
{
}
Debug.Assert(cbKey == cbEncryptedKey);
Array.Reverse(pbEncryptedKey);
}
示例10: GenerateKey
/// <summary>
/// Generates the key if provided CSP handle is valid
/// </summary>
internal static int GenerateKey(SafeProvHandle safeProvHandle, int algID, int flags, uint keySize, out SafeKeyHandle safeKeyHandle)
{
int hr = S_OK;
VerifyValidHandle(safeProvHandle);
int capiFlags = (int)((uint)MapCspKeyFlags(flags) | ((uint)keySize << 16));
if (!Interop.CryptGenKey(safeProvHandle, algID, capiFlags, out safeKeyHandle))
{
hr = GetErrorCode();
}
if (hr != S_OK)
{
throw new CryptographicException(SR.Format(SR.CryptGenKey_Failed, Convert.ToString(GetErrorCode())));
}
safeKeyHandle.KeySpec = algID;
return hr;
}
示例11: GetKeyParameter
/// <summary>
///Method helps get the different key properties
/// </summary>
/// <param name="safeKeyHandle">Key handle</param>
/// <param name="dwKeyParam"> Key property you want to get</param>
/// <returns>Returns the key property</returns>
internal static byte[] GetKeyParameter(SafeKeyHandle safeKeyHandle, int keyParam)
{
byte[] pb = null;
int cb = 0;
VerifyValidHandle(safeKeyHandle); //This will throw if handle is invalid
switch (keyParam)
{
case Constants.CLR_KEYLEN:
{
//ToDO : Check if we should use silent flag here as this might not run
//downlevel so we might want to use silent flag
// Some Csp's may pop up a UI here since we don't use CRYPT_SILENT flag
// which is not supported in downlevel platforms
if (!Interop.CryptGetKeyParam(safeKeyHandle, (int)CryptGetKeyParamQueryType.KP_KEYLEN, null, ref cb, 0))
{
throw new CryptographicException(SR.Format(SR.CryptGetKeyParam_Failed, Convert.ToString(GetErrorCode())));
}
pb = new byte[cb];
if (!Interop.CryptGetKeyParam(safeKeyHandle, (int)CryptGetKeyParamQueryType.KP_KEYLEN, pb, ref cb, 0))
{
throw new CryptographicException(SR.Format(SR.CryptGetKeyParam_Failed, Convert.ToString(GetErrorCode())));
}
break;
}
case Constants.CLR_PUBLICKEYONLY:
{
pb = new byte[1];
pb[0] = safeKeyHandle.PublicOnly ? (byte)1 : (byte)0;
break;
}
case Constants.CLR_ALGID:
{
// returns the algorithm ID for the key
if (!Interop.CryptGetKeyParam(safeKeyHandle, (int)CryptGetKeyParamQueryType.KP_ALGID, null, ref cb, 0))
{
throw new CryptographicException(SR.Format(SR.CryptGetKeyParam_Failed, Convert.ToString(GetErrorCode())));
}
pb = new byte[cb];
if (!Interop.CryptGetKeyParam(safeKeyHandle, (int)CryptGetKeyParamQueryType.KP_ALGID, pb, ref cb, 0))
{
throw new CryptographicException(SR.Format(SR.CryptGetKeyParam_Failed, Convert.ToString(GetErrorCode())));
}
break;
}
default:
{
Debug.Assert(false);
break;
}
}
return pb;
}
示例12: CryptEncrypt
public static extern bool CryptEncrypt(SafeKeyHandle safeKeyHandle, SafeHashHandle safeHashHandle,
bool Final, int dwFlags, byte[] pbData, ref int pdwDataLen,
int dwBufLen);
示例13: GetUserKey
/// <summary>
/// Retrieves the handle for user public / private key pair.
/// </summary>
internal static int GetUserKey(SafeProvHandle safeProvHandle, int keySpec, out SafeKeyHandle safeKeyHandle)
{
int hr = S_OK;
VerifyValidHandle(safeProvHandle);
if (!Interop.CryptGetUserKey(safeProvHandle, keySpec, out safeKeyHandle))
{
hr = GetErrorCode();
}
if (hr == S_OK)
{
safeKeyHandle.KeySpec = keySpec;
}
return hr;
}
示例14: ExportKeyBlob
/// <summary>
/// Helper for Export CSP
/// </summary>
internal static byte[] ExportKeyBlob(bool includePrivateParameters, SafeKeyHandle safeKeyHandle)
{
VerifyValidHandle(safeKeyHandle);
byte[] pbRawData = null;
int cbRawData = 0;
int dwBlobType = includePrivateParameters ? PRIVATEKEYBLOB : PUBLICKEYBLOB;
if (!Interop.CryptExportKey(safeKeyHandle, SafeKeyHandle.InvalidHandle, dwBlobType, 0, null, ref cbRawData))
{
throw new CryptographicException(SR.Format(SR.CryptExportKey_Failed, Convert.ToString(GetErrorCode())));
}
pbRawData = new byte[cbRawData];
if (!Interop.CryptExportKey(safeKeyHandle, SafeKeyHandle.InvalidHandle, dwBlobType, 0, pbRawData, ref cbRawData))
{
throw new CryptographicException(SR.Format(SR.CryptExportKey_Failed, Convert.ToString(GetErrorCode())));
}
return pbRawData;
}
示例15: NCryptDecrypt
public static unsafe extern SECURITY_STATUS NCryptDecrypt(
SafeKeyHandle hKey,
byte* pbInput,
int cbInput,
void* pPaddingInfo,
byte* pbOutput,
int cbOutput,
out int pcbResult,
NCryptEncryptFlags dwFlags);