Exemplo n.º 1
0
        private static void RSA_Test()
        {
            //RSAEncryption GenPrivateKeyc = new RSAEncryption(4096, true);
            //GenPrivateKeyc.GeneratePrivateKey();
            //string PrivateKey = GenPrivateKeyc.PrivateKey;

            int    BitSize          = 4096;
            string PreGenPrivateKey = @"<RSAKeyValue>
                                            <Modulus>1ClYJTeXDkbppKjvJqC3xf+E4P4eVa4lwvFmdGTsqDdJoT+RMvLg/WkrWsCEASmxaj3ohlg1kBhSv2ZXuZlH90Roba5EWOxD1EQUDjk0e711ga0YVwZF5UUo9yx+Lo1QR3ErmeNMOkJDa0IZVnmuILgdaTFBdBm2ZYdJVnpeB+BIycNT0vAoqtwdDZXySjAzfl6nL6WsNw/XqJMIDuFcIt8hv6vghFtpiQXeWEsuZq3DQPlCu0oJDYuoAaRU5KxOIakbTzpTS11eBx+w1PDgd+VCAEVbx71sqjSFsAOEvmm4A0lRBRnQuJOdoGLNFoSePDGP9J88KfIfosMtAqFDUX2/8EsAc6B3QnpQ0un5vC2Au0xUDY0fwsKtN9yvFQPw10eRXEV+Smz4pBH+4gOEKi0RxNt3chKa0qqGG9I/CqL1/PPEtvN31Bjxc4H2vAyW3XMRNs7o9pktimaRNpwZ6sbBDi2eNY6Ty5ff7jHv0uy9DRQsreTewhXvZK6M8OcBUxLp1tkzi9zTBKTPTMXAuUF1oWDJktWDBuGnxbZcTfTvJ0X3zS8/mXdsUHsgV5vcGeT+2hZLQnskrwlbxt4QjEHSl0hgWM9i5Yhd+ltlg/9URvZdnkh5pKoShJR4OWNSBsI3kwRzwPHAKag8J4TSFIgZXCkSvtTlsM6v44f8pNU=</Modulus>
                                            <Exponent>AQAB</Exponent>
                                            <P>3cBHXk4SpnPWskCpGfJbW5u5XO3q1srmsW9XCDwo4HWezMaIjznjcwd46W50nUAkfS6zt91Ez7xPzWg0+kTrLwJEnAwLb5rYk7aGk29G8Vz0DW6rBnzT8hIxgdAnRUk/Htxkee1k8aHdL5kDUkfBDX1sRxi20A8bNHG039oq0joxkQKO8nrctIxHLiTtPXUH1R3AZ4+35keONp4iRBvKudPlZFOGHw4JmtW/mm6opAHOMZJyMpz6LFbQuQ6FAb7YkP63e0qELgP5PgnFgz/k2vA5gqjCfLdHNqh4o9iTuEDh8JPY4ADu3JkaJXdp3NPn2vsZHW3IJQON4WnjfFB3mQ==</P>
                                            <Q>9O3oLQiJXD3O9aQnyUpI4MQjJ2JacXCbNmcS8Kv+U1eYpQqQK1PwJCl2jJ8KgP7Hy8H3kuUxMDFv1fuWO1UFC4fzrODx5W6Vo/ZUhud0l8q8OfQKq4YOmpHR/eFAj9Bo3bGNXnjBWCV0RmxA0cAQ/y/bAdBTOQntBQUNLqfstTu6fAMor6fzYpzic1olUlOQf9wCOHNE/JSgjMgaXdpYLxLsCSexN/ut8T8fxBSX3NeSUlLbj2CWtzEGsKwP7rwIfnZ9UUKdBCaGAj2UIi5wO2TBnEb0EhjRcOa15YThZTp+4U6LQNVJC9nK26yhBrWH2ZEft5a0nPgJLIabT90snQ==</Q>
                                            <DP>yVS/92FPEY1uylxmq8YdKClUvIjOhMGnfkWmcTWdr11bFnTSm6dlWJTaNKYyfms0NevnA/KDfVBt7ALGxss39HBMtplA8M1YAZTgzo9ji9RnSKLH6JYBIHFgPYotfXypMG3NU94znibl2UdFerjnEEZlvo8zu+dbPdxW6j78Te7D/fKisojWRZ5vKfgg5YGR4O6oN96Giy9AcVpVphzNjLZUOSiURzHJiqiy05XQy0dQXDWoNUfM4+DWlI4YOKN7oPmCwQ/Avr6g1rCsgSPLtvQQYw6xteX5ZCjFj40dYVaXTIQPjiGKvQLMeGPY28QRaAI+pTd9Vg3KDXTEM6QjUQ==</DP>
                                            <DQ>ENQz6rw2a+8XREuGLE99WGxBmhgo7Lh3AbLtWzoGHIXdSCHErCV1T5bFvX3EA/79jWODdkVnLs+GxqYluWfrE9LAjHVcSY5im8R2JFrM6Q0WB8lb3lM0t6wjSJVskTUZr3neo8oaRss0BQ61GXRf9pi8LJC61yV2cqzZLgZ9viofcxvodMFOeM0cxh5AiDqTqCVexbAt4kj4CxRIs4AoJPvg2fQvOhCB8ByNOzTLBnKNbDijO2PAl0+4DPWVlqq2zrGnhKjWDw3ykT7X6c1VCs+ueeVqKcAoy+AeSWnq7sCpLSPvb4H4JedOB/ABlGturSVKj5u8RzjHsJaDH2asBQ==</DQ>
                                            <InverseQ>YTR07LDfg26rZt6gaVlxYioX/UhbjoIPnH5Gd1ZcaGBfnkzaXatHv6YDA0wuj2VmAelmdTMD21H2TgHvvRRnpsVix/+uphV71QCKPBooJke/Dba2YxRYz5UYWid/VDvtFddzw3NdQF8mzqhr/FpdrZWeLiuDHlZLmQxqNWRlpFX1w1CBMZBuv8Z2cLf//sr/rZ3bY9F6EXqLoMIOnp+Gv069pfp7xpm5Ymcz3ixmCXY0BiwHxfbw2YAQus1Q3s+GSqtVU6IYFe6VbwdcRR45WdFEMF2I6mboehN2pTAUyEkvYIYra/pfjkXrTKPTvyucR1BmObKYqg9jKIXLKH3IRA==</InverseQ>
                                            <D>Ig0isxJ5gZabEEz22T3JUROCKbRPfRPuxpuFBKBgJV1+SU2RCdrWhoWXKkEkzqT47yLRi6JjsmVc/pA3+zdhSAvoMNZb7OO6vTpR97hxtnyBfBcihXEhzbrsaMNw2xreLCE7TL8g8GbLOE9LDsiHzIOQYN5BcZdg4Wm1uRX5uoziUdOyQ/Q8qrOaTCBpW0PiN+GMNscB3XKC+/DhRbYg2g3y9jbpWYTsaswQ1B347AzufiKjdbjbvBtSkzTjVTJcdeWU1wH29W0eVslc0ch5VnTqw21eXjAGXUkBve7Kot8H5CsjwExU5hL3JRNGdFtDpEiWIL5f4yGTt0VZF4d3bLV5q3R3l34ghdt171tShSGz013J0Z5Q/iHBgRkSR//0f8ZITe7iSkhkfZXbx7Ihi13ufBJwIdcDhT7LYKHLk/H3fgCnkAigEmT14/oZwYtW0CqnHtzbBpO+jPLIMAFbhty6GE2LKlQx91YwqMODnYRYs7e8evOeiAadLAjAxQOjNZ1J8EKfwmtmqBqfiUA5O1uJRAavuMhRw/UTMqOeBEGxosmUsV4aw9BIYASmJ9uzc7pkZdPwBlVdnHPn5MILmAcE2vYhv9bRgwUF8LRT4GkP9IW2g48WabzLhIdSu/azjT2GBnkMwz5FcwPYiFvQc3fquqVWhn9PqGN5tHq6LhE=</D>
                                        </RSAKeyValue>";

            RSAEncryption A_Rsa = new RSAEncryption(BitSize, "", PreGenPrivateKey, true);

            //When generating, only the modulus and Exponent should be made public, nothing else
            string PublicKeyFromA = A_Rsa.GeneratePublicKey();

            string TestData = "Helllo, This is A, let's hope this message arrived well";

            byte[] EncryptedData = A_Rsa.Encrypt(ASCIIEncoding.ASCII.GetBytes(TestData), 0, TestData.Length);
            byte[] SignedData    = A_Rsa.SignData(ASCIIEncoding.ASCII.GetBytes(TestData));

            RSAEncryption B_Rsa = new RSAEncryption(BitSize, A_Rsa.PublicParameters.Value.Modulus, A_Rsa.PublicParameters.Value.Exponent, true);

            byte[] DecryptedData = B_Rsa.Decrypt(EncryptedData, 0, EncryptedData.Length);
        }
Exemplo n.º 2
0
    public void ExecuteDecrypt()
    {
        if (string.IsNullOrEmpty(privateKeyText.text))
        {
            return;
        }
        string encryptedText = textInput.text;
        string plane         = RSAEncryption.Decrypt(encryptedText, publicAndPrivateKeyValuePair.Value);

        resultText.text = plane;
    }
    private bool ValidateIncomingVariables(HttpRequest request)
    {
        bool isGenuine = false;

        // Step 1 -Read the follwoing from the hidden values
        //1 -Request Encrypted Session Key
        //2- Request Encrypted Data
        //3- Request IV
        //4- Request Encrypted Data`s Hash
        var requestEncryptedSessionKeyBytes = Convert.FromBase64String(Request.Form["hdEncryptedSessionKey"]);
        var requestEncryptedDataBytes       = Convert.FromBase64String(Request.Form["hdEncryptedData"]);
        var requestIvBytes         = Convert.FromBase64String(Request.Form["hdIv"]);
        var requestHashedDataBytes = Convert.FromBase64String(Request.Form["hdHashedData"]);

        // Step 2 -Decrypt the request session key using the receiver's private key.
        var rsa = new RSAEncryption();
        var requestDecryptedSessionKey = rsa.Decrypt(Server.MapPath("~/Keys/privatekey.xml"), requestEncryptedSessionKeyBytes);

        // Step 3-Building the string from the incoming request's actual data
        var actualData = Utils.BuildString(
            Request.Form["ModifiedFirstVariable"],
            Request.Form["ModifiedSecondVariable"],
            Request.Form["ModifiedThirdVariable"],
            Request.Form["ModifiedForthVariable"],
            Request.Form["ModifiedFifthVariable"],
            Request.Form["ModifiedSixthVariable"],
            Request.Form["ModifiedSeventhVariable"],
            Request.Form["ModifiedEighthVariable"]);

        // Step 4-Encrypt the incoming request's actual data using the decrypted session key and the iv.
        AESEncryption aes = new AESEncryption();
        var           actualEncryptedData = aes.Enrypt(Encoding.UTF8.GetBytes(actualData), requestDecryptedSessionKey, requestIvBytes);
        var           actualDataHash      = HashGenerator.ComputeHmacSha256((actualEncryptedData), requestDecryptedSessionKey);

        // Step 5-Compare the actual hash with received hash(from request)
        var isActualDataHashMatch = Compare(requestHashedDataBytes, actualDataHash);

        // Step 6-Calculate the hash for the encrypted data
        var requestEncryptedDataHash        = HashGenerator.ComputeHmacSha256((requestEncryptedDataBytes), requestDecryptedSessionKey);
        var isRequestEncryptedDataHashMatch = Compare(actualDataHash, requestEncryptedDataHash);

        if (isActualDataHashMatch && isRequestEncryptedDataHashMatch)
        {
            //Step 7 -Decrypt the data using the decrypted session key and the iv. - out of scope
            //var decryptedDataBytes = aes.Decrypt(encryptedDataBytes, decryptedSessionKey, ivBytes);
            //var plainData =Encoding.Default.GetString(decryptedDataBytes);
            isGenuine = true;
        }
        return(isGenuine);
    }
Exemplo n.º 4
0
        public bool Login(string login, string password)
        {
            DataConnection.DefaultSettings = new MySettings(_test);

            using var db = new DbDoctor();
            var user = GetByLogin(login);

            if (user != null && password == RSAEncryption.Decrypt(user.Password))
            {
                return(true);
            }

            return(false);
        }
            /// <summary>
            /// ValidateKey method implmentation
            /// </summary>
            public override bool ValidateKey(string upn)
            {
                if (string.IsNullOrEmpty(upn))
                {
                    return(false);
                }
                string lupn = upn.ToLower();
                string key  = ReadKey(lupn);

                if (string.IsNullOrEmpty(key))
                {
                    return(false);
                }
                if (HasStorageInfos(key))
                {
                    using (var prov = new RSAEncryption(_xorsecret))
                    {
                        byte[] crypted = StripStorageInfos(key);
                        if (crypted == null)
                        {
                            return(false);
                        }

                        prov.Certificate = KeysStorage.GetUserCertificate(lupn, true);
                        byte[] cleared = prov.Decrypt(crypted, lupn);

                        if (cleared == null)
                        {
                            return(false); // Key corrupted
                        }
                        if (prov.CheckSum == null)
                        {
                            return(false); // Key corrupted
                        }
                        if (prov.CheckSum.SequenceEqual(CheckSumEncoding.CheckSum(lupn)))
                        {
                            return(true);  // OK RSA
                        }
                        else
                        {
                            return(false); // Key corrupted
                        }
                    }
                }
                else
                {
                    return(false);
                }
            }
Exemplo n.º 6
0
        //保存文件路径
        /// <summary>
        /// 获取客户端保存的所有用户
        /// </summary>
        private void GetClientUsers()
        {
            try
            {
                string FileInfo = string.Empty;
                if (File.Exists(FilePath))
                {
                    //打开流进行读取
                    using (FileStream fs = File.OpenRead(FilePath))
                    {
                        //创建一个byte数组以读取数据
                        byte[] arr = new byte[fs.Length];
                        //继续读完文件中的所有数据
                        while (fs.Read(arr, 0, arr.Length) > 0)
                        {
                            FileInfo += Encoding.UTF8.GetString(arr);
                        }
                    }
                    FileInfo = FileInfo.Replace('\0', ' ').Trim();
                    if (!string.IsNullOrEmpty(FileInfo))
                    {
                        string fileinfo = RSAEncryption.Decrypt(FileInfo);

                        string[] values = fileinfo.Split(';');
                        foreach (var item in values)
                        {
                            UserInfoData.Add(item);
                        }
                    }
                }
                string user = IniHelper.ProfileReadValue("ServerUser", "user", IniHelper.defaultUserData);
                if (UserInfoData.Count > 0)
                {
                    if (UserInfoData.Contains(user))
                    {
                        UserInfoSelectItem = user;
                        IsSaveUserName     = true;
                    }
                    else
                    {
                        UserInfoSelectItem = UserInfoData[0];
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Info(ex.Message);
            }
        }
Exemplo n.º 7
0
        private ApiToken GetToken(string authHeader)
        {
            if (!string.IsNullOrEmpty(authHeader))
            {
                string tokenText = RSAEncryption.Decrypt(authHeader);

                ApiToken token;
                if (ApiToken.TryParse(tokenText, out token))
                {
                    return(token);
                }
            }

            return(null);
        }
        public LoginViewModel()
        {
            UserNameTemp = IniHelper.ProfileReadValue("User", "Username", IniHelper.configpath);
            UserName     = UserNameTemp;
            string pwd = IniHelper.ProfileReadValue("User", "Password", IniHelper.configpath);

            if (!string.IsNullOrEmpty(pwd))
            {
                Password = RSAEncryption.Decrypt(pwd);
            }
            Passwordtemp = Password;
            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
            {
                IsSave = true;
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 取配置节点
        /// </summary>
        /// <param name="key"></param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static string GetEncryptConfig(string key, string defaultValue = "")
        {
            var str = ConfigurationManager.AppSettings[key];

            if (str.IsEmpty())
            {
                return(defaultValue);
            }
            if (str.Contains(EncryptSplit) && str.Length > 100)
            {
                return(RSAEncryption.Decrypt(EncryptKey, str.Substring(str.IndexOf(EncryptSplit) + EncryptSplit.Length)));
            }
            else
            {
                return(str);
            }
        }
Exemplo n.º 10
0
 public HttpResponseMessage Register(RegisterInfo registerInfo)
 {
     if (ModelState.IsValid)
     {
         if (!(UserService.Instance.GetAll().Select(x => x.Email).Contains(registerInfo.Email)))
         {
             RSAEncryption encryption = new RSAEncryption();
             registerInfo.Pwd = encryption.Decrypt(Encoding.ASCII.GetBytes(registerInfo.Pwd));
             UserService.Instance.Create(registerInfo.RegisterInfoToUser());
             return(new HttpResponseMessage(HttpStatusCode.OK));
         }
         else
         {
             return(new HttpResponseMessage(HttpStatusCode.Conflict));
         }
     }
     return(new HttpResponseMessage(HttpStatusCode.BadRequest));
 }
            /// <summary>
            /// ProbeKey method implmentation
            /// </summary>
            public override byte[] ProbeKey(string upn)
            {
                if (string.IsNullOrEmpty(upn))
                {
                    return(null);
                }
                string lupn = upn.ToLower();
                string key  = ReadKey(lupn);

                if (string.IsNullOrEmpty(key))
                {
                    return(null);
                }

                byte[] probed = null;
                using (var prov = new RSAEncryption(_xorsecret))
                {
                    byte[] crypted = StripStorageInfos(key);
                    if (crypted == null)
                    {
                        return(null);
                    }

                    prov.Certificate = KeysStorage.GetUserCertificate(lupn, true);
                    probed           = prov.Decrypt(crypted, lupn);
                    if (probed == null)
                    {
                        return(null);
                    }
                }
                if (probed.Length > MAX_PROBE_LEN)
                {
                    byte[] buffer = new byte[MAX_PROBE_LEN];
                    Buffer.BlockCopy(probed, 0, buffer, 0, MAX_PROBE_LEN);
                    return(buffer);
                }
                else
                {
                    return(probed);
                }
            }
Exemplo n.º 12
0
        /// <summary>
        /// Decrypt:  Asymmetrical decryption of a string using private RSA key -
        /// INTERNAL ONLY, NEVER EXPOSE THIS METHOD EXTERNAL TO THIS ASSEMBLY EXCEPT BY PENALTY OF PROGRAMMER FLOGGING
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Decrypt(string data)
        {
            try
            {
                if (EncryptionEnabled)
                {
                    if (string.IsNullOrEmpty(_private))
                    {
                        return("You need to set the private key in the configuration for decryption to work correctly. [Missing AppSetting.RSA_PRIVATE_KEY]");
                    }

                    return(RSAEncryption.Decrypt(data, _private));
                }
                return(data);
            }
            catch (Exception exception)
            {
                // ExceptionHelper.Capture(exception);
                return("Decryption failed. " + exception.Message);
            }
        }
            /// <summary>
            /// EncodedKey method implementation
            /// </summary>
            public override string EncodedKey(string upn)
            {
                if (string.IsNullOrEmpty(upn))
                {
                    return(null);
                }
                string lupn = upn.ToLower();
                string key  = ReadKey(lupn);

                if (string.IsNullOrEmpty(key))
                {
                    return(null);
                }

                byte[] cleared = null;
                using (var prov = new RSAEncryption(_xorsecret, _certificatethumbprint))
                {
                    byte[] crypted = StripStorageInfos(key);
                    if (crypted == null)
                    {
                        return(null);
                    }

                    cleared = prov.Decrypt(crypted, lupn);
                    if (cleared == null)
                    {
                        return(null);
                    }
                }
                if (cleared.Length > MAX_PROBE_LEN)
                {
                    byte[] buffer = new byte[MAX_PROBE_LEN];
                    Buffer.BlockCopy(cleared, 0, buffer, 0, MAX_PROBE_LEN);
                    return(Base32.Encode(buffer));
                }
                else
                {
                    return(Base32.Encode(cleared));
                }
            }
Exemplo n.º 14
0
        public AuthenticateResult Authenticate(LoginModel logonModel)
        {
            if (logonModel != null)
            {
                User user = null;
                if (!string.IsNullOrEmpty(logonModel.Token))
                {
                    string tokenText = RSAEncryption.Decrypt(logonModel.Token);

                    ApiToken token;
                    if (ApiToken.TryParse(tokenText, out token))
                    {
                        if (token.AuthenticationTime > DateTime.Today.AddDays(-10))
                        {
                            user = _userRepository.GetUser(token.UserId);
                        }
                    }
                }
                else
                {
                    user = _userRepository.GetUser(logonModel.Username);
                    if (user != null)
                    {
                        if (user.Password != logonModel.Password)
                        {
                            return(new AuthenticateResult(false, null)
                            {
                                Message = "invalid password"
                            });
                        }
                    }
                }

                if (user != null)
                {
                    ApiToken token = new ApiToken()
                    {
                        UserId   = user.Id,
                        UserName = user.Username,
                        Timezone = user.Timezone,
                        Language = user.Language,
                        //Roles = SerializeRoles(user.StaffAtBusinesses),
                        AuthenticationTime = DateTime.Now
                    };

                    string encryptedToken = RSAEncryption.Encrypt(token.ToString());
                    user.Password = null; // clear password
                    AuthenticateResult result = new AuthenticateResult(true, encryptedToken)
                    {
                        User = new UserDTO(user)
                    };

                    return(result);
                }
            }

            return(new AuthenticateResult(false, null)
            {
                Message = "invalid login"
            });
        }
Exemplo n.º 15
0
 /// <summary>
 /// 字符串 RSA 解密
 /// </summary>
 /// <param name="text">需要解密的文本</param>
 /// <param name="privateKey">私钥</param>
 /// <returns></returns>
 public static string ToRSADecrypt(this string text, string privateKey)
 {
     return(RSAEncryption.Decrypt(text, privateKey));
 }