/// <summary>
 /// Decrypt method implementation
 /// </summary>
 public override byte[] Decrypt(byte[] cipherData, string description = "")
 {
     if (cipherData == null || cipherData.Length <= 0)
     {
         throw new ArgumentNullException("cipherData");
     }
     if (!IsEncrypted(cipherData))
     {
         return(cipherData);
     }
     if (!CngKey.Exists(SystemUtilities.SystemKeyName, KeyStorageProvider, CngKeyOpenOptions.MachineKey))
     {
         throw new CryptographicException(string.Format("Error : key {0} doesn't exist...", SystemUtilities.SystemKeyName));
     }
     try
     {
         byte[] unencrypted = null;
         byte[] encrypted   = RemoveHeader(cipherData);
         CngKey cngkey      = CngKey.Open(SystemUtilities.SystemKeyName, KeyStorageProvider, CngKeyOpenOptions.MachineKey);
         using (RSACng aes = new RSACng(cngkey))
         {
             unencrypted = aes.Decrypt(encrypted, RSAEncryptionPadding.OaepSHA256);
             return(unencrypted);
         }
     }
     catch (Exception Ex)
     {
         if (!string.IsNullOrEmpty(description))
         {
             Log.WriteEntry(string.Format("Error decrypting value for {0} : {1}", description, Ex.Message), System.Diagnostics.EventLogEntryType.Error, 666);
         }
         return(cipherData);
     }
 }
        /// <summary>
        /// Given a KeyProvider and a KeyName, decrypts the data with the given key
        /// </summary>
        /// <param name="providerName">Provider where the key is stored</param>
        /// <param name="keyName">Name of the key to use</param>
        /// <param name="toDecrypt">Data to decrypt</param>
        /// <param name="hashAlgorithm">OAEP hash algorithm, Look in PaddingHashAlgorithmNames.cs for values, but supports only SHA1, SHA256, SHA384, SHA512</param>
        /// <param name="paddingFlags">Padding Type, Look in PaddingFlags.cs for values, but supports only PKCS1 amd OAEP</param>
        /// <exception cref="CryptographicException">Cryptographic Exception</exception>
        /// <returns>The decrypted data</returns>
        public byte[] DecryptWithLocalKey(string providerName, string keyName, byte[] toDecrypt, string hashAlgorithm = PaddingHashAlgorithmNames.SHA512, int paddingFlags = PaddingFlags.OAEPPadding)
        {
            CngProvider provider  = new CngProvider(providerName);
            bool        keyExists = false;

            byte[] decrypted;

            try
            {
                keyExists = CngKey.Exists(keyName, provider);
            }
            catch (CryptographicException e)
            {
                // This happens if the provider isn't a valid one, but we want the exception to have better info
                throw new CryptographicException(string.Format("The provider {0} does not exist", providerName), e);
            }

            if (!keyExists)
            {
                throw new CryptographicException(string.Format("They key {0} does not exist and cannot be used for decryption", keyName));
            }

            using (CngKey key = CngKey.Open(keyName, provider))
            {
                using (RSACng rsa = new RSACng(key))
                {
                    RSAEncryptionPadding padding = this.GetRSAPadding(hashAlgorithm, paddingFlags);
                    decrypted = rsa.Decrypt(toDecrypt, padding);
                }
            }
            return(decrypted);
        }
Example #3
0
        private static byte[] decryptBytesPublicKey(byte[] data, X509Certificate2 certificate)
        {
            /*
             * byte[] chunk = new byte[16];
             * byte[] outputBytes = new byte[data.Length];
             * int position = 0;
             * int leftover = 0;
             *
             * //rsa needs to decrypt in blocks of data
             * bool notDecrypted = true;
             * while (notDecrypted)
             * {
             *  if (position + 16 < data.Length)
             *  { //if we have not reached the end, copy next 16 bytes in the chunk of data to decrypt
             *      Array.Copy(data, position, chunk, position, 16);
             *      position += 16;
             *  }
             *  else
             *  {
             *      Array.Copy(data, position, chunk, position, data.Length - position);
             *      leftover = data.Length - position;
             *      notDecrypted = false;
             *  }*/
            if (data.Length < 256)
            {
                var x = new byte[256 - data.Length];
                data = combine(x, data);
            }

            using (RSACng rsa = (RSACng)certificate.GetRSAPublicKey())
            {
                return(rsa.Decrypt(data, RSAEncryptionPadding.OaepSHA256));
                //Array.Copy(x, 0, outputBytes, position, leftover > 0 ? leftover : position);
            }
        }
 /// <summary>
 /// Decrypt method implementation
 /// </summary>
 public override string Decrypt(string cipherText, string description = "")
 {
     if (string.IsNullOrEmpty(cipherText))
     {
         return(cipherText);
     }
     if (!IsEncrypted(cipherText))
     {
         return(cipherText);
     }
     try
     {
         byte[] encrypted   = RemoveHeader(Convert.FromBase64String(cipherText));
         byte[] unencrypted = null;
         CngKey cngkey      = CngKey.Open(SystemUtilities.SystemKeyName, KeyStorageProvider, CngKeyOpenOptions.MachineKey);
         using (RSACng aes = new RSACng(cngkey))
         {
             unencrypted = aes.Decrypt(encrypted, RSAEncryptionPadding.OaepSHA256);
             return(Encoding.Unicode.GetString(unencrypted));
         }
     }
     catch (Exception Ex)
     {
         if (!string.IsNullOrEmpty(description))
         {
             Log.WriteEntry(string.Format("Error decrypting value for {0} : {1}", description, Ex.Message), System.Diagnostics.EventLogEntryType.Error, 666);
         }
         return(cipherText);
     }
 }
Example #5
0
 private static byte[] decryptBytesPrivateKey(byte[] data, X509Certificate2 certificate)
 {
     using (RSACng rsa = (RSACng)certificate.GetRSAPrivateKey())
     {
         return(rsa.Decrypt(data, RSAEncryptionPadding.OaepSHA256));
     }
 }
Example #6
0
        public byte[] Unwrap(byte[] encryptedCek, object key, int cekSizeBits, IDictionary <string, object> header)
        {
            if (key is CngKey)
            {
                var privateKey = new RSACng((CngKey)key);

                var padding = useRsaOaepPadding ? RSAEncryptionPadding.OaepSHA1 :
                              RSAEncryptionPadding.Pkcs1;

                return(privateKey.Decrypt(encryptedCek, padding));
            }

            if (key is RSACryptoServiceProvider)
            {
                var privateKey = (RSACryptoServiceProvider)key;

                return(privateKey.Decrypt(encryptedCek, useRsaOaepPadding));
            }

            if (key is RSA)
            {
                var privateKey = (RSA)key;

                var padding = useRsaOaepPadding ? RSAEncryptionPadding.OaepSHA1 :
                              RSAEncryptionPadding.Pkcs1;

                return(privateKey.Decrypt(encryptedCek, padding));
            }

            throw new ArgumentException("RsaKeyManagement algorithm expects key to be of either CngKey, RSACryptoServiceProvider or RSA types.");
        }
Example #7
0
        /// <summary>
        /// Decrypt the text using the specified CNG key.
        /// </summary>
        /// <param name="rsaCngProvider">RSA CNG Provider.</param>
        /// <param name="encryptedColumnEncryptionKey">Encrypted Column Encryption Key.</param>
        /// <returns>Returns the decrypted plaintext Column Encryption Key or throws an exception if there are any errors.</returns>
        private byte[] RSADecrypt(RSACng rsaCngProvider, byte[] encryptedColumnEncryptionKey)
        {
            Debug.Assert((encryptedColumnEncryptionKey != null) && (encryptedColumnEncryptionKey.Length != 0));
            Debug.Assert(rsaCngProvider != null);

            return(rsaCngProvider.Decrypt(encryptedColumnEncryptionKey, RSAEncryptionPadding.OaepSHA1));
        }
Example #8
0
        public object Decrypt(object value, string keyName = null)
        {
#if NETSTANDARD
            using (var rsa = new RSACng())
            {
                var privateKey = GetParameters(KeyStore.GetKey(PrivateKey));
                rsa.ImportParameters(privateKey);

                var cypherBytes = Convert.FromBase64String(value.ToString());
                var plainBytes  = rsa.Decrypt(cypherBytes, Padding);

                return(Encoding.UTF8.GetString(plainBytes));
            }
#else
            using (var rsa = (RSACryptoServiceProvider)RSA.Create())
            {
                var privateKey = GetParameters(KeyStore.GetKey(PrivateKey));
                rsa.ImportParameters(privateKey);

                var cypherBytes = Convert.FromBase64String(value.ToString());
                var plainBytes  = rsa.Decrypt(cypherBytes, false);

                return(Encoding.UTF8.GetString(plainBytes));
            }
#endif
        }
Example #9
0
            public static string Decrypt(string B64text, string Key, int Keybits = 2048)
            {
                string plainText = "";

                byte[] encryptedBytes = null;
                byte[] plainBytes     = null;

                try
                {
                    using (RSACng rsa = new RSACng(Keybits))
                    {
                        rsa.FromXmlString(Key);
                        encryptedBytes = Convert.FromBase64String(B64text);
                        plainBytes     = rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.Pkcs1);
                        plainText      = Encoding.Unicode.GetString(plainBytes);
                    }
                    return(plainText);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception decrypting file! More info:");
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                }

                return(null);
            }
Example #10
0
        /// <summary>
        /// Given a KeyProvider and a KeyName, decrypts the data with the given key
        /// </summary>
        /// <param name="providerName">Provider where the key is stored</param>
        /// <param name="keyName">Name of the key to use</param>
        /// <param name="toDecrypt">Data to decrypt</param>
        /// <param name="hashAlgorithm">OAEP hash algorithm, Look in PaddingHashAlgorithmNames.cs for values, but supports only SHA1, SHA256, SHA384, SHA512</param>
        /// <param name="paddingFlags">Padding Type, Look in PaddingFlags.cs for values, but supports only PKCS1 amd OAEP</param>
        /// <exception cref="CryptographicException">Cryptographic Exception</exception>
        /// <returns>The decrypted data</returns>
        public byte[] DecryptWithLocalKey(string providerName, string keyName, byte[] toDecrypt, string hashAlgorithm = PaddingHashAlgorithmNames.SHA512, int paddingFlags = PaddingFlags.OAEPPadding)
        {
            CngProvider provider = new CngProvider(providerName);

            byte[]            decrypted;
            CngKeyOpenOptions cngkeyOpenOpts = CngKeyOpenOptions.MachineKey;
            bool keyExists = doesKeyExists(provider, keyName, cngkeyOpenOpts);

            if (!keyExists)
            {
                if (doesKeyExists(provider, keyName, CngKeyOpenOptions.None))
                {
                    cngkeyOpenOpts = CngKeyOpenOptions.None;
                }
                else
                {
                    throw new CryptographicException(string.Format("They key {0} does not exist and cannot be used for decryption", keyName));
                }
            }

            using (CngKey key = CngKey.Open(keyName, provider, cngkeyOpenOpts))
            {
                using (RSACng rsa = new RSACng(key))
                {
                    RSAEncryptionPadding padding = this.GetRSAPadding(hashAlgorithm, paddingFlags);
                    decrypted = rsa.Decrypt(toDecrypt, padding);
                }
            }
            return(decrypted);
        }
Example #11
0
        public static byte[] Decrypt(byte[] privateKey, byte[] data)
        {
            CngKey key    = CngKey.Import(privateKey, CngKeyBlobFormat.GenericPrivateBlob);
            RSACng crypto = new RSACng(key);
            var    result = crypto.Decrypt(data, RSAEncryptionPadding.OaepSHA512);

            return(result);
        }
Example #12
0
 public static byte[] DecryptRSA(byte[] data, RSACng privateKey, RSAEncryptionPadding padding)
 {
     //using (RSACng instance = new RSACng()) {
     //instance.ImportParameters(privateKey.ExportParameters(true));
     //return instance.Encrypt(data, padding);
     //}
     return(privateKey.Decrypt(data, padding));
 }
Example #13
0
        internal static void DecryptXml(RSACng asymmetricAlgorithm, XmlDocument xmlDoc, string[] xmlElementsXPaths)
        {
            if (asymmetricAlgorithm == null)
            {
                throw new ArgumentNullException("asymmetricAlgorithm");
            }
            if (xmlDoc == null)
            {
                throw new ArgumentNullException("xmlDoc");
            }
            if (xmlElementsXPaths == null)
            {
                throw new ArgumentNullException("xmlElementsXPaths");
            }

            // create the symmetric algorithm which was used for encryption
            var symmetricAlgorithm = new AesManaged();

            symmetricAlgorithm.Padding = PaddingMode.ISO10126;

            foreach (var xPath in xmlElementsXPaths)
            {
                // select all encrypted attribute elements
                var encryptedElements = xmlDoc.SelectNodes(xPath);

                Debug.Assert(encryptedElements != null, "encryptedElements != null");
                foreach (XmlNode encryptedElement in encryptedElements)
                {
                    // load the encrypted data element
                    var encryptedDataElement = encryptedElement.SelectSingleNode("//*[local-name() = 'EncryptedData']") as XmlElement;
                    var encryptedData        = new EncryptedData();
                    Debug.Assert(encryptedDataElement != null, "encryptedDataElement != null");
                    encryptedData.LoadXml(encryptedDataElement);

                    // load the encrypted key element
                    var encryptedKeyElement = encryptedDataElement.SelectSingleNode("//*[local-name() = 'EncryptedKey']") as XmlElement;
                    var encryptedKey        = new EncryptedKey();
                    Debug.Assert(encryptedKeyElement != null, "encryptedKeyElement != null");
                    encryptedKey.LoadXml(encryptedKeyElement);

                    // decrypt the key using the specifief asymmetric algorithm
                    var symetricKey = asymmetricAlgorithm.Decrypt(encryptedKey.CipherData.CipherValue, RSAEncryptionPadding.OaepSHA1);

                    // use the asymmetric decrypted key to decrypt the encrypted data using the specified symmetric algorithm
                    symmetricAlgorithm.Key = symetricKey;

                    var output = new EncryptedXml {
                        Mode = CipherMode.CBC, Padding = PaddingMode.ISO10126
                    };
                    var data = output.DecryptData(encryptedData, symmetricAlgorithm);

                    // replace the encrypted element with its decrypted form
                    output.ReplaceData((XmlElement)encryptedElement, data);
                }
            }
        }
Example #14
0
        public string Decrypt(string encryptedData, string keyName)
        {
            var key         = CngKey.Open(keyName);
            var decodedData = Convert.FromBase64String(encryptedData);
            var cng         = new RSACng(key);

            var decryptedData = cng.Decrypt(decodedData, RSAEncryptionPadding.Pkcs1);
            var decodedString = Encoding.UTF8.GetString(decryptedData);

            return(decodedString);
        }
        public string RSADecrypt(string cipherText)
        {
            var keyData = Convert.FromBase64String(_privateKey);

            using var cngKey = CngKey.Import(keyData, CngKeyBlobFormat.Pkcs8PrivateBlob);
            using var rsa    = new RSACng(cngKey);
            var data = Convert.FromBase64String(cipherText);

            var decryptData = rsa.Decrypt(data, RSAEncryptionPadding.OaepSHA256);

            return(Encoding.UTF8.GetString(decryptData));
        }
Example #16
0
        /// <summary>
        /// Decrypts the message using an exchange private key that has a pin.
        /// </summary>
        /// <param name="encryptedMessage">Encrypted message as base64 string to be decrypted</param>
        /// <param name="privateKey">Private exchange key to decrypt the message</param>
        /// <param name="padding">Padding mode to be used with the decryption</param>
        /// <param name="pin">The private key pin</param>
        /// <returns>Decrypted message as byte array</returns>
        /// <exception cref="ArgumentException">There is null in the parameters or one of the parameters empty</exception>
        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired.-or- The parameters parameter has missing fields. -or- The padding mode is not supported. -or- The certificate context is invalid. -or- wrong pin has been inputed.</exception>
        /// <exception cref="FormatException">The length of string, ignoring white-space characters, is not zero or a multiple of 4. -or-The format of s is invalid. string contains a non-base-64 character, more than two padding characters, or a non-white space-character among the padding characters.</exception>
        public static byte[] Decrypt(string encryptedMessage, X509Certificate2 privateKey, RSAEncryptionPadding padding, string pin)
        {
            try
            {
                byte[] decodedEncryptedBytes = Convert.FromBase64String(encryptedMessage);
                RSA    rsa    = privateKey.GetRSAPrivateKey();
                RSACng rsaCng = rsa as RSACng;
                if (rsaCng != null)
                {
                    // Set the PIN, an explicit null terminator is required to this Unicode/UCS-2 string.

                    byte[] propertyBytes;

                    if (pin[pin.Length - 1] == '\0')
                    {
                        propertyBytes = Encoding.Unicode.GetBytes(pin);
                    }
                    else
                    {
                        propertyBytes = new byte[Encoding.Unicode.GetByteCount(pin) + 2];
                        Encoding.Unicode.GetBytes(pin, 0, pin.Length, propertyBytes, 0);
                    }

                    const string NCRYPT_PIN_PROPERTY = "SmartCardPin";

                    CngProperty pinProperty = new CngProperty(
                        NCRYPT_PIN_PROPERTY,
                        propertyBytes,
                        CngPropertyOptions.None);

                    rsaCng.Key.SetProperty(pinProperty);
                    return(rsaCng.Decrypt(decodedEncryptedBytes, padding));
                }
                throw new CryptographicException("The key is not compatible with Cryptography Next Generation (CNG)");
            }
            catch (CryptographicException ex)
            {
                throw ex;
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            catch (FormatException ex)
            {
                throw ex;
            }
        }
        private UserConnection ProcessClient(Socket s)
        {
            var ss = Encoding.ASCII.GetBytes("aaaa can you see this??");

            s.Send(ss);
            UserConnection conn = new UserConnection();

            conn.Sock = s;
            conn.Aes  = new AesCryptoServiceProvider();
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                using (RSACng rsa = new RSACng(3072))
                {
                    conn.Sock.Send(rsa.ExportRSAPublicKey());
                    var aesKey = new byte[384];
                    conn.Sock.Receive(aesKey);
                    conn.Aes.Key = rsa.Decrypt(aesKey, RSAEncryptionPadding.Pkcs1);
                }
            }
            else
            {
                using (RSAOpenSsl rsa = new RSAOpenSsl(3072))
                {
                    conn.Sock.Send(rsa.ExportRSAPublicKey());
                    var aesKey = new byte[384];
                    conn.Sock.Receive(aesKey);
                    conn.Aes.Key = rsa.Decrypt(aesKey, RSAEncryptionPadding.Pkcs1);
                }
            }
            byte[] encryptedMsg;
            var    header = new byte[20];

            conn.Aes.IV.CopyTo(header, 0);
            using (MemoryStream mem = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(mem, conn.Aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    using (StreamWriter sw = new StreamWriter(cs))
                        sw.Write("OK!");
                    encryptedMsg = mem.ToArray();
                }
            }
            BitConverter.GetBytes(encryptedMsg.Length).CopyTo(header, 16);
            conn.Sock.Send(header);
            conn.Sock.Send(encryptedMsg);
            return(conn);
        }
Example #18
0
        public T104 GetSymmetricKeyAndSignature()
        {
            Request request = new Request(appConfig);

            request.GlobalInfo.InterfaceCode = "T104";
            T104 response = (T104)SendRequest(request);

            byte[] privateKey = Convert.FromBase64String(File.ReadAllText(appConfig.PrivateKey));
            using (CngKey signingKey = CngKey.Import(privateKey, CngKeyBlobFormat.Pkcs8PrivateBlob))
                using (RSACng rsaCng = new RSACng(signingKey))
                {
                    byte[] decryptedAESKey = rsaCng.Decrypt(Convert.FromBase64String(response.PasswordAes), RSAEncryptionPadding.Pkcs1);
                    string AESKey          = Encoding.UTF8.GetString(decryptedAESKey);
                    File.WriteAllText(appConfig.SessionAESKey, AESKey);
                }
            return(response);
        }
Example #19
0
        protected override bool HandshakeActive(SendCall Send, ReceiveCall Receive)
        {
            Send(Encoding.ASCII.GetBytes(KEXCrypto.ToXmlString(false)));
            if (!Receive(out byte[] data, out EndPoint source))
            {
                return(false);
            }

            DataCrypto.Key = KEXCrypto.Decrypt(data, RSAEncryptionPadding.OaepSHA256);
            Send(DataCrypto.IV);

            if (!Receive(out data, out source))
            {
                return(false);
            }

            return(DecryptSecret(data));
        }
Example #20
0
        public void RSACngTest()
        {
            byte[] keyData;
            var    rsaKeyParameters = new CngKeyCreationParameters
            {
                ExportPolicy = CngExportPolicies.AllowPlaintextExport,
                KeyUsage     = CngKeyUsages.AllUsages,
                Parameters   =
                {
                    new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None)
                }
            };

            using (var key = CngKey.Create(CngAlgorithm.Rsa, null, rsaKeyParameters))
            {
                keyData = key.Export(CngKeyBlobFormat.Pkcs8PrivateBlob);
            }

            Console.WriteLine("-----BEGIN PRIVATE KEY-----");
            Console.WriteLine(Convert.ToBase64String(keyData, Base64FormattingOptions.InsertLineBreaks));
            Console.WriteLine("-----END PRIVATE KEY-----");

            string original = "Hello world!";

            Console.WriteLine(original);

            byte[] encrypted;

            using (var key = CngKey.Import(keyData, CngKeyBlobFormat.Pkcs8PrivateBlob))
                using (var rsa = new RSACng(key))
                {
                    encrypted = rsa.Encrypt(Encoding.UTF8.GetBytes(original), RSAEncryptionPadding.Pkcs1);
                }

            Console.WriteLine(Convert.ToBase64String(encrypted));

            string decrypted;

            using (var key = CngKey.Import(keyData, CngKeyBlobFormat.Pkcs8PrivateBlob))
                using (var rsa = new RSACng(key))
                {
                    decrypted = Encoding.UTF8.GetString(rsa.Decrypt(encrypted, RSAEncryptionPadding.Pkcs1));
                }
        }
Example #21
0
        public override byte[] Decrypt(byte[] cipherBytes, byte[] iv = null, string keyName = null)
        {
#if NETSTANDARD
            using (var rsa = new RSACng())
            {
                var privateKey = GetParameters(KeyStore.GetKey(PrivateKey));
                rsa.ImportParameters(privateKey);

                return(rsa.Decrypt(cipherBytes, Padding));
            }
#else
            using (var rsa = (RSACryptoServiceProvider)RSA.Create())
            {
                var privateKey = GetParameters(KeyStore.GetKey(PrivateKey));
                rsa.ImportParameters(privateKey);

                return(rsa.Decrypt(cipherBytes, false));
            }
#endif
        }
        public byte[] Decrypt(byte[] encryptedData)
        {
            CngProvider provider = new CngProvider(kspName);
            CngKey      key;

            // If you get an error here, make sure you register the KSP and the project run in 64bits
            if (!CngKey.Exists(keyId, provider))
            {
                throw new System.ArgumentException("Key " + keyId + " not found in " + kspName);
            }

            key = CngKey.Open(keyId, provider);
            RSACng cryptoEngine = new RSACng(key);

            var decryptedData = cryptoEngine.Decrypt(encryptedData, System.Security.Cryptography.RSAEncryptionPadding.OaepSHA256);

            cryptoEngine.Dispose();
            key.Dispose();

            return(decryptedData);
        }
Example #23
0
 DecryptAsync(byte[] ciphertext, byte[] iv, byte[] authenticationData, byte[] authenticationTag, string algorithm, System.Threading.CancellationToken token)
 {
     byte[] plaintext = rsaPrivateKey.Decrypt(ciphertext, RSAEncryptionPadding.OaepSHA1);
     return(Task.FromResult(plaintext));
 }
Example #24
0
 /// <summary>
 ///     Decrypts a string using the <see cref="RSA"/> algorithm.
 /// </summary>
 /// <param name="s">The encrypted string.</param>
 /// <param name="params">The <see cref="RSAParameters"/> that should be used.</param>
 /// <returns>Returns the decrypted string.</returns>
 public string RSADecrypt(string s, RSAParameters @params)
 {
     rsa.ImportParameters(@params);
     return(Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(s), RSAEncryptionPadding.Pkcs1)));
 }
Example #25
0
 public byte[] Decrypt(byte[] encryptedBytes)
 {
     return(rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.Pkcs1));
 }
Example #26
0
        private void Connecting(string userName, string password)
        {
#if NETCOREAPP
            using (var clientRSA = RSA.Create())
#else
            using (var clientRSA = new RSACng())
#endif
            {
                var clientPK = clientRSA.Export();
                using (DataPackage request = new DataPackage("UserName.String.32", "PublicKey.String.256"))
                {
                    request.Headers.Add("ActionID", "Sys.LoginRequest");
                    request.Headers.Add("UserName", userName);
                    request.UpdateHeaders();
                    request.AddNew();
                    request["UserName"]  = userName;
                    request["PublicKey"] = clientPK;
                    request.Update();
                    using (var response = SendAndRecieve(request))
                    {
                        if (response.Headers.ContainsKey("Status") &&
                            (string)response.Headers["Status"] == "ERROR")
                        {
                            throw new TCPConnectorException(response);
                        }

                        response.GoDataTop();
                        response.Read();
                        _loginInfo = new LoginInfo();
                        _loginInfo.Import(clientRSA.Decrypt(((string)response["LoginInfo"]).ToByteArray(), _padding));
                        _clientAes = Aes.Create()
                                     .ImportBin(_loginInfo.CryptoKey);
                    }
                }

                using (var request = new DataPackage("UserName.String.32", "SessionID.String.34", "EncryptedKey.String.256"))
                {
                    request.Headers.Add("ActionID", "Sys.Logon");
                    request.Headers.Add("UserName", userName);
                    request.UpdateHeaders();
                    request.AddNew();
                    request["UserName"]     = userName;
                    request["SessionID"]    = _loginInfo.SessionID.ToString();
                    request["EncryptedKey"] = _clientAes
                                              .EncryptBin(Encoding.UTF8.GetBytes(password))
                                              .ToBASE64String();
                    request.Update();
                    using (var response = SendAndRecieve(request))
                    {
                        if (response.Headers.ContainsKey("Status") &&
                            (string)response.Headers["Status"] == "ERROR")
                        {
                            throw new TCPConnectorException(response);
                        }

                        response.GoDataTop();
                        response.Read();
                        var token = (string)response["Ticket"];
                        _ticket = new Guid(_clientAes.DecryptBin(token.ToByteArray()).Take(16).ToArray());
                        //_ticket = new Guid(((BinaryDataBuffer)_clientAes.DecryptBin(token.ToByteArray())).Slice(0, 16));
                        //_userName = userName;
                        Connected = true;
                    }
                }
            }
        }
Example #27
0
        public override X509Certificate2 LoadApplicationCertificate(string thumbprint, string subjectName, string applicationURI, string password)
        {
            try
            {
                // Create a handle based on the hash of the keys
                ushort    slotIndex = ushort.Parse(thumbprint);
                TpmHandle nvHandle  = TpmHandle.NV(slotIndex);
                ushort    offset    = 0;

                // Read the serial number
                byte[] serialNumber = m_tpm[m_ownerAuth].NvRead(nvHandle, nvHandle, sizeof(long), offset);
                offset += sizeof(long);

                // Read the "valid from" date (today) in FileTime format
                byte[] validFrom = m_tpm[m_ownerAuth].NvRead(nvHandle, nvHandle, sizeof(long), offset);
                offset += sizeof(long);

                // Read size of keys from NV storage (located in the first 4 bytes)
                byte[] certSizeBlob = m_tpm[m_ownerAuth].NvRead(nvHandle, nvHandle, sizeof(int), offset);
                offset += sizeof(int);

                // Read keys from NV storage in 64-byte chunks
                int    certSize   = BitConverter.ToInt32(certSizeBlob, 0);
                byte[] rawData    = new byte[certSize];
                ushort index      = 0;
                ushort sizeToRead = 0;
                while (index < certSize)
                {
                    if ((certSize - index) < 64)
                    {
                        sizeToRead = (ushort)(certSize - index);
                    }
                    else
                    {
                        sizeToRead = 64;
                    }

                    byte[] dataToRead = m_tpm[m_ownerAuth].NvRead(nvHandle, nvHandle, sizeToRead, offset);
                    offset += sizeToRead;

                    for (int i = 0; i < sizeToRead; i++)
                    {
                        rawData[index + i] = dataToRead[i];
                    }

                    index += sizeToRead;
                }

                // Import
                TextReader textReader        = new StringReader(new string(Encoding.ASCII.GetChars(rawData)));
                PemReader  pemReader         = new PemReader(textReader);
                AsymmetricCipherKeyPair keys = (AsymmetricCipherKeyPair)pemReader.ReadObject();

                X509Name   CN            = new X509Name("CN=" + subjectName + ",DC=" + Utils.GetHostName());
                BigInteger SN            = new BigInteger(serialNumber).Abs();
                DateTime   validFromDate = DateTime.FromFileTime(BitConverter.ToInt64(validFrom, 0));

                // Certificate Generator
                X509V3CertificateGenerator cGenerator = new X509V3CertificateGenerator();
                cGenerator.SetSerialNumber(SN);
                cGenerator.SetSubjectDN(CN);
                cGenerator.SetIssuerDN(CN);
                cGenerator.SetNotBefore(validFromDate);
                cGenerator.SetNotAfter(validFromDate.AddYears(1));
                cGenerator.SetPublicKey(keys.Public);
                cGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(new List <DerObjectIdentifier>()
                {
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.1")
                }));
                cGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keys.Public), new GeneralNames(new GeneralName(CN)), SN));
                cGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.UniformResourceIdentifier, applicationURI)));

                ISignatureFactory signatureFactory         = new Asn1SignatureFactory("SHA1withRSA", keys.Private, new SecureRandom());
                Org.BouncyCastle.X509.X509Certificate cert = cGenerator.Generate(signatureFactory);
                X509Certificate2 certificate = new X509Certificate2(cert.GetEncoded());

                RSACng rsa = new RSACng();
                RsaPrivateCrtKeyParameters keyParams = (RsaPrivateCrtKeyParameters)keys.Private;

                m_RSAParams = new RSAParameters();

                m_RSAParams.Modulus = new byte[keyParams.Modulus.ToByteArrayUnsigned().Length];
                keyParams.Modulus.ToByteArrayUnsigned().CopyTo(m_RSAParams.Modulus, 0);

                m_RSAParams.P = new byte[keyParams.P.ToByteArrayUnsigned().Length];
                keyParams.P.ToByteArrayUnsigned().CopyTo(m_RSAParams.P, 0);

                m_RSAParams.Q = new byte[keyParams.Q.ToByteArrayUnsigned().Length];
                keyParams.Q.ToByteArrayUnsigned().CopyTo(m_RSAParams.Q, 0);

                m_RSAParams.DP = new byte[keyParams.DP.ToByteArrayUnsigned().Length];
                keyParams.DP.ToByteArrayUnsigned().CopyTo(m_RSAParams.DP, 0);

                m_RSAParams.DQ = new byte[keyParams.DQ.ToByteArrayUnsigned().Length];
                keyParams.DQ.ToByteArrayUnsigned().CopyTo(m_RSAParams.DQ, 0);

                m_RSAParams.InverseQ = new byte[keyParams.QInv.ToByteArrayUnsigned().Length];
                keyParams.QInv.ToByteArrayUnsigned().CopyTo(m_RSAParams.InverseQ, 0);

                m_RSAParams.D = new byte[keyParams.Exponent.ToByteArrayUnsigned().Length];
                keyParams.Exponent.ToByteArrayUnsigned().CopyTo(m_RSAParams.D, 0);

                m_RSAParams.Exponent = new byte[keyParams.PublicExponent.ToByteArrayUnsigned().Length];
                keyParams.PublicExponent.ToByteArrayUnsigned().CopyTo(m_RSAParams.Exponent, 0);

                rsa.ImportParameters(m_RSAParams);
                if (rsa != null)
                {
                    int    inputBlockSize = rsa.KeySize / 8 - 42;
                    byte[] bytes1         = rsa.Encrypt(new byte[inputBlockSize], RSAEncryptionPadding.OaepSHA1);
                    byte[] bytes2         = rsa.Decrypt(bytes1, RSAEncryptionPadding.OaepSHA1);
                    if (bytes2 != null)
                    {
                        return(certificate);
                    }
                }
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Could not load application certificate " + subjectName);
            }

            return(null);
        }
Example #28
0
 private static byte[] DecryptRsa(byte[] Input, RSACng RSA) => RSA.Decrypt(Input, RSAEncryptionPadding.CreateOaep(HashAlgorithmName.SHA256));
Example #29
0
 public virtual byte[] Decrypt(byte[] dataForDecryption)
 {
     return(Rsa.Decrypt(dataForDecryption, RSAEncryptionPadding.Pkcs1));
 }
Example #30
0
 public byte[] Decrypt(byte[] bytes)
 {
     return(algorithm.Decrypt(bytes, RSAEncryptionPadding.OaepSHA256));
 }