private static extern void EncryptKey(SafeKeyHandle pKeyContext,
                                       [MarshalAs(UnmanagedType.LPArray)] byte[] pbKey,
                                       int cbKey,
                                       [MarshalAs(UnmanagedType.Bool)] bool fOAEP,
                                       ObjectHandleOnStack ohRetEncryptedKey);
Ejemplo n.º 2
0
 [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;
 }
Ejemplo n.º 3
0
        [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);
            }
        }
Ejemplo n.º 4
0
 internal static extern int _GetUserKey(SafeProvHandle hProv, int keyNumber, ref SafeKeyHandle hKey);
Ejemplo n.º 5
0
 internal static extern int _ImportCspBlob(byte[] keyBlob, SafeProvHandle hProv, CspProviderFlags flags, ref SafeKeyHandle hKey);
Ejemplo n.º 6
0
 internal static extern int _EncryptData(SafeKeyHandle hKey, byte[] data, int ib, int cb, ref byte[] outputBuffer, int outputOffset, PaddingMode PaddingMode, bool fDone);
Ejemplo n.º 7
0
 internal static extern void _GenerateKey(SafeProvHandle hProv, int algid, CspProviderFlags flags, int keySize, ref SafeKeyHandle hKey);
Ejemplo n.º 8
0
 private void ImportKey(ReadOnlySpan <byte> key)
 {
     _keyHandle = Interop.BCrypt.BCryptImportKey(s_aesGcm, key);
 }
 public override void ImportParameters(RSAParameters parameters)
 {
     if ((this._safeKeyHandle != null) && !this._safeKeyHandle.IsClosed)
     {
         this._safeKeyHandle.Dispose();
         this._safeKeyHandle = null;
     }
     RSACspObject cspObject = RSAStructToObject(parameters);
     this._safeKeyHandle = SafeKeyHandle.InvalidHandle;
     if (IsPublic(parameters))
     {
         Utils._ImportKey(Utils.StaticProvHandle, 0xa400, CspProviderFlags.NoFlags, cspObject, ref this._safeKeyHandle);
     }
     else
     {
         KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
         KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(this._parameters, KeyContainerPermissionFlags.Import);
         permission.AccessEntries.Add(accessEntry);
         permission.Demand();
         if (this._safeProvHandle == null)
         {
             this._safeProvHandle = Utils.CreateProvHandle(this._parameters, this._randomKeyContainer);
         }
         Utils._ImportKey(this._safeProvHandle, 0xa400, this._parameters.Flags, cspObject, ref this._safeKeyHandle);
     }
 }
Ejemplo n.º 10
0
        internal GostCryptoAPITransform(
            int cArgs, int[] rgArgIds, object[] rgArgValues,
            SafeKeyHandle hKey,
            SafeProvHandle hProv,
            PaddingMode padding,
            CipherMode cipherChainingMode,
            int blockSize,
            bool encrypting)
        {
            _blockSizeValue = blockSize;
            _modeValue      = cipherChainingMode;
            _isStream       = _modeValue == CipherMode.OFB ||
                              _modeValue == CipherMode.CFB;
            _paddingValue    = padding;
            this._encrypting = encrypting;
            int[] numArray1 = new int[rgArgIds.Length];
            Array.Copy(rgArgIds, numArray1, rgArgIds.Length);
            object[] objArray1 = new object[rgArgValues.Length];
            for (int num2 = 0; num2 < rgArgValues.Length; num2++)
            {
                if (rgArgValues[num2] is byte[])
                {
                    byte[] buffer2 = (byte[])rgArgValues[num2];
                    byte[] buffer3 = new byte[buffer2.Length];
                    Array.Copy(buffer2, buffer3, buffer2.Length);
                    objArray1[num2] = buffer3;
                }
                else if (rgArgValues[num2] is int)
                {
                    objArray1[num2] = (int)rgArgValues[num2];
                }
                else if (rgArgValues[num2] is CipherMode)
                {
                    objArray1[num2] = (int)rgArgValues[num2];
                }
                else if (rgArgValues[num2] is PaddingMode)
                {
                    objArray1[num2] = (int)rgArgValues[num2];
                }
            }
            safeKeyHandle_  = hKey;
            _safeProvHandle = hProv;

            // Не добавляем ссылки на ключи и провайдеры
            // провайдер передан уже с addRef
            // ключ - получен через DuplicateKey

            for (int num3 = 0; num3 < cArgs; num3++)
            {
                switch (rgArgIds[num3])
                {
                case GostConstants.KP_SV:
                {
                    _ivValue = (byte[])objArray1[num3];
                    byte[] buffer1 = _ivValue;
                    CapiHelper.SetKeyParameter(safeKeyHandle_,
                                               numArray1[num3], buffer1);
                    break;
                }

                case GostConstants.KP_PADDING:
                {
                    CapiHelper.SetKeyParameter(safeKeyHandle_,
                                               numArray1[num3], BitConverter.GetBytes((int)objArray1[num3]));
                    break;
                }

                case GostConstants.KP_MODE:
                {
                    CapiHelper.SetKeyParameter(safeKeyHandle_,
                                               numArray1[num3], BitConverter.GetBytes((int)objArray1[num3]));
                    break;
                }

                default:
                {
                    throw new CryptographicException(SR.Argument_InvalidValue);
                }
                }
            }
        }
Ejemplo n.º 11
0
        [System.Security.SecurityCritical]  // auto-generated
        internal CryptoAPITransform(int algid, int cArgs, int[] rgArgIds,
                                    Object[] rgArgValues, byte[] rgbKey, PaddingMode padding,
                                    CipherMode cipherChainingMode, int blockSize,
                                    int feedbackSize, bool useSalt,
                                    CryptoAPITransformMode encDecMode)
        {
            int dwValue;

            byte[] rgbValue;

            BlockSizeValue   = blockSize;
            ModeValue        = cipherChainingMode;
            PaddingValue     = padding;
            encryptOrDecrypt = encDecMode;

            // Copy the input args
            int _cArgs = cArgs;

            int[] _rgArgIds = new int[rgArgIds.Length];
            Array.Copy(rgArgIds, _rgArgIds, rgArgIds.Length);
            _rgbKey = new byte[rgbKey.Length];
            Array.Copy(rgbKey, _rgbKey, rgbKey.Length);
            Object[] _rgArgValues = new Object[rgArgValues.Length];
            // an element of rgArgValues can only be an int or a byte[]
            for (int j = 0; j < rgArgValues.Length; j++)
            {
                if (rgArgValues[j] is byte[])
                {
                    byte[] rgbOrig = (byte[])rgArgValues[j];
                    byte[] rgbNew  = new byte[rgbOrig.Length];
                    Array.Copy(rgbOrig, rgbNew, rgbOrig.Length);
                    _rgArgValues[j] = rgbNew;
                    continue;
                }
                if (rgArgValues[j] is int)
                {
                    _rgArgValues[j] = (int)rgArgValues[j];
                    continue;
                }
                if (rgArgValues[j] is CipherMode)
                {
                    _rgArgValues[j] = (int)rgArgValues[j];
                    continue;
                }
            }

            _safeProvHandle = Utils.AcquireProvHandle(new CspParameters(Utils.DefaultRsaProviderType));

            SafeKeyHandle safeKeyHandle = SafeKeyHandle.InvalidHandle;

            // _ImportBulkKey will check for failures and throw an exception
            Utils._ImportBulkKey(_safeProvHandle, algid, useSalt, _rgbKey, ref safeKeyHandle);
            _safeKeyHandle = safeKeyHandle;

            for (int i = 0; i < cArgs; i++)
            {
                switch (rgArgIds[i])
                {
                case Constants.KP_IV:
                    IVValue  = (byte[])_rgArgValues[i];
                    rgbValue = IVValue;
                    Utils.SetKeyParamRgb(_safeKeyHandle, _rgArgIds[i], rgbValue, rgbValue.Length);
                    break;

                case Constants.KP_MODE:
                    ModeValue = (CipherMode)_rgArgValues[i];
                    dwValue   = (Int32)_rgArgValues[i];
SetAsDWord:
                    Utils.SetKeyParamDw(_safeKeyHandle, _rgArgIds[i], dwValue);
                    break;

                case Constants.KP_MODE_BITS:
                    dwValue = (Int32)_rgArgValues[i];
                    goto SetAsDWord;

                case Constants.KP_EFFECTIVE_KEYLEN:
                    dwValue = (Int32)_rgArgValues[i];
                    goto SetAsDWord;

                default:
                    throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeyParameter"), "_rgArgIds[i]");
                }
            }
        }
Ejemplo n.º 12
0
 private static extern void EncryptKey(SafeKeyHandle pKeyContext,
                                       [MarshalAs(UnmanagedType.LPArray)] byte[] pbKey,
                                       int cbKey,
                                       [MarshalAs(UnmanagedType.Bool)] bool fOAEP,
                                       ObjectHandleOnStack ohRetEncryptedKey);
Ejemplo n.º 13
0
        private static ICryptoTransform CreateTransformCore(
            SafeProvHandle hProv,
            SafeKeyHandle hKey,
            CipherMode mode,
            PaddingMode padding,
            byte[] rgbIV,
            int blockSize,
            int feedbackSize,
            bool encrypting)
        {
            //#Q_ ToDo выжечь огнём этот ад с двумя масивами для передачи параметров в GostCryptoAPITransform
            // переделать на словарь, или в идеале просто явно передавать параметры, но не этот ужас

            int num1 = 0;

            int[]    numArray1 = new int[10];
            object[] objArray1 = new object[10];

            // Не поддерживаем CTS. Выдаем приличное исключение.
            if (mode == CipherMode.CTS)
            {
                throw new ArgumentException(
                          SR.Argument_InvalidValue, nameof(mode)); //SR.Cryptography_CSP_CTSNotSupported
            }
            // Поддерживаем только правильные пары Padding - mode
            if (mode == CipherMode.OFB || mode == CipherMode.CFB)
            {
                if (padding != PaddingMode.None)
                {
                    throw new CryptographicException(
                              SR.Cryptography_InvalidPaddingMode);
                }
            }
            // Сбрасываем Pading, мы сами его поддерживаем.
            numArray1[num1] = GostConstants.KP_PADDING;
            objArray1[num1] = GostConstants.WINCRYPT_PADDING_ZERO;
            num1++;

            // Поддерживаем только CFB с feedback по ГОСТ.
            if ((mode == CipherMode.CFB) &&
                (feedbackSize != DefFeedbackSize))
            {
                throw new ArgumentException(SR.Argument_InvalidValue, nameof(feedbackSize));
            }
            // Нет ключа, генерим.
            if (hKey == null)
            {
                CapiHelper.GenerateKey(hProv,
                                       GostConstants.CALG_G28147,
                                       (int)CspProviderFlags.NoFlags, GostConstants.G28147_KEYLEN * BitsPerByte,
                                       out hKey);
            }
            // Ключ приходит как Handle, поэтому длины не проверяем.

            // Mode ставим всегда, так как при создании ключа по Handle
            // он может быть другим.
            numArray1[num1] = GostConstants.KP_MODE;
            objArray1[num1] = mode;
            num1++;

            // Для всех mode кроме ECB требуется синхропосылка. Устанавливаем.
            if (mode != CipherMode.ECB)
            {
                // Если ее нет, то генерим.
                if (rgbIV == null)
                {
                    if (!encrypting)
                    {
                        // при расшифровании IV должен быть задан
                        throw new CryptographicException(SR.Cryptography_MissingIV);
                    }
                    // Не используем GenerateIV: классовая и переданная
                    // IV могут отличаться.
                    rgbIV = new byte[IVSize / 8];
                    using (var rng = new GostRngCryptoServiceProvider(hProv))
                    {
                        rng.GetBytes(rgbIV);
                    }
                }
                // проверяем достаточность по длине.
                if (rgbIV.Length < IVSize / BitsPerByte)
                {
                    throw new CryptographicException(
                              SR.Cryptography_InvalidIVSize);
                }
                numArray1[num1] = GostConstants.KP_SV;
                objArray1[num1] = rgbIV;
                num1++;
            }

            // Можно еще установить для CFB количество бит зацепления, но
            // оно всегда равно 64 и его установка не поддерживается CSP.
            return(new GostCryptoAPITransform(num1, numArray1, objArray1, hKey, hProv,
                                              padding, mode, blockSize, encrypting));
        }
 internal static void ImportCspBlobHelper(CspAlgorithmType keyType, byte[] keyBlob, bool publicOnly, ref CspParameters parameters, bool randomKeyContainer, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle)
 {
     if ((safeKeyHandle != null) && !safeKeyHandle.IsClosed)
     {
         safeKeyHandle.Dispose();
     }
     safeKeyHandle = SafeKeyHandle.InvalidHandle;
     if (publicOnly)
     {
         parameters.KeyNumber = _ImportCspBlob(keyBlob, (keyType == CspAlgorithmType.Dss) ? StaticDssProvHandle : StaticProvHandle, CspProviderFlags.NoFlags, ref safeKeyHandle);
     }
     else
     {
         KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
         KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Import);
         permission.AccessEntries.Add(accessEntry);
         permission.Demand();
         if (safeProvHandle == null)
         {
             safeProvHandle = CreateProvHandle(parameters, randomKeyContainer);
         }
         parameters.KeyNumber = _ImportCspBlob(keyBlob, safeProvHandle, parameters.Flags, ref safeKeyHandle);
     }
 }
 internal static void GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, bool randomKeyContainer, int dwKeySize, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle)
 {
     SafeProvHandle hProv = CreateProvHandle(parameters, randomKeyContainer);
     if (parameters.CryptoKeySecurity != null)
     {
         KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
         KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.ChangeAcl);
         permission.AccessEntries.Add(accessEntry);
         permission.Demand();
         SetKeySetSecurityInfo(hProv, parameters.CryptoKeySecurity, parameters.CryptoKeySecurity.ChangedAccessControlSections);
     }
     if (parameters.ParentWindowHandle != IntPtr.Zero)
     {
         SetProviderParameter(hProv, parameters.KeyNumber, 10, parameters.ParentWindowHandle);
     }
     else if (parameters.KeyPassword != null)
     {
         IntPtr pbData = Marshal.SecureStringToCoTaskMemAnsi(parameters.KeyPassword);
         try
         {
             SetProviderParameter(hProv, parameters.KeyNumber, 11, pbData);
         }
         finally
         {
             if (pbData != IntPtr.Zero)
             {
                 Marshal.ZeroFreeCoTaskMemAnsi(pbData);
             }
         }
     }
     safeProvHandle = hProv;
     SafeKeyHandle invalidHandle = SafeKeyHandle.InvalidHandle;
     int hr = _GetUserKey(safeProvHandle, parameters.KeyNumber, ref invalidHandle);
     if (hr != 0)
     {
         if (((parameters.Flags & CspProviderFlags.UseExistingKey) != CspProviderFlags.NoFlags) || (hr != -2146893811))
         {
             throw new CryptographicException(hr);
         }
         _GenerateKey(safeProvHandle, parameters.KeyNumber, parameters.Flags, dwKeySize, ref invalidHandle);
     }
     byte[] buffer = _GetKeyParameter(invalidHandle, 9);
     int num2 = ((buffer[0] | (buffer[1] << 8)) | (buffer[2] << 0x10)) | (buffer[3] << 0x18);
     if ((((keyType == CspAlgorithmType.Rsa) && (num2 != 0xa400)) && (num2 != 0x2400)) || ((keyType == CspAlgorithmType.Dss) && (num2 != 0x2200)))
     {
         invalidHandle.Dispose();
         throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_WrongKeySpec"));
     }
     safeKeyHandle = invalidHandle;
 }
        internal CryptoAPITransform(int algid, int cArgs, int[] rgArgIds, object[] rgArgValues, byte[] rgbKey, PaddingMode padding, CipherMode cipherChainingMode, int blockSize, int feedbackSize, bool useSalt, CryptoAPITransformMode encDecMode)
        {
            this.BlockSizeValue = blockSize;
            this.ModeValue = cipherChainingMode;
            this.PaddingValue = padding;
            this.encryptOrDecrypt = encDecMode;
            int[] destinationArray = new int[rgArgIds.Length];
            Array.Copy(rgArgIds, destinationArray, rgArgIds.Length);
            this._rgbKey = new byte[rgbKey.Length];
            Array.Copy(rgbKey, this._rgbKey, rgbKey.Length);
            object[] objArray = new object[rgArgValues.Length];
            for (int i = 0; i < rgArgValues.Length; i++)
            {
                if (rgArgValues[i] is byte[])
                {
                    byte[] sourceArray = (byte[]) rgArgValues[i];
                    byte[] buffer3 = new byte[sourceArray.Length];
                    Array.Copy(sourceArray, buffer3, sourceArray.Length);
                    objArray[i] = buffer3;
                }
                else if (rgArgValues[i] is int)
                {
                    objArray[i] = (int) rgArgValues[i];
                }
                else if (rgArgValues[i] is CipherMode)
                {
                    objArray[i] = (int) rgArgValues[i];
                }
            }
            this._safeProvHandle = Utils.AcquireProvHandle(new CspParameters(Utils.DefaultRsaProviderType));
            SafeKeyHandle invalidHandle = SafeKeyHandle.InvalidHandle;
            Utils._ImportBulkKey(this._safeProvHandle, algid, useSalt, this._rgbKey, ref invalidHandle);
            this._safeKeyHandle = invalidHandle;
            for (int j = 0; j < cArgs; j++)
            {
                int num;
                switch (rgArgIds[j])
                {
                    case 1:
                    {
                        this.IVValue = (byte[]) objArray[j];
                        byte[] iVValue = this.IVValue;
                        Utils.SetKeyParamRgb(this._safeKeyHandle, destinationArray[j], iVValue, iVValue.Length);
                        continue;
                    }
                    case 4:
                        this.ModeValue = (CipherMode) objArray[j];
                        num = (int) objArray[j];
                        break;

                    case 5:
                        num = (int) objArray[j];
                        break;

                    case 0x13:
                        num = (int) objArray[j];
                        break;

                    default:
                        throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeyParameter"), "_rgArgIds[i]");
                }
                Utils.SetKeyParamDw(this._safeKeyHandle, destinationArray[j], num);
            }
        }
Ejemplo n.º 17
0
 [System.Security.SecurityCritical]  // auto-generated
 internal static bool VerifySign(SafeKeyHandle hKey, int calgKey, int calgHash, byte[] hash, byte[] signature)
 {
     return VerifySign(hKey, calgKey, calgHash, hash, hash.Length, signature, signature.Length);
 }
Ejemplo n.º 18
0
 private static int GetMinimumKeySize(SafeKeyHandle key)
 {
     var keyLengths = NCryptGetProperty<NCRYPT_SUPPORTED_LENGTHS>(key, KeyStoragePropertyIdentifiers.NCRYPT_LENGTHS_PROPERTY);
     return keyLengths.dwMinLength;
 }
Ejemplo n.º 19
0
 internal static extern void _ExportKey(SafeKeyHandle hKey, int blobType, object cspObject);
Ejemplo n.º 20
0
 private static extern void ExportCspBlob(SafeKeyHandle hKey, int blobType, ObjectHandleOnStack retBlob);
Ejemplo n.º 21
0
 internal static extern byte[] _GetKeyParameter(SafeKeyHandle hKey, uint paramID);
Ejemplo n.º 22
0
 internal static extern void SetKeyParamDw(SafeKeyHandle hKey, int param, int dwValue);
Ejemplo n.º 23
0
 internal static extern void _ImportBulkKey(SafeProvHandle hProv, int algid, bool useSalt, byte[] key, ref SafeKeyHandle hKey);
Ejemplo n.º 24
0
 internal static extern void SetKeyParamRgb(SafeKeyHandle hKey, int param, byte[] value, int cbValue);
Ejemplo n.º 25
0
 internal static extern void _ImportKey(SafeProvHandle hCSP, int keyNumber, CspProviderFlags flags, object cspObject, ref SafeKeyHandle hKey);
Ejemplo n.º 26
0
 private static extern void SignValue(SafeKeyHandle hKey, int keyNumber, int calgKey, int calgHash, byte[] hash, int cbHash, ObjectHandleOnStack retSignature);
Ejemplo n.º 27
0
        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;
        }
Ejemplo n.º 28
0
 [System.Security.SecurityCritical]  // auto-generated
 internal static byte[] SignValue(SafeKeyHandle hKey, int keyNumber, int calgKey, int calgHash, byte[] hash)
 {
     byte[] signature = null;
     SignValue(hKey, keyNumber, calgKey, calgHash, hash, hash.Length, JitHelpers.GetObjectHandleOnStack(ref signature));
     return signature;
 }
Ejemplo n.º 29
0
        [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);
            }
        }
Ejemplo n.º 30
0
 private static extern bool VerifySign(SafeKeyHandle hKey, int calgKey, int calgHash, byte[] hash, int cbHash, byte[] signature, int cbSignature);
Ejemplo n.º 31
0
        [System.Security.SecurityCritical]  // auto-generated 
        internal CryptoAPITransform(int algid, int cArgs, int[] rgArgIds,
                                    Object[] rgArgValues, byte[] rgbKey, PaddingMode padding, 
                                    CipherMode cipherChainingMode, int blockSize,
                                    int feedbackSize, bool useSalt,
                                    CryptoAPITransformMode encDecMode) {
            int dwValue; 
            byte[] rgbValue;
 
            BlockSizeValue = blockSize; 
            ModeValue = cipherChainingMode;
            PaddingValue = padding; 
            encryptOrDecrypt = encDecMode;

            // Copy the input args
            int _cArgs = cArgs; 
            int[] _rgArgIds = new int[rgArgIds.Length];
            Array.Copy(rgArgIds, _rgArgIds, rgArgIds.Length); 
            _rgbKey = new byte[rgbKey.Length]; 
            Array.Copy(rgbKey, _rgbKey, rgbKey.Length);
            Object[] _rgArgValues = new Object[rgArgValues.Length]; 
            // an element of rgArgValues can only be an int or a byte[]
            for (int j = 0; j < rgArgValues.Length; j++) {
                if (rgArgValues[j] is byte[]) {
                    byte[] rgbOrig = (byte[]) rgArgValues[j]; 
                    byte[] rgbNew = new byte[rgbOrig.Length];
                    Array.Copy(rgbOrig, rgbNew, rgbOrig.Length); 
                    _rgArgValues[j] = rgbNew; 
                    continue;
                } 
                if (rgArgValues[j] is int) {
                    _rgArgValues[j] = (int) rgArgValues[j];
                    continue;
                } 
                if (rgArgValues[j] is CipherMode) {
                    _rgArgValues[j] = (int) rgArgValues[j]; 
                    continue; 
                }
            } 

            _safeProvHandle = Utils.AcquireProvHandle(new CspParameters(Utils.DefaultRsaProviderType));

            SafeKeyHandle safeKeyHandle = SafeKeyHandle.InvalidHandle; 
            // _ImportBulkKey will check for failures and throw an exception
            Utils._ImportBulkKey(_safeProvHandle, algid, useSalt, _rgbKey, ref safeKeyHandle); 
            _safeKeyHandle = safeKeyHandle; 

            for (int i=0; i<cArgs; i++) { 
                switch (rgArgIds[i]) {
                case Constants.KP_IV:
                    IVValue = (byte[]) _rgArgValues[i];
                    rgbValue = IVValue; 
                    Utils.SetKeyParamRgb(_safeKeyHandle, _rgArgIds[i], rgbValue, rgbValue.Length);
                    break; 
 
                case Constants.KP_MODE:
                    ModeValue = (CipherMode) _rgArgValues[i]; 
                    dwValue = (Int32) _rgArgValues[i];
                SetAsDWord:
                    Utils.SetKeyParamDw(_safeKeyHandle, _rgArgIds[i], dwValue);
                    break; 

                case Constants.KP_MODE_BITS: 
                    dwValue = (Int32) _rgArgValues[i]; 
                    goto SetAsDWord;
 
                case Constants.KP_EFFECTIVE_KEYLEN:
                    dwValue = (Int32) _rgArgValues[i];
                    goto SetAsDWord;
 
                default:
                    throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeyParameter"), "_rgArgIds[i]"); 
                } 
            }
        } 
 internal static byte[] ExportCspBlobHelper(bool includePrivateParameters, CspParameters parameters, SafeKeyHandle safeKeyHandle)
 {
     if (includePrivateParameters)
     {
         KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
         KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Export);
         permission.AccessEntries.Add(accessEntry);
         permission.Demand();
     }
     byte[] o = null;
     ExportCspBlob(safeKeyHandle, includePrivateParameters ? 7 : 6, JitHelpers.GetObjectHandleOnStack<byte[]>(ref o));
     return o;
 }