Esempio n. 1
0
 public void Dispose()
 {
     if (_disposeCryptoProvider && _rsaKey != null)
     {
         _rsaKey.Dispose();
     }
 }
Esempio n. 2
0
        private void openPrivateKeyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (privateKey != null)
            {
                privateKey.Dispose();
                privateKey = null;
            }

            openFileDialog1.Title = "Open Private Key";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string privateKeyFile;
                    using (var streamReader = new StreamReader(openFileDialog1.FileName, Encoding.UTF8))
                    {
                        privateKeyFile = streamReader.ReadToEnd();
                    }
                    privateKey = RSAKeys.ImportPrivateKey(privateKeyFile);
                }
                catch (Exception ex)
                {
                    privateKey = null;
                    resetOpenFileDialog();
                    MessageBox.Show("Error while importing Private Key" + Environment.NewLine + ex.Message);
                    return;
                }
                label6.Text = openFileDialog1.FileName;
            }
            resetOpenFileDialog();
            toggleControls();
        }
Esempio n. 3
0
        // функция для ПРОВЕРКИ ЭЦП
        // аргументы: вход. байты сообщения; ключ (приватный/публичный), сформированная подпись
        public static bool edsAlg_verifyData(Byte[] message, Byte[] key, Byte[] sign)
        {
            bool result_check = false; // На выходе либо ДА либо НЕТ

            try
            {
                try
                {
                    if (key.Length < global.eds_size_key_byte)
                    {
                        throw new Exception("Введенный ключ не подходит этому приложению! (Не соответствие размера)");
                    }
                }
                catch
                {
                    throw;
                }
                try
                {
                    if (sign.Length < global.eds_size_key_byte)
                    {
                        throw new Exception("Формат заданной подписи не подходит этому приложению! (Не соответствие размера)");
                    }
                }
                catch
                {
                    throw;
                }

                RSACryptoServiceProvider rsaeds = new RSACryptoServiceProvider(global.eds_size_key_bit);  // объект класса у алгоритма RSA
                // ввод ключа
                try
                {
                    rsaeds.ImportCspBlob(key); // присваиваем ключ из аргумента
                }
                catch
                {
                    rsaeds.Dispose();
                    throw new Exception("Произошла ошибка при импортировании ключа в метод RSA!");
                }
                // проверка подписи для исходного сообщения
                try
                {
                    result_check = rsaeds.VerifyData(message, sign, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
                }
                catch
                {
                    rsaeds.Dispose();
                    throw new Exception("Произошла ошибка при проверке подписи!\nПроверьте правильность введенных данных:\n> Файл с данными;\n> Ключ\n> Подпись, которую проверяем для сообщения;");
                }
                rsaeds.Dispose();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return(result_check);
        }
Esempio n. 4
0
 public void Dispose()
 {
     _rsa?.Dispose();
     _rsa = null;
     _sha?.Dispose();
     _sha = null;
 }
Esempio n. 5
0
        public static string Encrypt(string publicKey, string textToEncrypt)
        {
            byte[] plainBytes     = null;
            byte[] encryptedBytes = null;
            string encryptedText  = "";

            using (var rsaProvider = new RSACryptoServiceProvider()) {
                try {
                    rsaProvider.FromXmlString(publicKey);

                    plainBytes     = Encoding.Unicode.GetBytes(textToEncrypt);
                    encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
                    encryptedText  = Convert.ToBase64String(encryptedBytes);
                }
                catch (Exception ex) {
                    Print(String.Format("[ENCRYPT] Exception: {0}", ex.Message));
                }
                finally {
                    rsaProvider.PersistKeyInCsp = false;
                    rsaProvider.Dispose();
                }
            }

            return(encryptedText);
        }
Esempio n. 6
0
        //http://blog.csdn.net/besley/article/details/7918787
        public static string Signature(string hashal = "SHA1")
        {
            string docFile = @"G:\MyCode\CSharp\20170418\X509Encyption\testSendFile.txt";

            byte[] hashBytes;
            using (FileStream fs = new FileStream(docFile, FileMode.Open))
            {
                //计算报文的Hash值
                HashAlgorithm hashAlgorithm = HashAlgorithm.Create(hashal);
                hashBytes = hashAlgorithm.ComputeHash(fs);
                fs.Close();
            }

            //Bob用自己(发送方)的私钥对报文摘要进行签名
            //包含私钥文件的rsa算法初始化
            string           priKeyFile  = @"G:\MyCode\CSharp\20170418\X509Encyption\public_privatekey.pfx";
            X509Certificate2 certEncrypt = new X509Certificate2(priKeyFile, "abc123");

            byte[] signedHashBytes;
            using (RSACryptoServiceProvider rsaProviderEncrypt = (RSACryptoServiceProvider)certEncrypt.PrivateKey)
            {
                //给报文摘要进行签名
                RSAPKCS1SignatureFormatter signFormatter = new RSAPKCS1SignatureFormatter(rsaProviderEncrypt);
                signFormatter.SetHashAlgorithm(hashal);
                signedHashBytes = signFormatter.CreateSignature(hashBytes);
                rsaProviderEncrypt.Dispose();
            }

            return(Convert.ToBase64String(signedHashBytes));
        }
        public static string Encrypt(string input)
        {
            //get X509 certificate from store
            X509Certificate2 cert = LoadCertificate();

            //use public key to encrypt
            var publicKey = cert.PublicKey.Key as RSACryptoServiceProvider;

            //get XML string of public key from certificate
            RSACryptoServiceProvider rsaEncryptor = new RSACryptoServiceProvider();

            //var xmlStringPublicKey = @"<RSAKeyValue><Modulus>u4zh/l+JL2GzHqsVH95dsZNfqfdI1rHSVFnpJky0e3pEv4/GuifblaME3w9Dcu64js9OzpRX1C4yqMhkTbH3BkeDGXXaI/pwvWWHWfTVAgubLL/5XvlGPWK/GgAwKTYebyTKDOkVWKpGfrd/JKZJKkwY1aXO/+ZM8RfPOYek1wuJ7r3ZGyEnw9UDf+6b/G0mibmXvosftpR6rSb4FSjVD4Uhef2NHTw1z0oGcVT3vAlUBCjmLU2DVWO8OsH5fZV7vevC7qY1o9Quu5kXmI59EN/bL8BU5uOeobDYGvR8yYztDD6KMsHQE37b3+IukjMb5/ca3CpSIUmsZa+GmirN+Q==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
            //rsaEncryptor.FromXmlString(xmlStringPublicKey);

            rsaEncryptor.FromXmlString(publicKey.ToXmlString(false));

            //encrypt input string
            byte[] cipherData = rsaEncryptor.Encrypt(Encoding.UTF8.GetBytes(input), true);

            //dispose object
            rsaEncryptor.Dispose();

            //convert to base64string from byte[] and return
            var toBase64String = Convert.ToBase64String(cipherData);

            return(toBase64String);
        }
Esempio n. 8
0
        static void Main()
        {
            // imposta i parametri del CSP per ottenere il container della chiave sulla CIE
            var cspParameters = new CspParameters(1, "Microsoft Base Smart Card Crypto Provider");

            cspParameters.Flags = CspProviderFlags.UseDefaultKeyContainer;

            // il middleware CIE espone un container di tipo Signature
            cspParameters.KeyNumber = (int)KeyNumber.Signature;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspParameters);
            // dal nome del container ricavo l'IdServizi.
            var idSerivizi = rsa.CspKeyContainerInfo.UniqueKeyContainerName.Replace("CIE-", "/");

            rsa.Dispose();

            // apro lo store dei certificati personali
            var store = new X509Store(StoreName.My);

            store.Open(OpenFlags.ReadOnly);

            // cerco nello store un certificato che abbia l'IdServizi nel Subject name
            var cc = store.Certificates.Find(X509FindType.FindBySubjectName, idSerivizi, false);

            // evito la validazione del certificato del server. In ambienti di produzione è necessario verificare che il server sia trusted
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

            // creo una web request  impostando il certificato della CIE come ClienCertificate
            var req = HttpWebRequest.Create("https://localhost/register.aspx") as HttpWebRequest;

            req.ClientCertificates.Add(cc[0]);

            // al momento dell'invio della request verrà richiesto il PIN
            var response = new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd();
        }
Esempio n. 9
0
        /// <summary>
        /// Read RSA public and private key from file or create new even if one of keys not exist.
        /// </summary>
        private static void SetRsaKeys()
        {
            string rsaPrivateKeyJson = File.ReadAllText(AppPaths.RsaPrivateKeyFilePath);
            string rsaPublicKeyJson  = File.ReadAllText(AppPaths.RsaPublicKeyFilePath);

            if (string.IsNullOrEmpty(rsaPrivateKeyJson) || string.IsNullOrEmpty(rsaPublicKeyJson))
            {
                using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider(RsaKeySize))
                {
                    _rsaPrivateKey = csp.ExportParameters(true);
                    _rsaPublicKey  = csp.ExportParameters(false);
                    csp.Dispose();
                }

                rsaPrivateKeyJson = _rsaPrivateKey.Serialize();
                rsaPublicKeyJson  = _rsaPublicKey.Serialize();

                File.WriteAllText(AppPaths.RsaPrivateKeyFilePath, rsaPrivateKeyJson);
                File.WriteAllText(AppPaths.RsaPublicKeyFilePath, rsaPublicKeyJson);
            }
            else
            {
                _rsaPrivateKey = ObjectToJson.Deserialize <RSAParameters>(rsaPrivateKeyJson);
                _rsaPublicKey  = ObjectToJson.Deserialize <RSAParameters>(rsaPublicKeyJson);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Deletes the RSA key with the specified key container name, if it exists.
        /// </summary>
        /// <param name="keystore">Specify which keystore the key should be deleted from.</param>
        /// <param name="keyContainerName">A string which uniquely identifies this encryption key among all other keys in the keystore.</param>
        public static void DeletePublicKeyFromKeystore(Keystore keystore, string keyContainerName)
        {
            CspParameters cspParams = CreateCspParameters(keystore, keyContainerName);

            cspParams.Flags |= CspProviderFlags.UseExistingKey;
            RSACryptoServiceProvider rsa;

            try
            {
                // Try to open existing key
                rsa = new RSACryptoServiceProvider(keySize, cspParams);
            }
            catch (CryptographicException)
            {
                return;                 // Key does not exist or is inaccessible.  No further action can be done.
            }
            try
            {
                // Delete existing key
                rsa.PersistKeyInCsp = false;
                rsa.Clear();
            }
            finally
            {
                rsa.Dispose();
            }
        }
Esempio n. 11
0
        private string CreateKeyPair()
        {
            ITracer tracer = _traceFactory.GetTracer();

            using (tracer.Step("SSHKeyManager.CreateKey"))
            {
                RSACryptoServiceProvider rsa = null;
                try
                {
                    rsa = new RSACryptoServiceProvider(dwKeySize: KeySize);
                    RSAParameters privateKeyParam = rsa.ExportParameters(includePrivateParameters: true);
                    RSAParameters publicKeyParam  = rsa.ExportParameters(includePrivateParameters: false);

                    string privateKey = PEMEncoding.GetString(privateKeyParam);
                    string publicKey  = SSHEncoding.GetString(publicKeyParam);

                    FileSystemHelpers.WriteAllText(_id_rsa, privateKey);
                    FileSystemHelpers.WriteAllText(_id_rsaPub, publicKey);

                    FileSystemHelpers.WriteAllText(_config, ConfigContent);
                    EnsureFilePermission();
                    return(publicKey);
                }
                finally
                {
                    if (rsa != null)
                    {
                        rsa.PersistKeyInCsp = false;
                        rsa.Dispose();
                    }
                }
            }
        }
        /// <summary>
        /// Instantiates a new key, the caller is responsible for disposing of this resource
        /// </summary>
        /// <param name="keyData">Delegate that procures key data on demand, cannot be null.</param>
        /// <returns>The algoriithm, cannot be null.</returns>
        /// <exception cref="CryptographicException">The encryption key could not be created, probably due to malformed key data.</exception>
        private static RSACryptoServiceProvider InstantiateAlgorithm(Func <string> keyData)
        {
            // omitting argument validation on private method, arguments validated by public methods
            // create an ssymmetric key
            RSACryptoServiceProvider algorithm = new RSACryptoServiceProvider();

            try
            {
                try
                {
                    // set key properties
                    algorithm.FromXmlString(keyData());

                    return(algorithm);
                }
                catch (XmlSyntaxException ex)
                {
                    // XmlSyntaxException not documented by FromXmlString but caugth during unit tests
                    throw new CryptographicException(ex.Message, ex);
                }
            }
            catch
            {
                if (algorithm != null)
                {
                    algorithm.Dispose();
                }

                throw;
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            lock (this)
            {
                if (!Disposed)
                {
                    Disposed = true;
                    GC.SuppressFinalize(this);

                    if (_cspEnc != null)
                    {
                        _cspEnc.Clear();
                        _cspEnc.Dispose();
                        _cspEnc = null;
                    }

                    if (_cspDec != null)
                    {
                        _cspDec.Clear();
                        _cspDec.Dispose();
                        _cspDec = null;
                    }
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Saves new public and private key pair, along with a salted-SHA-256 hash of the user password to protect these keys
        /// </summary>
        /// <param name="password">Choosen password</param>
        public static void SaveRSAParamaters(string password)
        {
            if (File.Exists("C:/EasySecurity/keys.bmu"))
            {
                File.Delete("C:/EasySecurity/keys.bmu");
            }
            FileStream file  = new FileStream("C:/EasySecurity/keys.bmu", FileMode.CreateNew, FileAccess.Write, FileShare.None);
            FileStream file2 = new FileStream("C:/EasySecurity/userPubKey.txt", FileMode.CreateNew, FileAccess.Write, FileShare.None);

            RSAParameters            keys, pub;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);

            keys = rsa.ExportParameters(true);
            pub  = rsa.ExportParameters(false);
            string xml          = SerializeRSAParams(keys);
            string xml2         = SerializeRSAParams(pub);
            string encryptedxml = AESThenHMAC.EncryptWithPassword(xml, password);

            using (StreamWriter sw = new StreamWriter(file))
            {
                string passhash = Convert.ToBase64String(Hashing.ComputeHash(password));
                sw.WriteLine("----START OF PASS HASH----");
                sw.WriteLine(passhash);
                sw.WriteLine("----END OF PASS HASH----");
                sw.WriteLine("----START KEYS----");
                sw.WriteLine(encryptedxml);
                sw.WriteLine("----END KEYS----");
            }
            using (StreamWriter sw = new StreamWriter(file2))
            {
                sw.WriteLine(xml2);
            }
            rsa.Dispose();
        }
        private void iCreateKeys_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (dlgSaveKeys.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                AppendLog("Creating keyfiles...");
                if (_PrivateKey != null)
                {
                    _PrivateKey.Dispose();
                }
                _PrivateKey   = new RSACryptoServiceProvider();
                eKeyFile.Text = "";
                try
                {
                    using (StreamWriter sw = new StreamWriter(dlgSaveKeys.FileName))
                    {
                        AppendLog("Writing private keyfile...");
                        sw.Write(_PrivateKey.ToXmlString(true));
                    }

                    string pubkeyfile = System.IO.Path.ChangeExtension(dlgSaveKeys.FileName, "pub");
                    using (StreamWriter sw = new StreamWriter(pubkeyfile))
                    {
                        AppendLog("Writing public keyfile...");
                        sw.Write(_PrivateKey.ToXmlString(false));
                    }
                    eKeyFile.Text = dlgSaveKeys.FileName;
                }
                catch
                {
                    AppendLog("Error creating keyfiles");
                }
            }
        }
Esempio n. 16
0
        public static bool VerifySignature(string digest, string hashal = "SHA1")
        {
            byte[] signedHashBytes = Convert.FromBase64String(digest);

            string docFileNew = @"G:\MyCode\CSharp\20170418\X509Encyption\testSendFile.txt";

            byte[] hashBytesNew;
            using (FileStream fs = new FileStream(docFileNew, FileMode.Open))
            {
                //计算报文的Hash值
                HashAlgorithm hashAlgorithm = HashAlgorithm.Create(hashal);
                hashBytesNew = hashAlgorithm.ComputeHash(fs);
                fs.Close();
            }

            //由证书公钥文件验证
            //初始化rsa算法
            string           pubKeyFile = @"G:\MyCode\CSharp\20170418\X509Encyption\publickey.cer";
            X509Certificate2 cerDecrypt = new X509Certificate2(pubKeyFile);
            bool             isOk       = false;

            using (RSACryptoServiceProvider rsaProviderDecrypt = (RSACryptoServiceProvider)cerDecrypt.PublicKey.Key)
            {
                //验证报文摘要和签名是否匹配
                RSAPKCS1SignatureDeformatter deFormatter = new RSAPKCS1SignatureDeformatter(rsaProviderDecrypt);
                deFormatter.SetHashAlgorithm(hashal);
                isOk = deFormatter.VerifySignature(hashBytesNew, signedHashBytes);
                rsaProviderDecrypt.Dispose();
            }

            Console.WriteLine("Verify result: " + isOk);
            return(isOk);
        }
Esempio n. 17
0
        public static string Sign(string message, string privateKey)
        {
            byte[] signedBytes = null;

            using (var rsaProvider = new RSACryptoServiceProvider())
            {
                byte[] originalData = new UTF8Encoding().GetBytes(message);

                try
                {
                    rsaProvider.FromXmlString(privateKey);
                    signedBytes = rsaProvider.SignData(originalData, CryptoConfig.MapNameToOID("SHA512"));
                }
                catch (Exception ex)
                {
                    Print(String.Format("[SIGN] Exception: {0}", ex.Message));
                }
                finally
                {
                    rsaProvider.PersistKeyInCsp = false;
                    rsaProvider.Dispose();
                }
            }

            return(Convert.ToBase64String(signedBytes));
        }
Esempio n. 18
0
 /// <summary>
 /// Returns the RSA key from the specified key container. Behavior if the key does not already exist is configured via argument.
 /// </summary>
 /// <param name="keystore">Specify which keystore the key should be loaded from.</param>
 /// <param name="keyContainerName">A string which uniquely identifies this encryption key among all other keys in the keystore.</param>
 /// <param name="createIfNoExist">If true, the key is created if it does not exist (can fail and throw exception).  If false, returns null if the key does not exist or is not accessible (not expected to throw).</param>
 /// <param name="publicOnly">If true, only the public key is returned. If false, the private key is returned.</param>
 /// <returns></returns>
 public static string GetKeyFromKeystore(Keystore keystore, string keyContainerName, bool createIfNoExist, bool publicOnly = true)
 {
     if (createIfNoExist)
     {
         using (RSACryptoServiceProvider rsa = GetRsaCspWithKeystore(keystore, keyContainerName))
         {
             return(Convert.ToBase64String(rsa.ExportCspBlob(!publicOnly)));
         }
     }
     else
     {
         CspParameters cspParams = CreateCspParameters(keystore, keyContainerName);
         cspParams.Flags |= CspProviderFlags.UseExistingKey;
         RSACryptoServiceProvider rsa;
         try
         {
             rsa = new RSACryptoServiceProvider(cspParams);
         }
         catch (CryptographicException)
         {
             return(null);                    // Thrown if the key does not exist, because of CspProviderFlags.UseExistingKey
         }
         try
         {
             rsa.PersistKeyInCsp = true;
             return(Convert.ToBase64String(rsa.ExportCspBlob(!publicOnly)));
         }
         finally
         {
             rsa.Dispose();
         }
     }
 }
Esempio n. 19
0
        public static bool Verify(string originalMessage, string signedMessage, string publicKey)
        {
            bool success = false;

            using (var rsaProvider = new RSACryptoServiceProvider())
            {
                byte[] bytesToVerify = new UTF8Encoding().GetBytes(originalMessage);
                byte[] signedBytes   = Convert.FromBase64String(signedMessage);
                try
                {
                    rsaProvider.FromXmlString(publicKey);
                    success = rsaProvider.VerifyData(bytesToVerify, CryptoConfig.MapNameToOID("SHA512"), signedBytes);
                }
                catch (Exception ex)
                {
                    Print(String.Format("[VERIFY] Exception: {0}", ex.Message));
                }
                finally
                {
                    rsaProvider.PersistKeyInCsp = false;
                    rsaProvider.Dispose();
                }
            }

            return(success);
        }
        public bool VerifyingSignature(string publicKey, string base64Signature, string base64Cypher, int bitSize = 2048, string hashType = "SHA1")
        {
            RSACryptoServiceProvider RSA = default;
            bool hasVerify = false;

            try
            {
                RSAParameters _key = publicKey.ToRsaParametersXML();

                byte[] _bytesCypher    = Convert.FromBase64String(base64Cypher);
                byte[] _bytesSignature = Convert.FromBase64String(base64Signature);

                RSA = new RSACryptoServiceProvider(bitSize);
                RSA.ImportParameters(_key);

                RSAPKCS1SignatureDeformatter RsaDeformatter = new RSAPKCS1SignatureDeformatter();
                RsaDeformatter.SetKey(RSA);
                RsaDeformatter.SetHashAlgorithm(hashType);

                hasVerify = RsaDeformatter.VerifySignature(_bytesCypher, _bytesSignature);
            }
            catch (Exception ex)
            {
                Console.WriteLine("VerifyingSignature FAIL: {0}", ex.Message);
            }
            finally
            {
                RSA.Dispose();
            }

            return(hasVerify);
        }
Esempio n. 21
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _rsaPrivate.Dispose();
     }
 }
Esempio n. 22
0
        public static bool Validate(string originalString, string encrytedString, string publicKey)
        {
            bool flag = false;
            RSACryptoServiceProvider key = new RSACryptoServiceProvider();

            try
            {
                key.FromXmlString(publicKey);
                RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key);
                deformatter.SetHashAlgorithm("SHA1");
                byte[] rgbSignature = Convert.FromBase64String(encrytedString);
                byte[] rgbHash      = new SHA1Managed().ComputeHash(Encoding.ASCII.GetBytes(originalString));
                if (deformatter.VerifySignature(rgbHash, rgbSignature))
                {
                    flag = true;
                }
            }
            catch
            {
            }
            finally
            {
                if (key != null)
                {
                    key.Dispose();
                }
            }
            return(flag);
        }
Esempio n. 23
0
        private static string RSADecrypt(string input)
        {
            var decryptProvider = new RSACryptoServiceProvider();
            var xmlPrivate      = Certificate.PrivateKey.ToXmlString(true);

            decryptProvider.FromXmlString(xmlPrivate);
            var inputBytes   = Convert.FromBase64String(input);
            var bufferSize   = decryptProvider.KeySize / 8;
            var buffer       = new byte[bufferSize];
            var inputStream  = new MemoryStream(inputBytes);
            var outputStream = new MemoryStream();

            while (true)
            {
                var readOnce = inputStream.Read(buffer, 0, bufferSize);
                if (readOnce <= 0)
                {
                    break;
                }
                var temp = new byte[readOnce];
                Array.Copy(buffer, 0, temp, 0, readOnce);
                var tempEncrypted = decryptProvider.Decrypt(temp, false);
                outputStream.Write(tempEncrypted, 0, tempEncrypted.Length);
            }
            inputStream.Dispose();
            var output = outputStream.ToArray();

            outputStream.Dispose();
            decryptProvider.Dispose();
            return(Encoding.UTF8.GetString(output));
        }
Esempio n. 24
0
        /// <summary>
        /// Disposes of internal components.
        /// </summary>
        /// <param name="disposing">true, if called from Dispose(), false, if invoked inside a finalizer.</param>
        protected override void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
#if NETSTANDARD1_4
                    if (_rsa != null && _disposeRsa)
                    {
                        _rsa.Dispose();
                    }
#else
                    if (_rsaCryptoServiceProvider != null && _disposeRsa)
                    {
                        _rsaCryptoServiceProvider.Dispose();
                    }

                    if (_rsaCryptoServiceProviderProxy != null)
                    {
                        _rsaCryptoServiceProviderProxy.Dispose();
                    }
#endif
                    _disposed = true;
                }
            }
        }
        public string Encrypt(string publicKey, string plainText, int bitSize = 2048)
        {
            RSACryptoServiceProvider RSA = default;
            string base64Cypher          = string.Empty;

            try
            {
                RSAParameters _key        = publicKey.ToRsaParametersXML();
                byte[]        _plainBytes = Encoding.Default.GetBytes(plainText);

                RSA = new RSACryptoServiceProvider(bitSize);
                RSA.ImportParameters(_key);

                byte[] _bytesCypher = RSA.Encrypt(_plainBytes, false);

                base64Cypher = Convert.ToBase64String(_bytesCypher);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Encrypt FAIL: {0}", ex.Message);
            }
            finally
            {
                RSA.Dispose();
            }

            return(base64Cypher);
        }
Esempio n. 26
0
        /// <summary>
        /// Verifies if a given signature is indeed generated using a given message and a public key
        /// </summary>
        /// <param name="RSAParams">Signer's public key</param>
        /// <param name="message">Plaintext Message</param>
        /// <param name="signature">Signature to be checked</param>
        /// <returns>boolean, true if the signature is valid</returns>
        public static bool VerifySignature(RSAParameters RSAParams, string message, string signature)
        {
            byte[] signedHashedValueWithSalt = Convert.FromBase64String(signature);
            byte[] signedHashedValue         = new byte[signedHashedValueWithSalt.Length - 15];
            byte[] saltBytes = new byte[15];

            for (int i = signedHashedValueWithSalt.Length - 15, j = 0; i < signedHashedValueWithSalt.Length; i++, j++)
            {
                saltBytes[j] = signedHashedValueWithSalt[i];
            }
            byte[] hashedValueWithSalt = Hashing.ComputeHash(message, saltBytes);
            byte[] hashedValue         = new byte[hashedValueWithSalt.Length - 15];
            for (int i = 0; i < hashedValueWithSalt.Length - 15; ++i)
            {
                hashedValue[i] = hashedValueWithSalt[i];
            }
            for (int i = 0; i < signedHashedValueWithSalt.Length - 15; ++i)
            {
                signedHashedValue[i] = signedHashedValueWithSalt[i];
            }
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(RSAParams);
            RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(rsa);

            RSADeformatter.SetHashAlgorithm("SHA256");
            bool x = RSADeformatter.VerifySignature(hashedValue, signedHashedValue);

            rsa.Dispose();
            return(x);
        }
Esempio n. 27
0
 public void Dispose()
 {
     if (algorithm != null)
     {
         algorithm.Dispose();
     }
 }
        public string Decrypt(string privateKey, string base64Cypher, int bitSize = 2048)
        {
            RSACryptoServiceProvider RSA = default;
            string plainText             = string.Empty;

            try
            {
                RSAParameters _key         = privateKey.ToRsaParametersXML();
                byte[]        _bytesCypher = Convert.FromBase64String(base64Cypher);

                RSA = new RSACryptoServiceProvider(bitSize);
                RSA.ImportParameters(_key);
                var _payload = RSA.Decrypt(_bytesCypher, false);

                plainText = Encoding.Default.GetString(_payload);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Decrypt FAIL: {0}", ex.Message);
            }
            finally
            {
                RSA.Dispose();
            }

            return(plainText);
        }
Esempio n. 29
0
        public byte[] SignWithCertificate(string message, X509Certificate2 certificate)
        {
            if (certificate.PublicKey.Key.KeySize < ClientAssertionCertificate.MinKeySizeInBits)
            {
                throw new ArgumentOutOfRangeException("rawData",
                                                      string.Format(CultureInfo.InvariantCulture, AdalErrorMessage.CertificateKeySizeTooSmallTemplate, ClientAssertionCertificate.MinKeySizeInBits));
            }

            X509AsymmetricSecurityKey x509Key = new X509AsymmetricSecurityKey(certificate);
            RSACryptoServiceProvider  rsa     = x509Key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSACryptoServiceProvider;

            RSACryptoServiceProvider newRsa = null;

            try
            {
                newRsa = GetCryptoProviderForSha256(rsa);
                using (SHA256Cng sha = new SHA256Cng())
                {
                    return(newRsa.SignData(Encoding.UTF8.GetBytes(message), sha));
                }
            }
            finally
            {
                if (newRsa != null && !ReferenceEquals(rsa, newRsa))
                {
                    newRsa.Dispose();
                }
            }
        }
        public string GeneratingSignature(string privateKey, string base64Cypher, int bitSize = 2048, string hashType = "SHA1")
        {
            RSACryptoServiceProvider RSA = default;
            string base64Signature       = string.Empty;

            try
            {
                RSAParameters _key         = privateKey.ToRsaParametersXML();
                byte[]        _bytesCypher = Convert.FromBase64String(base64Cypher);

                RSA = new RSACryptoServiceProvider(bitSize);
                RSA.ImportParameters(_key);

                RSAPKCS1SignatureFormatter RsaFormatter = new RSAPKCS1SignatureFormatter();
                RsaFormatter.SetKey(RSA);
                RsaFormatter.SetHashAlgorithm(hashType);

                byte[] bytesSignature = RsaFormatter.CreateSignature(_bytesCypher);

                base64Signature = Convert.ToBase64String(bytesSignature);
            }
            catch (Exception ex)
            {
                Console.WriteLine("GeneratingSignature FAIL: {0}", ex.Message);
            }
            finally
            {
                RSA.Dispose();
            }

            return(base64Signature);
        }