Ejemplo n.º 1
0
        public async Task <string> GenerateJwtTokenAsync(string username, string password)
        {
            if (!_membershipProvider.VerifyUserPassword(username, password))
            {
                return("Wrong access");
            }

            var claims = _membershipProvider.GetUserClaims(username);

            var publicAndPrivateKey = await _rsaProvider.GetPrivateAndPublicKeyAsync();

            RSACryptoServiceProvider PrivateKey = new RSACryptoServiceProvider(2048);

            RSAKeyExtensions.FromXmlString(PrivateKey, publicAndPrivateKey.priv);
            IdentityModelEventSource.ShowPII = true;
            JwtSecurityToken jwtToken = new JwtSecurityToken
                                        (
                issuer: "http://issuer.com",
                audience: "http://mysite.com",
                claims: claims,
                signingCredentials: new SigningCredentials(new RsaSecurityKey(PrivateKey), SecurityAlgorithms.RsaSha256Signature),
                expires: DateTime.Now.AddDays(30)
                                        );

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            string tokenString = tokenHandler.WriteToken(jwtToken);

            await SaveToken(tokenString);

            return(tokenString);
        }
Ejemplo n.º 2
0
        public async Task <bool> ValidateTokenAsync(string TokenString)
        {
            Boolean result = false;

            try
            {
                JwtSecurityToken         securityToken        = new JwtSecurityToken(TokenString);
                JwtSecurityTokenHandler  securityTokenHandler = new JwtSecurityTokenHandler();
                RSACryptoServiceProvider publicAndPrivate     = new RSACryptoServiceProvider(2048);

                var publicAndPrivateKey = await _rsaProvider.GetPrivateAndPublicKeyAsync();

                RSAKeyExtensions.FromXmlString(publicAndPrivate, publicAndPrivateKey.pub);

                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {
                    ValidIssuer      = "http://issuer.com",
                    ValidAudience    = "http://mysite.com",
                    IssuerSigningKey = new RsaSecurityKey(publicAndPrivate)
                };

                ClaimsPrincipal claimsPrincipal = securityTokenHandler.ValidateToken(TokenString, validationParameters, out SecurityToken _secToken);

                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }

            return(result);
        }
Ejemplo n.º 3
0
        private static void CreateInitFile(String filePath)
        {
            RSA    rsa       = RSA.Create();
            string xmlString = RSAKeyExtensions.ToXmlString(rsa, true);

            File.WriteAllText(filePath, xmlString);
        }
Ejemplo n.º 4
0
        private RSAKeysPair GenerateKeys(RSAKeySize rsaKeySize)
        {
            int keySize = (int)rsaKeySize;

            if (keySize % 2 != 0 || keySize < 512)
            {
                throw new Exception("Key should be multiple of two and greater than 512.");
            }

            var rsaKeysTypes = new RSAKeysPair();

            using (var provider = new RSACryptoServiceProvider(keySize))
            {
                var publicKey  = RSAKeyExtensions.ToXmlString(provider, false);
                var privateKey = RSAKeyExtensions.ToXmlString(provider, true);

                var publicKeyWithSize  = IncludeKeyInEncryptionString(publicKey, keySize);
                var privateKeyWithSize = IncludeKeyInEncryptionString(privateKey, keySize);

                rsaKeysTypes.PublicKey  = publicKeyWithSize;
                rsaKeysTypes.PrivateKey = privateKeyWithSize;
            }

            return(rsaKeysTypes);
        }
Ejemplo n.º 5
0
        private byte[] Encrypt(byte[] data, int keySize, string publicKeyXml)
        {
            if (data == null || data.Length == 0)
            {
                throw new ArgumentException("Data are empty", "data");
            }

            int maxLength = GetMaxDataLength(keySize);

            if (data.Length > maxLength)
            {
                throw new ArgumentException(string.Format("Maximum data length is {0}", maxLength), "data");
            }

            if (!IsKeySizeValid(keySize))
            {
                throw new ArgumentException("Key size is not valid", "keySize");
            }

            if (string.IsNullOrEmpty(publicKeyXml))
            {
                throw new ArgumentException("Key is null or empty", "publicKeyXml");
            }

            using (var provider = new RSACryptoServiceProvider(keySize))
            {
                RSAKeyExtensions.FromXmlString(provider, publicKeyXml);
                return(provider.Encrypt(data, optimalAsymmetricEncryptionPadding));
            }
        }
Ejemplo n.º 6
0
 public Product()
 {
     _key            = RSA.Create();
     _id             = Guid.NewGuid();
     _issuedLicenses = new ObservableCollection <License>();
     _publicKey      = RSAKeyExtensions.ToXmlString(_key, false);
     _privateKey     = RSAKeyExtensions.ToXmlString(_key, true);
 }
Ejemplo n.º 7
0
        private (String priv, String pub) CreatePrivateAndPublicKey()
        {
            using (var rsa = new RSACryptoServiceProvider(2048))
            {
                try
                {
                    rsa.ExportParameters(false);
                    string pubKey = RSAKeyExtensions.ToXmlString(rsa, false);
                    rsa.ExportParameters(true);
                    string privKey = RSAKeyExtensions.ToXmlString(rsa, true);

                    return(privKey, pubKey);
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>Create (if not exists) or load private key for licensing. Should not be used by client software</summary>
        /// <example>
        /// <code>
        /// SimpleLicense myLicenseProvider = SimpleLicense.InitFile("main.key");
        /// </code>
        /// </example>
        /// <param name="keyFilePath">File path to the key file. If not exists, a new key file will be created.</param>
        public static SimpleLicense Init(String keyFilePath)
        {
            try
            {
                SimpleLicense license   = null;
                string        xmlString = String.Empty;

                if (!File.Exists(keyFilePath))
                {
                    CreateInitFile(keyFilePath);
                }

                xmlString = File.ReadAllText(keyFilePath);
                license   = new SimpleLicense();
                RSAKeyExtensions.FromXmlString(license._rsa, xmlString);

                return(license);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Ejemplo n.º 9
0
        private byte[] Decrypt(byte[] data, int keySize, string publicAndPrivateKeyXml)
        {
            if (data == null || data.Length == 0)
            {
                throw new ArgumentException("Data are empty", "data");
            }

            if (!IsKeySizeValid(keySize))
            {
                throw new ArgumentException("Key size is not valid", "keySize");
            }

            if (string.IsNullOrEmpty(publicAndPrivateKeyXml))
            {
                throw new ArgumentException("Key is null or empty", "publicAndPrivateKeyXml");
            }

            using (var provider = new RSACryptoServiceProvider(keySize))
            {
                RSAKeyExtensions.FromXmlString(provider, publicAndPrivateKeyXml);
                return(provider.Decrypt(data, optimalAsymmetricEncryptionPadding));
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Login to sugang.inha.ac.kr
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static SugangSession Create(string id, string pwd)
        {
            //
            //  Reuqest RSA Public Key
            //

            string public_key;

            using (var client = new WebClient())
                public_key = client.DownloadString("https://sugang.inha.ac.kr/ITISWebCommon/xml/PublicKey.xml");

            var rsa = new RSACryptoServiceProvider();

            RSAKeyExtensions.FromXmlString(rsa, public_key);

            var ide  = encrpyt(rsa, id);
            var pwde = encrpyt(rsa, pwd);

            //
            //  Get Parameters from Menu.aspx
            //

            string menu_aspx;

            using (var client = new WebClient())
                menu_aspx = client.DownloadString("https://sugang.inha.ac.kr/sugang/Menu.aspx");

            var document = new HtmlDocument();

            document.LoadHtml(menu_aspx);
            var root_node = document.DocumentNode;
            var form      = root_node.SelectSingleNode("//form[@name='form1']");

            var param = new Dictionary <string, string>();

            foreach (var input in form.SelectNodes(".//input"))
            {
                param.Add(input.GetAttributeValue("name", ""), input.GetAttributeValue("value", ""));
            }
            param["hhdencId"] = ide;
            param["hhdencPw"] = pwde;

            param.Add("__EVENTTARGET", "ibtnLogin");
            param.Add("__EVENTARGUMENT", "");

            //
            //  Request Session Cookie
            //

            var request = (HttpWebRequest)WebRequest.Create("https://sugang.inha.ac.kr/sugang/Menu.aspx");

            pass_common(ref request);

            request.Method = "POST";
            request.Headers.Add("Origin", "https://sugang.inha.ac.kr");
            request.Headers.Add(HttpRequestHeader.Cookie, "this.GetLangCode=");

            var xx = request.Headers.ToString();

            var request_stream = new StreamWriter(request.GetRequestStream());
            var query          = string.Join("&", param.ToList().Select(x => $"{x.Key}={Uri.EscapeDataString(x.Value)}"));

            request_stream.Write(query);
            request_stream.Close();

            //
            //  Create Session
            //

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                var cookies = response.Cookies;

                // Fake response
                var res = new StreamReader(response.GetResponseStream()).ReadToEnd();

                if (cookies.Count == 0 || cookies[0].Name != "ITISSugangHome")
                {
                    return(ErrorSession);
                }

                var ss = new SugangSession {
                    Cookies = cookies
                };

                try
                {
                    ss.create_itissugang_session();
                    ss.IsValidITISSugangCookie = true;
                }
                catch { }

                return(ss);
            }
        }