Esempio n. 1
0
        /// <summary>
        /// Encrypts a text and returns it as an array of bytes.
        /// </summary>
        /// <param name="text">Text to encrypt</param>
        /// <returns>Array of bytes containing the encrypted text</returns>
        public byte[] Encrypt(string text)
        {
            try
            {
                //Convert the text to an array of bytes
                byte[] bytes = _encoder.GetBytes(text);

                //Save the text in the encryptor's stream
                using (MemoryStream stream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(stream, _encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(bytes, 0, bytes.Length);
                        cryptoStream.FlushFinalBlock();

                        //Get the encrypted text as an array of bytes from the stream
                        stream.Position = 0;
                        byte[] encryptedBytes = new byte[stream.Length];
                        stream.Read(encryptedBytes, 0, encryptedBytes.Length);

                        //Free resources
                        cryptoStream.Close();

                        //Return the result
                        return(encryptedBytes);
                    }
                }
            }
            catch (Exception ex)
            {
                CryptographicException outerEx = new CryptographicException("The text {0} can't be encrypted", ex);
                outerEx.Data.Add(0, text);
                throw outerEx;
            }
        }
Esempio n. 2
0
        public static string Decrypt(byte[] key, string text)
        {
            string str;

            byte[] numArray = new byte[8];
            Array.Copy(key, 0, numArray, 0, 8);
            TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider()
            {
                BlockSize = 64,
                KeySize   = 192,
                Mode      = CipherMode.CBC,
                Padding   = PaddingMode.PKCS7,
                Key       = key,
                IV        = numArray
            };

            byte[] numArray1 = Convert.FromBase64String(text);
            try
            {
                ICryptoTransform cryptoTransform = tripleDESCryptoServiceProvider.CreateDecryptor();
                byte[]           numArray2       = cryptoTransform.TransformFinalBlock(numArray1, 0, (int)numArray1.Length);
                return(Encoding.Unicode.GetString(numArray2));
            }
            catch (CryptographicException cryptographicException1)
            {
                CryptographicException cryptographicException = cryptographicException1;
                //Errorlog
                str = AES.DecryptOld(AES.KEY_OLD, text);
            }
            return(str);
        }
Esempio n. 3
0
        /// <summary>
        /// Decrypts a byte array and returns it as text.
        /// </summary>
        /// <param name="encryptedArray">Array of bytes to decrypt</param>
        /// <returns>Text containing the array of bytes decrypted</returns>
        public string Decrypt(byte[] encryptedArray)
        {
            try
            {
                //Save the encrypted array of bytes into the stream of the decryptor
                using (MemoryStream stream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(stream, _decryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(encryptedArray, 0, encryptedArray.Length);
                        cryptoStream.FlushFinalBlock();

                        //Get the decrypted text as an array of bytes from the stream
                        stream.Position = 0;
                        byte[] decryptedBytes = new byte[stream.Length];
                        stream.Read(decryptedBytes, 0, decryptedBytes.Length);
                        stream.Close();

                        //Convert the decrypted array of bytes to string and return it
                        return(_encoder.GetString(decryptedBytes));
                    }
                }
            }
            catch (Exception ex)
            {
                CryptographicException outerEx = new CryptographicException("The text {0} can't be decrypted", ex);
                outerEx.Data.Add(0, encryptedArray);
                throw outerEx;
            }
        }
        public static void LoadMultipleExtensionRequestsInOneAttribute()
        {
            // This is TestData.BigExponentPkcs10Bytes, except
            // * A challenge password was added before the extensions requests
            // * The extensions requests attribute value was cloned within the one attribute node
            // * The signature was changed to just 1 bit, to cut down on space.
            const string Pkcs10Pem = @"
-----BEGIN CERTIFICATE REQUEST-----
MIICVjCCAj8CAQAwgYoxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9u
MRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRp
b24xIDAeBgNVBAsTFy5ORVQgRnJhbWV3b3JrIChDb3JlRlgpMRIwEAYDVQQDEwls
b2NhbGhvc3QwggEkMA0GCSqGSIb3DQEBAQUAA4IBEQAwggEMAoIBAQCvgcHL2CA/
YkpTntZggXU3I5Oig31IkOSKGd7TaXMRViCWjWvg09qjiqd3vgLuC2uTtyTo3MEr
YytPqAu8klvOYk9Mp8xgYwazlAPijJMtJN1Ub/5O9qN/EHcLIhXqjLtb9CfoxNib
eeszg3UQDF+D5V3ptEZt377uQlOa7zPvGHt3YMOxobIQPC2BRFZKDBA5oJyFz2tZ
dOtRb8jWYjyUrjpaC7O0x5KVfUMjkVZs8+KlKvsMFCueBoG4lyZxryuC3TkKObk5
z3GVaGh+SZCmMFDKd2jc1rN4hC8Y/bH22f8Ja69765jc+TDWb8/VA/WNQb/0YhLi
Tjr8RepCvYhHAgUCAAAEQaCBhDATBgkqhkiG9w0BCQcxBgwEMTIzNDBtBgkqhkiG
9w0BCQ4xYDAuMCwGA1UdEQQlMCOHBH8AAAGHEAAAAAAAAAAAAAAAAAAAAAGCCWxv
Y2FsaG9zdDAuMCwGA1UdEQQlMCOHBH8AAAGHEAAAAAAAAAAAAAAAAAAAAAGCCWxv
Y2FsaG9zdDANBgkqhkiG9w0BAQsFAAMCB4A=
-----END CERTIFICATE REQUEST-----";

            CryptographicException ex = Assert.Throws <CryptographicException>(
                () => CertificateRequest.LoadSigningRequestPem(
                    Pkcs10Pem,
                    HashAlgorithmName.SHA256,
                    CertificateRequestLoadOptions.SkipSignatureValidation));

            Assert.Contains("Extension Request", ex.Message);
        }
Esempio n. 5
0
    public static bool EncryptString(string Content)
    {
        byte[] cipherBytes;

        try
        {
            cipherBytes = _Encrypt(Content);
        }
        catch (CryptographicException ex)
        {
            _exception = new CryptographicException(ex.Message, ex.InnerException);
            return(false);
        }

        if (_encodingType == EncodingType.HEX)
        {
            _content = BytesToHex(cipherBytes);
        }
        else
        {
            _content = System.Convert.ToBase64String(cipherBytes);
        }

        return(true);
    }
        public string SignMd5Hash(byte[] hashedBytes)
        {
            byte[] signedHash = null;
            try
            {
                signedHash = _privateKey.SignHash(hashedBytes, CryptoConfig.MapNameToOID("MD5"));
            }
            catch (CryptographicException ex)
            {
                if (ex.Message == "Bad Hash.")
                {
                    var cryptoEx = new CryptographicException("Bad Hash; Use BasicHasher.GetMd5HashBytes() to generate a proper hash before calling this method.");
                }
                else
                {
                    throw;
                }
            }

            if (_encoding == EncodingOption.Base64String)
            {
                return(Convert.ToBase64String(signedHash));
            }
            else if (_encoding == EncodingOption.HexString)
            {
                return(signedHash.ToHexString());
            }
            else
            {
                throw new NotImplementedException(_encoding.ToString());
            }
            //return signedHash.ToHexString();
        }
Esempio n. 7
0
        public static void InvalidCertificateBlob()
        {
            CryptographicException ex = Assert.ThrowsAny <CryptographicException>(
                () => new X509Certificate2(new byte[] { 0x01, 0x02, 0x03 }));

            CryptographicException defaultException = new CryptographicException();

            Assert.NotEqual(defaultException.Message, ex.Message);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Assert.Equal(unchecked ((int)0x80092009), ex.HResult);
                // TODO (3233): Test that Message is also set correctly
                //Assert.Equal("Cannot find the requested object.", ex.Message);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                Assert.Equal(-25257, ex.HResult);
            }
            else // Any Unix
            {
                Assert.Equal(0x0D07803A, ex.HResult);
                Assert.Equal("error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error", ex.Message);
            }
        }
        public void SymmetricSignatureProviderTests_Constructor()
        {
            // no errors
            SymmetricSignatureProviderTests_Constructor("Creates with no errors", KeyingMaterial.SymmetricSecurityKey_256, SecurityAlgorithms.HmacSha256Signature);

            // null, empty algorithm digest
            SymmetricSignatureProviderTests_Constructor("Constructor:   - NUll key", null, SecurityAlgorithms.HmacSha256Signature, ExpectedException.ArgNull);
            SymmetricSignatureProviderTests_Constructor("Constructor:   - algorithm == string.Empty", KeyingMaterial.SymmetricSecurityKey_256, string.Empty, ExpectedException.ArgEx());

            // GetKeyedHashAlgorithm throws
            Exception            innerException = new CryptographicException("hi from inner");
            SymmetricSecurityKey key            = new FaultingSymmetricSecurityKey(KeyingMaterial.SymmetricSecurityKey_256, innerException);

            SymmetricSignatureProviderTests_Constructor("Constructor:   - SecurityKey.GetKeyedHashAlgorithm throws", key, SecurityAlgorithms.HmacSha256Signature, ExpectedException.InvalidOp("Jwt10532", innerException));

            // Key returns null KeyedHash
            key = new FaultingSymmetricSecurityKey(KeyingMaterial.SymmetricSecurityKey_256, null);
            SymmetricSignatureProviderTests_Constructor("Constructor:   - SecurityKey returns null KeyedHashAlgorithm", key, SecurityAlgorithms.HmacSha256Signature, ExpectedException.InvalidOp("Jwt10533"));

            //_keyedHash.Key = _key.GetSymmetricKey() is null;
            KeyedHashAlgorithm keyedHashAlgorithm = KeyingMaterial.SymmetricSecurityKey_256.GetKeyedHashAlgorithm(SecurityAlgorithms.HmacSha256Signature);

            key = new FaultingSymmetricSecurityKey(KeyingMaterial.SymmetricSecurityKey_256, null, null, keyedHashAlgorithm, null);
            SymmetricSignatureProviderTests_Constructor("Constructor:   - key returns null bytes to pass to _keyedHashKey", key, SecurityAlgorithms.HmacSha256Signature, ExpectedException.InvalidOp("Jwt10534", new NullReferenceException()));
        }
Esempio n. 9
0
        protected override void ReadWrongPassword(byte[] pfxBytes, string wrongPassword)
        {
            CryptographicException ex = Assert.ThrowsAny <CryptographicException>(
                () => new X509Certificate2(pfxBytes, wrongPassword, s_importFlags));

            AssertMessageContains("password", ex);
        }
        public void ReadWriteNistP256_PreservesKeyUsage_Explicit_LimitedPrivate()
        {
            if (!SupportsExplicitCurves)
            {
                return;
            }

            // This key has a keyUsage set to 0b00000000 (no key usages are valid).
            // Since the CNG PKCS8 import will re-write these keys with Q=(0,0)
            // in the PrivateKeyInfo, we want to make sure that the Attributes
            // are kept.
            const string base64 = @"
MIIBQgIBADCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0BAQIhAP////8AAAAB
AAAAAAAAAAAAAAAA////////////////MFsEIP////8AAAABAAAAAAAAAAAAAAAA
///////////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMV
AMSdNgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg
9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8A
AAAA//////////+85vqtpxeehPO5ysL8YyVRAgEBBCcwJQIBAQQgcKEsLbFoRe1W
/2jPwhpHKz8E19aFG/Y0ny19WzRSs4qgDTALBgNVHQ8xBAMCAAA=";

            T key = CreateKey();

            key.ImportPkcs8PrivateKey(Convert.FromBase64String(base64), out _);
            CryptographicException ex = Assert.ThrowsAny <CryptographicException>(() => Exercise(key));

            Assert.Equal(NTE_PERM, ex.HResult);
        }
            private byte[] AsymmetricDecrypt(byte[] encryptedKey)
            {
                byte[] array = null;
                CryptographicException ex = null;

                foreach (RSACryptoServiceProvider rsacryptoServiceProvider in this.GetCryptoServiceProviders())
                {
                    try
                    {
                        array = rsacryptoServiceProvider.Decrypt(encryptedKey, false);
                        break;
                    }
                    catch (CryptographicException ex2)
                    {
                        if (ex == null)
                        {
                            ex = ex2;
                        }
                        array = null;
                    }
                }
                if (array == null)
                {
                    throw ex;
                }
                return(array);
            }
Esempio n. 12
0
                public static CryptographicException /*!*/ Create(RubyClass /*!*/ self, [DefaultProtocol, DefaultParameterValue(null)] MutableString message)
                {
                    CryptographicException result = new CryptographicException(RubyExceptions.MakeMessage(ref message, "Not enought data."));

                    RubyExceptionData.InitializeException(result, message);
                    return(result);
                }
        public static RSACryptoServiceProvider GetRSACryptoServiceProviderFromPublicKey(X509Certificate2 x509Certificate2)
        {
            if (x509Certificate2 == null)
            {
                throw new ArgumentException("x509Certificate2");
            }
            if (x509Certificate2.PublicKey == null)
            {
                throw new ArgumentException("x509Certificate2.PublicKey.Key must be populated.");
            }

            try
            {
                var rsa = x509Certificate2.PublicKey.Key as RSACryptoServiceProvider;
                if (rsa != null)
                {
                    return(rsa);
                }
            }
            catch (Exception ex)
            {
                var outerEx = new CryptographicException(string.Format("X509Certificate2 with thumbprint '{0}' indicates that HasPrivateKey is TRUE, but the service or account may not have access to the private key or the private key may be missing or corrupted.", x509Certificate2.Thumbprint.ToLower()), ex);
                throw outerEx;
            }
            throw new CryptographicException(string.Format("X509Certificate2 with thumbprint '{0}' does not have a valid RSA public key.", x509Certificate2.Thumbprint.ToLower()));
        }
Esempio n. 14
0
        public static void InvalidCertificateBlob()
        {
            CryptographicException ex = Assert.ThrowsAny <CryptographicException>(
                () => new X509Certificate2(new byte[] { 0x01, 0x02, 0x03 }));

            CryptographicException defaultException = new CryptographicException();

            Assert.NotEqual(defaultException.Message, ex.Message);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Assert.Equal(unchecked ((int)0x80092009), ex.HResult);
                // TODO (3233): Test that Message is also set correctly
                //Assert.Equal("Cannot find the requested object.", ex.Message);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                Assert.Equal(-25257, ex.HResult);
            }
            else // Any Unix
            {
                // OpenSSL encodes the function name into the error code. However, the function name differs
                // between versions (OpenSSL 1.0, OpenSSL 1.1 and BoringSSL) and it's subject to change in
                // the future, so don't test for the exact match and mask out the function code away. The
                // component number (high 8 bits) and error code  (low 12 bits) should remain the same.
                Assert.Equal(0x0D00003A, ex.HResult & 0xFF000FFF);
            }
        }
Esempio n. 15
0
        protected override void ReadEmptyPfx(byte[] pfxBytes, string correctPassword)
        {
            CryptographicException ex = Assert.Throws <CryptographicException>(
                () => new X509Certificate2(pfxBytes, correctPassword, s_importFlags));

            AssertMessageContains("no certificates", ex);
        }
Esempio n. 16
0
            internal byte[] DecryptCek(X509Certificate2 cert, RSA privateKey, out Exception exception)
            {
                ReadOnlyMemory <byte>?parameters = _asn.KeyEncryptionAlgorithm.Parameters;
                string keyEncryptionAlgorithm    = _asn.KeyEncryptionAlgorithm.Algorithm.Value;

                switch (keyEncryptionAlgorithm)
                {
                case Oids.Rsa:
                    if (parameters != null &&
                        !parameters.Value.Span.SequenceEqual(s_rsaPkcsParameters))
                    {
                        exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
                        return(null);
                    }
                    break;

                case Oids.RsaOaep:
                    if (parameters != null &&
                        !parameters.Value.Span.SequenceEqual(s_rsaOaepSha1Parameters))
                    {
                        exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
                        return(null);
                    }
                    break;

                default:
                    exception = new CryptographicException(
                        SR.Cryptography_Cms_UnknownAlgorithm,
                        _asn.KeyEncryptionAlgorithm.Algorithm.Value);

                    return(null);
                }

                return(DecryptCekCore(cert, privateKey, _asn.EncryptedKey.Span, keyEncryptionAlgorithm, out exception));
            }
Esempio n. 17
0
            public override unsafe ContentInfo?TryDecrypt(
                RecipientInfo recipientInfo,
                X509Certificate2?cert,
                AsymmetricAlgorithm?privateKey,
                X509Certificate2Collection originatorCerts,
                X509Certificate2Collection extraStore,
                out Exception?exception)
            {
                // When encryptedContent is null Windows seems to decrypt the CEK first,
                // then return a 0 byte answer.

                Debug.Assert((cert != null) ^ (privateKey != null));

                if (recipientInfo.Pal is ManagedKeyTransPal ktri)
                {
                    RSA?key = privateKey as RSA;

                    if (privateKey != null && key == null)
                    {
                        exception = new CryptographicException(SR.Cryptography_Cms_Ktri_RSARequired);
                        return(null);
                    }

                    byte[]? cek = ktri.DecryptCek(cert, key, out exception);
                    // Pin CEK to prevent it from getting copied during heap compaction.
                    fixed(byte *pinnedCek = cek)
                    {
                        try
                        {
                            if (exception != null)
                            {
                                return(null);
                            }

                            return(TryDecryptCore(
                                       cek !,
                                       _envelopedData.EncryptedContentInfo.ContentType,
                                       _envelopedData.EncryptedContentInfo.EncryptedContent,
                                       _envelopedData.EncryptedContentInfo.ContentEncryptionAlgorithm,
                                       out exception));
                        }
                        finally
                        {
                            if (cek != null)
                            {
                                Array.Clear(cek, 0, cek.Length);
                            }
                        }
                    }
                }
                else
                {
                    exception = new CryptographicException(
                        SR.Cryptography_Cms_RecipientType_NotSupported,
                        recipientInfo.Type.ToString());

                    return(null);
                }
            }
Esempio n. 18
0
 public static void Clear()
 {
     _algorithm    = Algorithm.SHA1;
     _content      = string.Empty;
     _key          = string.Empty;
     _encodingType = EncodingType.HEX;
     _exception    = null;
 }
        private static void CheckBadKeyset(X509Certificate2 cert)
        {
            CryptographicException ex = Assert.ThrowsAny <CryptographicException>(
                () => cert.GetRSAPrivateKey());

            // NTE_BAD_KEYSET
            Assert.Equal(-2146893802, ex.HResult);
        }
    private void EmptyConstructor()
    {
        // Construct a CryptographicException with no parameters.
        CryptographicException cryptographicException =
            new CryptographicException();

        Console.WriteLine("Created an empty CryptographicException.");
    }
Esempio n. 21
0
        private static byte[] DecryptKey(
            RSA privateKey,
            RSAEncryptionPadding encryptionPadding,
            ReadOnlySpan <byte> encryptedKey,
            out Exception exception)
        {
            if (privateKey == null)
            {
                exception = new CryptographicException(SR.Cryptography_Cms_Signing_RequiresPrivateKey);
                return(null);
            }

#if netcoreapp
            byte[] cek       = null;
            int    cekLength = 0;

            try
            {
                cek = ArrayPool <byte> .Shared.Rent(privateKey.KeySize / 8);

                if (!privateKey.TryDecrypt(encryptedKey, cek, encryptionPadding, out cekLength))
                {
                    Debug.Fail("TryDecrypt wanted more space than the key size");
                    exception = new CryptographicException();
                    return(null);
                }

                exception = null;
                return(new Span <byte>(cek, 0, cekLength).ToArray());
            }
            catch (CryptographicException e)
            {
                exception = e;
                return(null);
            }
            finally
            {
                if (cek != null)
                {
                    Array.Clear(cek, 0, cekLength);
                    ArrayPool <byte> .Shared.Return(cek);
                }
            }
#else
            try
            {
                exception = null;
                return(privateKey.Decrypt(encryptedKey.ToArray(), encryptionPadding));
            }
            catch (CryptographicException e)
            {
                exception = e;
                return(null);
            }
#endif
        }
Esempio n. 22
0
        public void ToDashboardSettingsViewModel_WhenBase64StringCanBeDeserializedAndCryptographicExceptionWasThrown_ReturnsNull()
        {
            CryptographicException exception = new CryptographicException();
            IContentHelper         sut       = CreateSut(exception);

            string base64String = BuildDashboardSettingsViewModelAsBase64String();
            DashboardSettingsViewModel result = sut.ToDashboardSettingsViewModel(base64String);

            Assert.IsNull(result);
        }
Esempio n. 23
0
        public void ToValue_WhenBase64StringCanBeConvertedToUTF8AndCryptographicExceptionWasThrown_ReturnsNull()
        {
            CryptographicException exception = new CryptographicException();
            IContentHelper         sut       = CreateSut(exception);

            string base64String = BuildStringValueAsBase64String();
            string result       = sut.ToValue(base64String);

            Assert.IsNull(result);
        }
Esempio n. 24
0
        public void ToValue_WhenByteArrayCanBeConvertedToUTF8AndCryptographicExceptionWasThrown_ReturnsNull()
        {
            CryptographicException exception = new CryptographicException();
            IContentHelper         sut       = CreateSut(exception);

            byte[] byteArray = BuildStringValueAsByteArray();
            string result    = sut.ToValue(byteArray);

            Assert.IsNull(result);
        }
Esempio n. 25
0
        protected override void ReadWrongPassword(byte[] pfxBytes, string wrongPassword)
        {
            X509Certificate2Collection coll = new X509Certificate2Collection();

            CryptographicException ex = Assert.ThrowsAny <CryptographicException>(
                () => coll.Import(pfxBytes, wrongPassword, s_importFlags));

            AssertMessageContains("password", ex);
            Assert.Equal(ErrorInvalidPasswordHResult, ex.HResult);
        }
    private void StringConstructor()
    {
        // Construct a CryptographicException using a custom error message.
        string errorMessage = ("Unexpected Operation exception.");
        CryptographicException cryptographicException =
            new CryptographicException(errorMessage);

        Console.WriteLine("Created a CryptographicException with the " +
                          "following error message: " + errorMessage);
    }
Esempio n. 27
0
        public void ToDashboardViewModel_WhenByteArrayCanBeDeserializedAndCryptographicExceptionWasThrown_ReturnsNull()
        {
            CryptographicException exception = new CryptographicException();
            IContentHelper         sut       = CreateSut(exception);

            byte[]             byteArray = BuildDashboardViewModelAsByteArray();
            DashboardViewModel result    = sut.ToDashboardViewModel(byteArray);

            Assert.IsNull(result);
        }
Esempio n. 28
0
        public static void InvalidInput(string input, string messageFragment)
        {
            CryptographicException exception =
                Assert.ThrowsAny <CryptographicException>(() => new X500DistinguishedName(input));

            if (CultureInfo.CurrentCulture.Name == "en-US")
            {
                Assert.Contains(messageFragment, exception.Message);
            }
        }
Esempio n. 29
0
    public static bool DecryptFile(string Filename, string Target)
    {
        if (!File.Exists(Filename))
        {
            _exception = new CryptographicException(ERR_NO_FILE);
            return(false);
        }

        //Make sure the target file can be written
        try {
            FileStream fs = File.Create(Target);
            fs.Close();
            //fs.Dispose()  ' Works with VB 2005 only
            File.Delete(Target);
        }
        catch (Exception ex) {
            _exception = new CryptographicException(ERR_FILE_WRITE);
            return(false);
        }

        byte[] inStream   = null;
        byte[] clearBytes = null;

        try {
            StreamReader objReader = null;
            FileStream   objFS     = null;
            System.Text.ASCIIEncoding objEncoding = new System.Text.ASCIIEncoding();
            objFS     = new FileStream(Filename, FileMode.Open);
            objReader = new StreamReader(objFS);
            inStream  = objEncoding.GetBytes(objReader.ReadToEnd());
        }
        // The following is the VB 2005 equivalent
        //inStream = File.ReadAllBytes(Filename)
        catch (Exception ex) {
            _exception = new CryptographicException(ERR_FILE_READ);
            return(false);
        }

        try {
            clearBytes = _Decrypt(inStream);
        }
        catch (Exception ex) {
            _exception = new CryptographicException(ex.Message, ex.InnerException);
            return(false);
        }

        //Create the decrypted file
        FileStream outStream = File.Create(Target);

        outStream.Write(clearBytes, 0, clearBytes.Length);
        outStream.Close();
        //outStream.Dispose() ' Works with VB 2005 only

        return(true);
    }
        private static byte[]? DecryptKey(
            RSA?privateKey,
            RSAEncryptionPadding encryptionPadding,
            ReadOnlySpan <byte> encryptedKey,
            out Exception?exception)
        {
            if (privateKey == null)
            {
                exception = new CryptographicException(SR.Cryptography_Cms_Signing_RequiresPrivateKey);
                return(null);
            }

#if NETCOREAPP || NETSTANDARD2_1
            byte[]? cek = null;
            int cekLength = 0;

            try
            {
                cek = CryptoPool.Rent(privateKey.KeySize / 8);

                if (!privateKey.TryDecrypt(encryptedKey, cek, encryptionPadding, out cekLength))
                {
                    Debug.Fail("TryDecrypt wanted more space than the key size");
                    exception = new CryptographicException();
                    return(null);
                }

                exception = null;
                return(new Span <byte>(cek, 0, cekLength).ToArray());
            }
            catch (CryptographicException e)
            {
                exception = e;
                return(null);
            }
            finally
            {
                if (cek != null)
                {
                    CryptoPool.Return(cek, cekLength);
                }
            }
#else
            try
            {
                exception = null;
                return(privateKey.Decrypt(encryptedKey.ToArray(), encryptionPadding));
            }
            catch (CryptographicException e)
            {
                exception = e;
                return(null);
            }
#endif
        }