public static byte[] ComputeCombinedKey(byte[] requestorEntropy, byte[] issuerEntropy, int keySizeInBits)
 {
     if (requestorEntropy == null)
     {
         throw new ArgumentNullException("requestorEntropy");
     }
     if (issuerEntropy == null)
     {
         throw new ArgumentNullException("issuerEntropy");
     }
     int num = ValidateKeySizeInBytes(keySizeInBits);
     byte[] array = new byte[num];
     
     using (KeyedHashAlgorithm algorithm = new HMACSHA1())
     {
         algorithm.Key = requestorEntropy;
         byte[] buffer = issuerEntropy;
         byte[] buffer3 = new byte[(algorithm.HashSize / 8) + buffer.Length];
         byte[] buffer4 = null;
         try
         {
             try
             {
                 int num2 = 0;
                 while (num2 < num)
                 {
                     algorithm.Initialize();
                     buffer = algorithm.ComputeHash(buffer);
                     buffer.CopyTo(buffer3, 0);
                     issuerEntropy.CopyTo(buffer3, buffer.Length);
                     algorithm.Initialize();
                     buffer4 = algorithm.ComputeHash(buffer3);
                     for (int i = 0; i < buffer4.Length; i++)
                     {
                         if (num2 >= num)
                         {
                             continue;
                         }
                         array[num2++] = buffer4[i];
                     }
                 }
             }
             catch
             {
                 Array.Clear(array, 0, array.Length);
                 throw;
             }
             return array;
         }
         finally
         {
             if (buffer4 != null)
             {
                 Array.Clear(buffer4, 0, buffer4.Length);
             }
             Array.Clear(buffer3, 0, buffer3.Length);
             algorithm.Clear();
         }
     }
 }
Пример #2
0
        public static Account Decrypt(Stream inputStream, ConsoleType consoleType)
        {
            var hmac = new HMACSHA1(consoleType == ConsoleType.Retail ? RetailKey : DevkitKey);
            var hash = inputStream.ReadBytes(16);
            var rc4Key = hmac.ComputeHash(hash);
            Array.Resize(ref rc4Key, 16);

            var rest = inputStream.ReadBytes(388);
            var body = RC4.Decrypt(rc4Key, rest);

            var compareBuffer = hmac.ComputeHash(body);
            if (!memcmp(hash, compareBuffer, 16))
                throw new InvalidDataException("Keys do not match");
            return ModelFactory.GetModel<Account>(body.Skip(8).ToArray());
        }
 //EncodePassword:Encrypts, Hashes, or leaves the password clear based on the PasswordFormat.
 public string EncodePassword(string password)
 {
     var encodedPassword = password;
     var hash = new HMACSHA1 { Key = HexToByte(_machineKey.ValidationKey) };
     encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
     return encodedPassword;
 }
        internal static string GetOAuthHeader(Dictionary<string, string> parameters, string url, string comsumeSercret, string tokenSecret)
        {
            parameters = parameters.OrderBy(x => x.Key).ToDictionary(v => v.Key, v => v.Value);

            string concat = string.Empty;

            string OAuthHeader = "OAuth ";
            foreach (var key in parameters.Keys)
            {
                concat += key + "=" + parameters[key] + "&";
                OAuthHeader += key + "=" + "\"" + parameters[key] + "\",";
            }

            concat = concat.Remove(concat.Length - 1, 1);
            concat = EncodeToUpper(concat);

            concat = "POST&" + EncodeToUpper(url) + "&" + concat;

            byte[] content = Encoding.UTF8.GetBytes(concat);

            HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(comsumeSercret + "&" + tokenSecret));
            hmac.ComputeHash(content);

            string hash = Convert.ToBase64String(hmac.Hash);

            hash = hash.Replace("-", "");

            OAuthHeader += "oauth_signature=\"" + EncodeToUpper(hash) + "\"";

            return OAuthHeader;
        }
Пример #5
0
 private static string CalcHMACSHA1Hash(string s)
 {
     using(HMACSHA1 cs = new HMACSHA1(Encoding.UTF8.GetBytes(HostedPaymentSettings.PublicKey)))
     {
         return Convert.ToBase64String(cs.ComputeHash(Encoding.UTF8.GetBytes(s)));
     }
 }
Пример #6
0
        public static string GeneratePassword(string secret, long iterationNumber, int digits = 6)
        {
            byte[] counter = BitConverter.GetBytes(iterationNumber);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(counter);
            }

            byte[] key = Encoding.ASCII.GetBytes(secret);

            System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(key, true);

            byte[] hash = hmac.ComputeHash(counter);

            int offset = hash[hash.Length - 1] & 0xf;

            int binary =
                ((hash[offset] & 0x7f) << 24)
                | ((hash[offset + 1] & 0xff) << 16)
                | ((hash[offset + 2] & 0xff) << 8)
                | (hash[offset + 3] & 0xff);

            int password = binary % (int)Math.Pow(10, digits); // 6 digits

            return(password.ToString(new string('0', digits)));
        }
Пример #7
0
        public virtual string HmacHash(string key, string message)
        {
            var hmac = new HMACSHA1(Sha1Bytes(key));
            byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));

            return BitConverter.ToString(hashBytes).Replace("-", "");
        }
Пример #8
0
        protected internal Uri Sign(Uri _uri)
        {
            if (_uri == null)
                throw new ArgumentNullException("_uri");

            if (string.IsNullOrWhiteSpace(this.Key))
                throw new ArgumentException("Invalid signing key.");

            if (this.ClientId == null)
                throw new NullReferenceException("ClientID");

            if (!this.ClientId.StartsWith("gme-"))
                throw new ArgumentException("A user ID must start with 'gme-'.");

            var _urlSegmentToSign = _uri.LocalPath + _uri.Query + "&client=" + this.ClientId;
            var _privateKey = SignableRequest.FromBase64UrlString(this.Key);
            byte[] _signature;

            using (var _algorithm = new HMACSHA1(_privateKey))
            {
                _signature = _algorithm.ComputeHash(Encoding.ASCII.GetBytes(_urlSegmentToSign));
            }

            return new Uri(_uri.Scheme + "://" + _uri.Host + _urlSegmentToSign + "&signature=" + SignableRequest.ToBase64UrlString(_signature));
        }
        private static string Sign(string url, string appSid, string appKey)
        {
            // Add AppSid parameter.
            UriBuilder uriBuilder = new UriBuilder(url);

            if (uriBuilder.Query != null && uriBuilder.Query.Length > 1)
                uriBuilder.Query = uriBuilder.Query.Substring(1) + "&appSID=" + appSid;
            else
                uriBuilder.Query = "appSID=" + appSid;

            // Remove final slash here as it can be added automatically.
            uriBuilder.Path = uriBuilder.Path.TrimEnd('/');

            // Compute the hash.
            byte[] privateKey = Encoding.UTF8.GetBytes(appKey);
            HMACSHA1 algorithm = new HMACSHA1(privateKey);

            byte[] sequence = ASCIIEncoding.ASCII.GetBytes(uriBuilder.Uri.AbsoluteUri);
            byte[] hash = algorithm.ComputeHash(sequence);
            string signature = Convert.ToBase64String(hash);

            // Remove invalid symbols.
            signature = signature.TrimEnd('=');
            signature = HttpUtility.UrlEncode(signature);

            // Convert codes to upper case as they can be updated automatically.
            signature = Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());

            // Add the signature to query string.
            return string.Format("{0}&signature={1}", uriBuilder.Uri.AbsoluteUri, signature);
        }
Пример #10
0
        private static string buildSignature(NameValueCollection queryString)
        {
            try
            {

            //// The HMAC secret as configured in the skin
                string hmacSecret = Globals.Instance.settings["PayPalhmacSecret"];

            //// Generate the signing string
            string signingString = queryString["paymentAmount"] + queryString["currencyCode"] +
                                   queryString["shipBeforeDate"] + queryString["merchantReference"] +
                                   queryString["skinCode"] + queryString["merchantAccount"] +
                                   queryString["sessionValidity"] + queryString["allowedMethods"] + queryString["merchantReturnData"];

            //// Values are always transferred using UTF-8 encoding
            var encoding = new System.Text.UTF8Encoding();

            //// Calculate the HMAC
            var myhmacsha1 = new HMACSHA1(encoding.GetBytes(hmacSecret));
            return Convert.ToBase64String(myhmacsha1.ComputeHash(encoding.GetBytes(signingString)));
                }
            catch (Exception exp)
            {
                log.Error(exp);
                throw;
            }
        }
        private static bool IsValidRequest(HttpActionContext context, string authToken, string urlOverride = null)
        {
            var value = new StringBuilder();
            
            // Take the host URL from the request, or use the URL override if there is one
            var fullUrl = string.IsNullOrEmpty(urlOverride) ? context.Request.RequestUri.ToString() : urlOverride;

            value.Append(fullUrl);

            var request = HttpContext.Current.Request;

            // If POST request, concatenate the key-value pairs in the request
            if (context.Request.Method == HttpMethod.Post)
            {
                var sortedKeys = request.Form.AllKeys.OrderBy(k => k, StringComparer.Ordinal).ToList();
                foreach (var key in sortedKeys)
                {
                    value.Append(key);
                    value.Append(request.Form[key]);
                }
            }

            // Create signature using AuthToken as key
            var sha1 = new HMACSHA1(Encoding.UTF8.GetBytes(authToken));
            var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(value.ToString()));
            var encoded = Convert.ToBase64String(hash);

            var sig = request.Headers["X-Twilio-Signature"];

            // Compare our signatures
            return sig == encoded;
        }
Пример #12
0
        /// <summary>
        ///   Generates a pin by hashing a key and counter.
        /// </summary>
        private static string GeneratePin(byte[] key, long counter)
        {
            //Get counter bytes (in big endian order)
            var counterBytes = BitConverter.GetBytes(counter);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(counterBytes);

            byte[] hash;
            using (var hmac = new HMACSHA1(key))
                hash = hmac.ComputeHash(counterBytes);

            var offset = hash[hash.Length - 1] & 0xF;

            var selectedBytes = new byte[sizeof(int)];
            Buffer.BlockCopy(hash, offset, selectedBytes, 0, sizeof(int));

            //spec interprets bytes in big-endian order
            if (BitConverter.IsLittleEndian)
                Array.Reverse(selectedBytes);

            var selectedInteger = BitConverter.ToInt32(selectedBytes, 0);

            //remove the most significant bit for interoperability per spec
            var truncatedHash = selectedInteger & 0x7FFFFFFF;

            //generate number of digits for given pin length
            var pin = truncatedHash % _pinModulo;

            return pin.ToString(CultureInfo.InvariantCulture).PadLeft(PIN_LENGTH, '0');
        }
Пример #13
0
        public void SetupCrypto(BigInteger key)
        {
            byte[] ServerDecryptionKey =
            {
                0xC2, 0xB3, 0x72, 0x3C, 0xC6, 0xAE, 0xD9, 0xB5,
                0x34, 0x3C, 0x53, 0xEE, 0x2F, 0x43, 0x67, 0xCE
            };

            byte[] ServerEncryptionKey =
            {
                0xCC, 0x98, 0xAE, 0x04, 0xE8, 0x97, 0xEA, 0xCA,
                0x12, 0xDD, 0xC0, 0x93, 0x42, 0x91, 0x53, 0x57
            };

            HMACSHA1 decryptHMAC = new HMACSHA1(ServerDecryptionKey);
            HMACSHA1 encryptHMAC = new HMACSHA1(ServerEncryptionKey);

            var decryptHash = decryptHMAC.ComputeHash(key.GetBytes());
            var encryptHash = encryptHMAC.ComputeHash(key.GetBytes());

            const int dropN = 1024; //1000 before WoTLK, 1024 now
            var buf = new byte[dropN];

            ClientConnection.Decrypt = new ARC4(decryptHash);
            ClientConnection.Encrypt = new ARC4(encryptHash);

            ClientConnection.Decrypt.Process(buf, 0, buf.Length);
            ClientConnection.Encrypt.Process(buf, 0, buf.Length);
        }
Пример #14
0
        public static string HOTP2(byte[] key, ulong counter, int digits = 6)
        {
            // compute SHA-1 HMAC of the key
            System.Security.Cryptography.HMACSHA1 hmac =
                new System.Security.Cryptography.HMACSHA1(key, true);

            // convert the counter to bytes, check if the system is little endian and reverse if necessary
            byte[] counter_bytes = BitConverter.IsLittleEndian ? BitConverter.GetBytes(counter).Reverse().ToArray() : BitConverter.GetBytes(counter);

            // compute the hash using the counter value
            byte[] hmac_result = hmac.ComputeHash(counter_bytes);

            // get the last 4 bits of the HMAC Result to determine the offset
            int offset = hmac_result[hmac_result.Length - 1] & 0xf;

            // get the value of 4 bytes of the HMAC Result starting at the offset position
            int bin_code = (hmac_result[offset] & 0x7f) << 24
                           | (hmac_result[offset + 1] & 0xff) << 16
                           | (hmac_result[offset + 2] & 0xff) << 8
                           | (hmac_result[offset + 3] & 0xff);

            // HOTP = bin_code modulo 10^(digits)
            int hotp = bin_code % (int)Math.Pow(10, digits);

            // truncate the string to the number of significant digits
            return(hotp.ToString(String.Empty.PadRight(digits, '0')));
        }
Пример #15
0
		private string AuthorizationHeader(string status) {
			var oauth_token = UserToken;
			var oauth_token_secret = UserSecret;
			var oauth_consumer_key = AppToken;
			var oauth_consumer_secret = AppSecret;

			var oauth_version          = "1.0";
			var oauth_signature_method = "HMAC-SHA1";
			var oauth_nonce            = Convert.ToBase64String(
				new ASCIIEncoding().GetBytes(
					DateTime.Now.Ticks.ToString()));
			var timeSpan               = DateTime.UtcNow
				- new DateTime(1970, 1, 1, 0, 0, 0, 0,
					DateTimeKind.Utc);
			var oauth_timestamp        = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
			var resource_url           = "https://api.twitter.com/1.1/statuses/update.json";

			var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
				"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}";

			var baseString = string.Format(baseFormat,
				oauth_consumer_key,
				oauth_nonce,
				oauth_signature_method,
				oauth_timestamp,
				oauth_token,
				oauth_version,
				Uri.EscapeDataString(status)
			);

			baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url), 
				"&", Uri.EscapeDataString(baseString));

			var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
				"&",  Uri.EscapeDataString(oauth_token_secret));

			string oauth_signature;
			using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
			{
				oauth_signature = Convert.ToBase64String(
					hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
			}

			var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
				"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
				"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
				"oauth_version=\"{6}\"";

			var authHeader = string.Format(headerFormat,
				Uri.EscapeDataString(oauth_nonce),
				Uri.EscapeDataString(oauth_signature_method),
				Uri.EscapeDataString(oauth_timestamp),
				Uri.EscapeDataString(oauth_consumer_key),
				Uri.EscapeDataString(oauth_token),
				Uri.EscapeDataString(oauth_signature),
				Uri.EscapeDataString(oauth_version)
			);

			return authHeader;
		}
Пример #16
0
        //--- Extension Methods ---
        /// <summary>
        /// Add a Plug Pre-Handler to attach the appropriate auth header.
        /// </summary>
        /// <param name="plug">Plug instance to base operation on.</param>
        /// <param name="privateKey">Amazon S3 private key.</param>
        /// <param name="publicKey">Amazon S3 public key.</param>
        /// <returns>New Plug instance with pre-handler.</returns>
        public static Plug WithS3Authentication(this Plug plug, string privateKey, string publicKey)
        {
            return plug.WithPreHandler((verb, uri, normalizedUri, message) => {

                // add amazon date header (NOTE: this must be the real wall-time)
                var date = DateTime.UtcNow.ToString("r");
                message.Headers[AWS_DATE] = date;

                // add authorization header
                var authString = new StringBuilder()
                    .Append(verb)
                    .Append("\n")
                    .Append(message.Headers[DreamHeaders.CONTENT_MD5])
                    .Append("\n")
                    .Append(message.ContentType.ToString())
                    .Append("\n")
                    .Append("\n");
                foreach(var header in message.Headers.OrderBy(x => x.Key.ToLowerInvariant(), StringComparer.Ordinal)) {
                    if(!header.Key.StartsWithInvariantIgnoreCase("x-amz-")) {
                        continue;
                    }
                    authString.AppendFormat("{0}:{1}\n", header.Key.ToLowerInvariant(), header.Value);
                }
                authString.Append(normalizedUri.Path);
                var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(privateKey));
                var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(authString.ToString())));
                message.Headers.Authorization = string.Format("AWS {0}:{1}", publicKey, signature);
                message.Headers.ContentType = message.ContentType;
                return message;
            });
        }
Пример #17
0
 public string GetSignature()
 {
     var policy64 = GetPolicyInBase64();
     byte[] b64Key = Encoding.ASCII.GetBytes(CManager.Settings.AWSSecretAccessKey);
     var hmacSha1 = new HMACSHA1(b64Key);
     return Convert.ToBase64String(hmacSha1.ComputeHash(Encoding.ASCII.GetBytes(policy64)));
 }
Пример #18
0
        private static dynamic ConstructRequestBody(string publickey, string privatekey, dynamic data)
        { 
            Dictionary<string, dynamic> query = new Dictionary<string, dynamic>();
            query.Add("key", publickey);
            query.Add("nonce", new Random(1000).Next().ToString());
            query.Add("timestamp", DateTime.UtcNow.ToString("yyyy-MM-ddThh:mm:ssZ"));


            var signingValue = new StringBuilder();
            var signedValue = string.Empty;
            foreach (var s in query.Values.ToArray().OrderBy(s => s))
                signingValue.Append(s);
            Logger.Debug(string.Format("signed value:{0}", signingValue.ToString()));
            using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes(privatekey)))
            {
                var hashValue = hmac.ComputeHash(Encoding.ASCII.GetBytes(signingValue.ToString()));
                signedValue = Convert.ToBase64String(hashValue);
               
            }
            query.Add("sign", signedValue);
            query.Add("data",data);

            return new { 
                key = query["key"],
                nonce = int.Parse(query["nonce"]),
                timestamp = query["timestamp"],
                sign = query["sign"],
                data = query["data"]

            };

        }
Пример #19
0
        /// <summary>
        /// Generates a signature using the specified signatureType 
        /// </summary>
        /// <param name="httpMethod">The http method used</param>
        /// <param name="url">The full url to be signed</param>
        /// <param name="parametersIn">The collection of parameters to sign</param>
        /// <param name="consumerSecret">The OAuth consumer secret used to generate the signature</param>
        /// <returns>A base64 string of the hash value</returns>
        public static string GenerateSignature(string httpMethod, Uri url, NameValueCollection parametersIn, string consumerSecret)
        {
            // Work with a copy of the parameters so the caller's data is not changed
            var parameters = new NameValueCollection(parametersIn);

            // https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
            // The query component is parsed into a list of name/value pairs by treating it as an
            // "application/x-www-form-urlencoded" string, separating the names and values and
            // decoding them as defined by [W3C.REC - html40 - 19980424], Section 17.13.4.
            //
            // Unescape the query so that it is not doubly escaped by UrlEncodingParser.
            var querystring = new UrlEncodingParser(Uri.UnescapeDataString(url.Query));
            parameters.Add(querystring);

            var signatureBase = GenerateSignatureBase(httpMethod, url, parameters);

            // Note that in LTI, the TokenSecret (second part of the key) is blank
            var hmacsha1 = new HMACSHA1
            {
                Key = Encoding.ASCII.GetBytes($"{consumerSecret.ToRfc3986EncodedString()}&")
            };

            var dataBuffer = Encoding.ASCII.GetBytes(signatureBase);
            var hashBytes = hmacsha1.ComputeHash(dataBuffer);

            return Convert.ToBase64String(hashBytes);
        }
Пример #20
0
 public string getHash(string input)
 {
     HMACSHA1 myhmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["HashSecret"]));
     byte[] byteArray = Encoding.ASCII.GetBytes(input);
     MemoryStream stream = new MemoryStream(byteArray);
     return myhmacsha1.ComputeHash(stream).Aggregate("", (s, e) => s + String.Format("{0:x2}", e), s => s);
 }
 protected static byte[] HMAC(byte[] data, string key)
 {
     using (var hmac = new HMACSHA1(data, true))
     {
         return hmac.ComputeHash(Encoding.UTF8.GetBytes(key));
     }
 }
Пример #22
0
        public override void SetAuth(HttpWebRequest request, Stream body)
        {
            byte[] secretKey = Encoding.ASCII.GetBytes(Config.SECRET_KEY);
            using (HMACSHA1 hmac = new HMACSHA1(secretKey))
            {
                string pathAndQuery = request.Address.PathAndQuery;
                byte[] pathAndQueryBytes = Encoding.ASCII.GetBytes(pathAndQuery);
                using (MemoryStream buffer = new MemoryStream())
                {
                    buffer.Write(pathAndQueryBytes, 0, pathAndQueryBytes.Length);
                    buffer.WriteByte((byte)'\n');
                    if (request.ContentType == "application/x-www-form-urlencoded" && body != null)
                    {
                        if (!body.CanSeek)
                        {
                            throw new Exception("stream can not seek");
                        }
                        StreamUtil.Copy(body, buffer);
                        body.Seek(0, SeekOrigin.Begin);
                    }
                    byte[] digest = hmac.ComputeHash(buffer.ToArray());
                    string digestBase64 = Base64UrlSafe.Encode(digest);

                    string authHead = "QBox " + Config.ACCESS_KEY + ":" + digestBase64;
                    request.Headers.Add("Authorization", authHead);
                }
            }
        }
Пример #23
0
 public async Task<bool> GetData(string msisdn)
 {
     try
     {
         Tools.Tools.SetProgressIndicator(true);
         SystemTray.ProgressIndicator.Text = "fetching data";
         var client = new VikingsApi();
         OAuthUtility.ComputeHash = (key, buffer) =>
         {
             using (var hmac = new HMACSHA1(key))
             {
                 return hmac.ComputeHash(buffer);
             }
         };
         string json = await client.GetInfo(new AccessToken((string) IsolatedStorageSettings.ApplicationSettings["tokenKey"], (string) IsolatedStorageSettings.ApplicationSettings["tokenSecret"]), client.Balance, new KeyValuePair {name = "msisdn", content = msisdn});
         if (Error.HandleError(json, "there seems to be no connection"))
             return false;
         Tools.Tools.SetProgressIndicator(false);
         Balance = new UserBalance(json);
         return true;
     }
     catch (Exception)
     {
         Message.ShowToast("Could not load bundle info, please try again later");
         return false;
     }
 }
Пример #24
0
 public async Task<bool> GetSimInfo()
 {
     Tools.Tools.SetProgressIndicator(true);
     try
     {
         Tools.Tools.SetProgressIndicator(true);
         SystemTray.ProgressIndicator.Text = "loading sims";
         var client = new VikingsApi();
         OAuthUtility.ComputeHash = (key, buffer) =>
         {
             using (var hmac = new HMACSHA1(key))
             {
                 return hmac.ComputeHash(buffer);
             }
         };
         string json = await client.GetInfo(new AccessToken((string) IsolatedStorageSettings.ApplicationSettings["tokenKey"], (string) IsolatedStorageSettings.ApplicationSettings["tokenSecret"]), client.Sim, new KeyValuePair {content = "1", name = "alias"});
         Sims = JsonConvert.DeserializeObject<Sim[]>(json);
         Tools.Tools.SetProgressIndicator(false);
         return true;
     }
     catch (Exception)
     {
         Message.ShowToast("Could not load sim information, please try again later");
         return false;
     }
 }
Пример #25
0
 public static string HMACSHA1(string key, string message)
 {
     using (var hasher = new crypto.HMACSHA1(Encoding.UTF8.GetBytes(key)))
     {
         return(hasher.ComputeHash(Encoding.UTF8.GetBytes(message)).ToHexString());
     }
 }
Пример #26
0
        private static string EncodePassword(string password)
        {
            HMACSHA1 hash = new HMACSHA1 {Key = HexToByte(key)};
            string encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));

            return encodedPassword;
        }
Пример #27
0
 public static string Encode(string input, byte[] key)
 {
     HMACSHA1 myhmacsha1 = new HMACSHA1(key);
     byte[] byteArray = Encoding.ASCII.GetBytes(input);
     MemoryStream stream = new MemoryStream(byteArray);
     return myhmacsha1.ComputeHash(stream).Aggregate("", (s, e) => s + String.Format("{0:x2}", e), s => s);
 }
Пример #28
0
        /// <summary>
        /// The original code at
        /// http://www.codeproject.com/Articles/403355/Implementing-Two-Factor-Authentication-in-ASP-NET
        /// by Rick Bassham, http://www.codeproject.com/script/Membership/View.aspx?mid=4294419
        /// under MIT License, http://opensource.org/licenses/mit-license.php
        /// 
        /// Modified by HouYu Li <*****@*****.**>
        /// </summary>
        /// <param name="secret"></param>
        /// <param name="iterationNumber"></param>
        /// <param name="digits"></param>
        /// <returns></returns>
        public static string GeneratePassword(string secret, long iterationNumber, int digits = 6)
        {
            byte[] counter = BitConverter.GetBytes(iterationNumber);

            if (BitConverter.IsLittleEndian)
                Array.Reverse(counter);

            byte[] key = Base32Decode.Decode(secret);

            HMACSHA1 hmac = new HMACSHA1(key, true);

            byte[] hash = hmac.ComputeHash(counter);

            int offset = hash[hash.Length - 1] & 0xf;

            int binary =
                ((hash[offset] & 0x7f) << 24)
                | ((hash[offset + 1] & 0xff) << 16)
                | ((hash[offset + 2] & 0xff) << 8)
                | (hash[offset + 3] & 0xff);

            int password = binary % (int)Math.Pow(10, digits);

            return password.ToString(new string('0', digits));
        }
Пример #29
0
 public static string ComputeHash(string qs)
 {
     byte[] textBytes = Encoding.UTF8.GetBytes(qs);
     HMACSHA1 hashAlgorithm = new HMACSHA1(Security.HexToByteArray(_hashKey));
     byte[] hash = hashAlgorithm.ComputeHash(textBytes);
     return Security.ByteArrayToHex(hash);
 }
        protected string GetCodeInternal(string secret, ulong challengeValue)
        {
            ulong chlg = challengeValue;
            byte[] challenge = new byte[8];
            for (int j = 7; j >= 0; j--) {
                challenge[j] = (byte)((int)chlg & 0xff);
                chlg >>= 8;
            }

            var key = Base32Encoding.ToBytes(secret);
            for (int i = secret.Length; i < key.Length; i++) {
                key[i] = 0;
            }

            HMACSHA1 mac = new HMACSHA1(key);
            var hash = mac.ComputeHash(challenge);

            int offset = hash[hash.Length - 1] & 0xf;

            int truncatedHash = 0;
            for (int j = 0; j < 4; j++) {
                truncatedHash <<= 8;
                truncatedHash |= hash[offset + j];
            }

            truncatedHash &= 0x7FFFFFFF;
            truncatedHash %= 1000000;

            string code = truncatedHash.ToString();
            return code.PadLeft(6, '0');
        }
Пример #31
0
		public static string Generate(byte[] pbSecret, ulong uFactor,
			uint uCodeDigits, bool bAddChecksum, int iTruncationOffset)
		{
			byte[] pbText = MemUtil.UInt64ToBytes(uFactor);
			Array.Reverse(pbText); // Big-Endian

			HMACSHA1 hsha1 = new HMACSHA1(pbSecret);
			byte[] pbHash = hsha1.ComputeHash(pbText);

			uint uOffset = (uint)(pbHash[pbHash.Length - 1] & 0xF);
			if((iTruncationOffset >= 0) && (iTruncationOffset < (pbHash.Length - 4)))
				uOffset = (uint)iTruncationOffset;

			uint uBinary = (uint)(((pbHash[uOffset] & 0x7F) << 24) |
				((pbHash[uOffset + 1] & 0xFF) << 16) |
				((pbHash[uOffset + 2] & 0xFF) << 8) |
				(pbHash[uOffset + 3] & 0xFF));

			uint uOtp = (uBinary % vDigitsPower[uCodeDigits]);
			if(bAddChecksum)
				uOtp = ((uOtp * 10) + CalculateChecksum(uOtp, uCodeDigits));

			uint uDigits = (bAddChecksum ? (uCodeDigits + 1) : uCodeDigits);
			return uOtp.ToString().PadLeft((int)uDigits, '0');
		}
Пример #32
0
Файл: OTP.cs Проект: nrag/yapper
        /**
            * Generate a one-time password
            *
            * @param integer $input : number used to seed the hmac hash function.
            * This number is usually a counter (HOTP) or calculated based on the current
            * timestamp (see TOTP class).
            * @return integer the one-time password
            */
        public int GenerateOTP(Int64 input)
        {
            Byte[] secretBytes = Guid.Parse(this.secret).ToByteArray();
            HMAC hashgenerator = new HMACSHA1(secretBytes);

            hashgenerator.ComputeHash(IntToByteString(input));
            string hash = "";

            foreach (byte b in hashgenerator.Hash)
            {
                hash += b.ToString("x2");
            }

            List<int> hmac = new List<int>();
            foreach (string s in hash.Split(2))
            {
                hmac.Add(Int32.Parse(s, System.Globalization.NumberStyles.HexNumber));
            }

            // The offset is the last nibble of the hash
            int offset = hmac[19] & 0xf;

            // Code is 4 bytes starting at the offset
            int code = (hmac[offset + 0] & 0x7F) << 24 |
                    (hmac[offset + 1] & 0xFF) << 16 |
                    (hmac[offset + 2] & 0xFF) << 8 |
                    (hmac[offset + 3] & 0xFF);

            return code % (int)Math.Pow((double)10, (double)this.digits);
        }
Пример #33
0
        protected void Application_Start()
        {
            OAuthUtility.ComputeHash = (key, buffer) => { using (var hmac = new HMACSHA1(key)) { return hmac.ComputeHash(buffer); } };

            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
Пример #34
0
 private void CreatePasswordHash(string password, out byte[] passHash, out byte[] passSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA1())
     {
         passSalt = hmac.Key;
         passHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
     }
 }
 /// <summary>
 /// Generate salt from password.
 /// </summary>
 /// <param name="password">Password string.</param>
 /// <returns>Salt bytes.</returns>
 private byte[] SaltFromPassword(string password)
 {
     byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
     System.Security.Cryptography.HMACSHA1 hmac;
     hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes);
     byte[] salt = hmac.ComputeHash(passwordBytes);
     return(salt);
 }
Пример #36
0
 /// <summary>
 /// 加密
 /// </summary>
 /// <param name="content"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static byte[] Encrypt(byte[] content, byte[] key)
 {
     //HMACSHA1加密
     System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1();
     hmacsha1.Key = key;
     byte[] dataBuffer = content;
     byte[] hashBytes  = hmacsha1.ComputeHash(dataBuffer);
     return(hashBytes);
 }
Пример #37
0
 /// <summary>
 /// 加密
 /// </summary>
 /// <param name="content"></param>
 /// <param name="key"></param>
 /// <param name="encoding"></param>
 /// <returns></returns>
 public static byte[] Encrypt(string content, string key, Encoding encoding)
 {
     //HMACSHA1加密
     System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1();
     hmacsha1.Key = encoding.GetBytes(key);
     byte[] dataBuffer = encoding.GetBytes(content);
     byte[] hashBytes  = hmacsha1.ComputeHash(dataBuffer);
     return(hashBytes);
 }
Пример #38
0
        /// <summary>
        /// HMACSHA1  加密
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns></returns>
        public static string ToHMACSHA1(string secret, string mk)
        {
            var hmacsha1 = new System.Security.Cryptography.HMACSHA1();

            hmacsha1.Key = Encoding.UTF8.GetBytes(secret);
            byte[] dataBuffer = Encoding.UTF8.GetBytes(mk);
            byte[] hashBytes  = hmacsha1.ComputeHash(dataBuffer);
            return(Convert.ToBase64String(hashBytes));
        }
Пример #39
0
        private string GetHashString(string sPassword, string salt)
        {
            HashAlgorithm hash = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(salt));

            byte[] hashBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(sPassword));

            hash.Clear();

            return(BitConverter.ToString(hashBytes).Replace("-", string.Empty).ToLower());
        }
Пример #40
0
        private bool Verify(int version, string privateMac, string privateHash,
                            string passphrase, string keyTypeName, string encryptionName, string comment, byte[] publicBlob, byte[] privateBlob)
        {
            byte[] macData;
            using (MemoryStream macDataBuff = new MemoryStream())
            {
                if (version == 1)
                {
                    WriteMacData(macDataBuff, privateBlob);
                }
                else
                {
                    WriteMacData(macDataBuff, keyTypeName);
                    WriteMacData(macDataBuff, encryptionName);
                    WriteMacData(macDataBuff, comment);
                    WriteMacData(macDataBuff, publicBlob);
                    WriteMacData(macDataBuff, privateBlob);
                }
                macDataBuff.Close();
                macData = macDataBuff.ToArray();
            }

            if (privateMac != null)
            {
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                byte[] a = Encoding.ASCII.GetBytes("putty-private-key-file-mac-key");
                sha1.TransformBlock(a, 0, a.Length, null, 0);
                byte[] b = Encoding.UTF8.GetBytes(passphrase);
                sha1.TransformFinalBlock(b, 0, b.Length);
                byte[] key = sha1.Hash;
                sha1.Clear();

                System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(key);
                byte[] hash = hmacsha1.ComputeHash(macData);
                hmacsha1.Clear();
                string mac = BinToHex(hash);
                return(mac == privateMac);
            }
            else if (privateHash != null)
            {
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                byte[] hash = sha1.ComputeHash(macData);
                sha1.Clear();
                string mac = BinToHex(hash);
                return(mac == privateHash);
            }
            else
            {
                return(true);
            }
        }
Пример #41
0
        private static string GetSignature(string url, string method, string nonce, string timestamp, string token, string tokenSecret, Dictionary <string, object> parameters)
        {
            var dict = new Dictionary <string, object>();

            dict.Add("oauth_consumer_key", TumblrConsumerKey);
            dict.Add("oauth_nonce", nonce.ToString());
            dict.Add("oauth_signature_method", "HMAC-SHA1");
            dict.Add("oauth_timestamp", timestamp);
            dict.Add("oauth_token", token);
            dict.Add("oauth_version", "1.0");
            var sigBase = new StringBuilder();
            var first   = true;

            foreach (var d in (parameters == null ? dict : dict.Union(parameters)).OrderBy(p => p.Key))
            {
                if (!first)
                {
                    sigBase.Append("&");
                }
                first = false;
                if (d.Key.StartsWith("data"))
                {
                    sigBase.Append(d.Key);
                }
                else
                {
                    UrlEncode(sigBase, d.Key);
                }
                sigBase.Append("=");
                if (d.Value is byte[])
                {
                    EncodeSigStream(sigBase, (byte[])d.Value);
                }
                else
                {
                    UrlEncode(sigBase, d.Value.ToString());
                }
            }

            String SigBaseString = method.ToUpper() + "&";

            SigBaseString += UrlEncode(url) + "&" + UrlEncode(sigBase.ToString(), false);

            var keyMaterial      = Encoding.UTF8.GetBytes(TumblrConsumerSecret + "&" + tokenSecret);
            var HmacSha1Provider = new System.Security.Cryptography.HMACSHA1 {
                Key = keyMaterial
            };

            return(Convert.ToBase64String(HmacSha1Provider.ComputeHash(Encoding.UTF8.GetBytes(SigBaseString))));
        }
Пример #42
0
        /// <summary>
        /// Get the Cart Signature used in the &quot;signature&quot;
        /// form field that is posted to Google Checkout.
        /// </summary>
        /// <param name="cart">The Cart Xml returned from the
        /// <see cref="GCheckout.Checkout.CheckoutShoppingCartRequest.GetXml"/>
        /// method.</param>
        /// <param name="merchantKey">Your Google Merchant Key</param>
        /// <returns>A Base64 encoded string of the cart signature</returns>
        public static string GetCartSignature(byte[] cart, string merchantKey)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] key = encoding.GetBytes(merchantKey);

            using (System.Security.Cryptography.HMACSHA1 cryptobj = new
                                                                    System.Security.Cryptography.HMACSHA1(key)) {
                string retVal =
                    System.Convert.ToBase64String(cryptobj.ComputeHash(cart));

                cryptobj.Clear();
                return(retVal);
            }
        }
Пример #43
0
 private bool VerifyPassHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA1(passwordSalt))
     {
         var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
         for (int i = 0; i < computedHash.Length; i++)
         {
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
         return(true);
     }
 }
Пример #44
0
        private static string HMACSHA1(string secret, string data)
        {
            System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.Default.GetBytes(secret));

            byte [] dataHMAC = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(data));

            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < dataHMAC.Length; i++)
            {
                sBuilder.Append(dataHMAC[i].ToString("x2"));
            }

            return(sBuilder.ToString());
        }
Пример #45
0
        //原型HmacSha1
        public static string HmacSha1(string szString, string szKey)
        {
            System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1();
            hmacsha1.Key = Encoding.UTF8.GetBytes(szKey);
            byte[] dataBuffer = Encoding.UTF8.GetBytes(szString);
            byte[] hashBytes  = hmacsha1.ComputeHash(dataBuffer);

            StringBuilder ret = new StringBuilder();

            foreach (byte b in hashBytes)
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return(ret.ToString().ToLower());
        }
        public void ExampleScript()
        {
            // Turn input string into a byte array.
            var input = System.Text.Encoding.Unicode.GetBytes("Plain Text");

            // Create an instance of the Rijndael class.
            System.Security.Cryptography.RijndaelManaged cipher;
            cipher = new System.Security.Cryptography.RijndaelManaged();
            // Calculate salt bytes to make it harder to guess key by using a dictionary attack.
            var password = System.Text.Encoding.UTF8.GetBytes("password");
            var hmac     = new System.Security.Cryptography.HMACSHA1(password);
            var salt     = hmac.ComputeHash(password);
            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 10);
            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            var key     = secretKey.GetBytes(32);
            var iv      = secretKey.GetBytes(16);
            var cryptor = cipher.CreateEncryptor(key, iv);
            // Create new Input.
            var inputBuffer = new System.Byte[input.Length];

            // Copy data bytes to input buffer.
            System.Buffer.BlockCopy(input, 0, inputBuffer, 0, inputBuffer.Length);
            // Create a MemoryStream to hold the output bytes.
            var stream = new System.IO.MemoryStream();
            // Create a CryptoStream through which we are going to be processing our data.
            var mode         = System.Security.Cryptography.CryptoStreamMode.Write;
            var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode);

            // Start the crypting process.
            cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
            // Finish crypting.
            cryptoStream.FlushFinalBlock();
            // Convert data from a memoryStream into a byte array.
            var outputBuffer = stream.ToArray();

            // Close both streams.
            stream.Close();
            //cryptoStream.Close();
            // Convert encrypted data into a base64-encoded string.
            var base64String = System.Convert.ToBase64String(outputBuffer);
            // base64String = laFf3eKu9tzB2XksJjd8EVM3PA9O30wz0Y+X3nyelW4=
        }
Пример #47
0
        byte[] Transform(byte[] dataBytes, byte[] passwordBytes, bool encrypt, bool fips)
        {
            /// <summary>Encrypt by using AES-256 algorithm.</summary>
            // Create an instance of the Rijndael class.
            var cipher = fips
                                ? new System.Security.Cryptography.AesCryptoServiceProvider() as SymmetricAlgorithm
                                : new System.Security.Cryptography.RijndaelManaged();
            // Calculate salt to make it harder to guess key by using a dictionary attack.
            var hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes);
            var salt = hmac.ComputeHash(passwordBytes);
            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, salt, 10);
            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            var key = secretKey.GetBytes(32);
            var iv  = secretKey.GetBytes(16);
            // Get cryptor as System.Security.Cryptography.ICryptoTransform class.
            var cryptor = encrypt
                                ? cipher.CreateEncryptor(key, iv)
                                : cipher.CreateDecryptor(key, iv);
            // Create new Input.
            var inputBuffer = new byte[dataBytes.Length];

            // Copy data bytes to input buffer.
            System.Buffer.BlockCopy(dataBytes, 0, inputBuffer, 0, inputBuffer.Length);
            // Create a MemoryStream to hold the output bytes.
            var stream = new System.IO.MemoryStream();
            // Create a CryptoStream through which we are going to be processing our data.
            var mode         = System.Security.Cryptography.CryptoStreamMode.Write;
            var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode);

            // Start the crypting process.
            cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
            // Finish crypting.
            cryptoStream.FlushFinalBlock();
            // Convert data from a memoryStream into a byte array.
            var outputBuffer = stream.ToArray();

            // Close both streams.
            stream.Close();
            cryptoStream.Close();
            return(outputBuffer);
        }
Пример #48
0
        //O HMAC é a combinação de um hash + senha
        public static string HMAC(string palavra, string senha)
        {
            //Transformanda a senha em byte
            byte[] senhaByte = System.Text.Encoding.UTF8.GetBytes(senha);
            //Transformanda a palavra em byte
            byte[] palavraByte = System.Text.Encoding.UTF8.GetBytes(palavra);

            //Usando a função hash HMAC e passando a senha no construtor
            using (var hmac = new  System.Security.Cryptography.HMACSHA1(senhaByte))
            {
                //Gerando o hash
                byte[] hashByte = hmac.ComputeHash(palavraByte);

                //Transformando em base64
                string hashBase64 = System.Convert.ToBase64String(hashByte);

                //Retornando
                return(hashBase64);
            }
        }
    public static UserAccountCSV Create(string userName, string userPassword, string userRoles = "", bool requiresActivation = false)
    {
        if (string.IsNullOrWhiteSpace(userPassword))
        {
            return(null);
        }
        if (string.IsNullOrWhiteSpace(userName) || userName.Any(Char.IsWhiteSpace))
        {
            return(null);
        }

        var user = new UserAccountCSV();

        user.UserName = userName.Trim().ToLower();

        var accounts   = ReadAccountCSV();
        var userExists = accounts.FirstOrDefault(x => x.UserName == user.UserName) != null;

        if (userExists)
        {
            return(null);
        }

        // Create PasswordHash
        using (var hmac = new System.Security.Cryptography.HMACSHA1()) //HMACSHA512
        {
            user.PasswordSalt = hmac.Key;
            user.PasswordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(userPassword));
        }

        user.Roles     = System.Text.RegularExpressions.Regex.Replace(userRoles, @"\s+", "");
        user.CreatedOn = DateTime.Now;
        user.IsActive  = !requiresActivation;

        accounts.Add(user);
        WriteAccountCSV(accounts);

        user.PasswordSalt = null;
        user.PasswordHash = null;
        return(user);
    }
Пример #50
0
        /// <summary>
        /// Generate a TOTP using provided binary data.
        /// </summary>
        /// <param name="key">Binary data.</param>
        /// <returns>Time-based One Time Password encoded byte array.</returns>
        public byte[] Generate(byte[] key)
        {
            System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(key, true); //Instanciates a new hash provider with a key.
            byte[] hash = hmac.ComputeHash(GetBytes((ulong)Counter));                                          //Generates hash from key using counter.
            hmac.Clear();                                                                                      //Clear hash instance securing the key.

            /*int binary =                                        //Math.
             * ((hash[offset] & 0x7f) << 24)                   //Math.
             | ((hash[offset + 1] & 0xff) << 16)             //Math.
             | ((hash[offset + 2] & 0xff) << 8)              //Math.
             | (hash[offset + 3] & 0xff);                    //Math.
             |
             | int password = binary % (int)Math.Pow(10, length); //Math.*/

            int offset = hash[hash.Length - 1] & 0x0f;           //Math.

            byte[] totp = { hash[offset + 3], hash[offset + 2], hash[offset + 1], hash[offset] };
            return(totp);

            /*
             * return password.ToString(new string('0', length)); //Math.*/
        }
        protected void TestButton_Click(object sender, EventArgs e)
        {
            // Define key and data string.
            string k = "test key";
            string s = "abc新闻网efg新闻网";

            byte[] kb = System.Text.Encoding.UTF8.GetBytes(k);
            byte[] sb = System.Text.Encoding.UTF8.GetBytes(s);
            // Test SHA1.
            WriteLog("// Create SHA1 Algorithm");
            System.Security.Cryptography.SHA1CryptoServiceProvider sha1;
            sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            string hash = System.BitConverter.ToString(sha1.ComputeHash(sb));

            WriteLog("sha1.ComputeHash('" + s + "') = " + hash);
            // Test HMACSHA1.
            Trace.Write("// Create HMAC-SHA1 Algorithm");
            System.Security.Cryptography.HMACSHA1 hmac;
            hmac = new System.Security.Cryptography.HMACSHA1(kb);
            hash = System.BitConverter.ToString(hmac.ComputeHash(sb));
            WriteLog("hmac.ComputeHash('" + k + "','" + s + "') = " + hash);
        }
Пример #52
0
        public async Task <bool> IsValidSha1Async(string orgId, string teamId, string appId, string sha1, string payload)
        {
            if (!await organisationRepository.ExistsByAsync(o => o.Id == orgId))
            {
                return(false);
            }

            if (!await this.teamRepository.ExistsByAsync(t => t.TeamCode == teamId && t.OrganisationId == orgId))
            {
                return(false);
            }

            var appLocated = await this.repository.GetByAsync(app => app.TeamCode == teamId && app.OrganisationId == orgId && app.Id == appId);

            if (appLocated == null)
            {
                return(false);
            }

            if (string.IsNullOrWhiteSpace(appLocated.GithubSecretKey))
            {
                return(true);
            }

            var keyBody   = Encoding.UTF8.GetBytes(payload);
            var secretKey = Encoding.UTF8.GetBytes(appLocated.GithubSecretKey);

            using (var hmacAlgorithm = new System.Security.Cryptography.HMACSHA1(secretKey))
            {
                var hmac    = hmacAlgorithm.ComputeHash(keyBody);
                var hmacHex = "sha1=" + hmac.ToHexString();

                return(true);
                //return sha1 == hmacHex;
            }
        }
Пример #53
0
        private byte[] Authenticate(byte[] iv, byte[] encrypted)
        {
#if NETSTANDARD1_3
            var hmac      = new System.Security.Cryptography.HMACSHA1(_hmacKey.Buffer);
            var composite = new byte[iv.Length + encrypted.Length];
            Array.Copy(iv, 0, composite, 0, iv.Length);
            Array.Copy(encrypted, 0, composite, iv.Length, encrypted.Length);
            var result = hmac.ComputeHash(composite);
#else
            var hmac = System.Security.Cryptography.HMACSHA1.Create();
            hmac.Key = _hmacKey.Buffer;

            hmac.TransformBlock(iv, 0, iv.Length, iv, 0);
            hmac.TransformFinalBlock(encrypted, 0, encrypted.Length);

            var result = hmac.Hash;
#endif

#if !NET20 && !NET30 && !NET35
            hmac.Dispose();
#endif

            return(result);
        }
Пример #54
0
 public byte[] ComputeHash(byte[] data, int offset, int length)
 {
     _algorithm.Initialize();
     return(_algorithm.ComputeHash(data, offset, length));
 }
Пример #55
0
        //Function that is executed once button is clicked and goes through various checks and eventually adds the e-mail or domain to the blocked sites profile group in mimecast
        public void AddBlockedSite()
        {
            //Setup required variables - ENTER YOUR OWN HERE
            string baseUrl         = "https://us-api.mimecast.com";
            string uri             = "/api/directory/add-group-member";
            string accessKey       = "enter your own here";
            string secretKey       = "enter your own here";
            string appId           = "enter your own here";
            string appKey          = "enter your own here";
            string blockedsenderid = "enter your own here";

            //Code borrowed from Mimecast's API Documentation with modifications to work with this application
            //Generate request header values
            string hdrDate   = System.DateTime.Now.ToUniversalTime().ToString("R");
            string requestId = System.Guid.NewGuid().ToString();

            //Create the HMAC SHA1 of the Base64 decoded secret key for the Authorization header
            System.Security.Cryptography.HMAC h = new System.Security.Cryptography.HMACSHA1(System.Convert.FromBase64String(secretKey));

            //Use the HMAC SHA1 value to sign the hdrDate + ":" requestId + ":" + URI + ":" + appkey
            byte[] hash = h.ComputeHash(System.Text.Encoding.Default.GetBytes(hdrDate + ":" + requestId + ":" + uri + ":" + appKey));

            //Build the signature to be included in the Authorization header in your request
            string signature = "MC " + accessKey + ":" + System.Convert.ToBase64String(hash);

            //Build Request
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(baseUrl + uri);
            request.Method      = "POST";
            request.ContentType = "application/json";

            //Add Headers
            request.Headers[System.Net.HttpRequestHeader.Authorization] = signature;
            request.Headers.Add("x-mc-date", hdrDate);
            request.Headers.Add("x-mc-req-id", requestId);
            request.Headers.Add("x-mc-app-id", appId);

            // checks to see if domain or e-mail address is checked
            if (rb_domain.IsChecked == true)
            {
                status.Content = ("Domain selected.");
                if (CheckDomain(tb_entry.Text))
                {
                    status.Content = ("Domain is valid.");

                    //Add request body
                    //Create and write data to stream
                    string postData = "{\"data\": [{\"id\": \"" + blockedsenderid + "\",\"domain\": \"" + tb_entry.Text + "\"}]}";

                    byte[] payload = System.Text.Encoding.UTF8.GetBytes(postData);

                    System.IO.Stream stream = request.GetRequestStream();
                    stream.Write(payload, 0, payload.Length);
                    stream.Close();

                    //Send Request
                    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                    //Output response to console
                    System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
                    string responseBody           = "";
                    string temp = null;
                    while ((temp = reader.ReadLine()) != null)
                    {
                        responseBody += temp;
                    }
                    ;

                    //json parsing variables - this will retrieve the meta and failure messages to confirm successful entries from Mimecast's API
                    var jsonDoc         = JsonDocument.Parse(responseBody);
                    var root            = jsonDoc.RootElement;
                    var entrystatus     = root.GetProperty("meta");
                    var entryfailstatus = root.GetProperty("fail");

                    //error handling and updating status if status is 200 and no failures this means the site was successfully added, if not it confirms status ok but there were failures
                    if (entrystatus.ToString() == "{\"status\":200}")
                    {
                        if (entryfailstatus.ToString() == "[]")
                        {
                            status.Content = ("Domain added successfully.");
                        }
                        else
                        {
                            status.Content = ("Status OK but failures present!");
                        }
                    }
                    else
                    {
                        status.Content = ("Domain not blocked, status failed.");
                    }
                }
                else
                {
                    status.Content = ("Domain is on free-email list, please recheck!");
                }
            }
            if (rb_email.IsChecked == true)
            {
                if (ValidateEmail(tb_entry.Text))
                {
                    status.Content = ("Valid e-mail");

                    //Add request body
                    //Create and write data to stream
                    string postData = "{\"data\": [{\"id\": \"" + blockedsenderid + "\",\"emailAddress\": \"" + tb_entry.Text + "\"}]}";

                    byte[] payload = System.Text.Encoding.UTF8.GetBytes(postData);

                    System.IO.Stream stream = request.GetRequestStream();
                    stream.Write(payload, 0, payload.Length);
                    stream.Close();

                    //Send Request
                    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                    //Output response to console
                    System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
                    string responseBody           = "";
                    string temp = null;
                    while ((temp = reader.ReadLine()) != null)
                    {
                        responseBody += temp;
                    }
                    ;

                    //json parsing variables - this will retrieve the meta and failure messages to confirm successful entries
                    var jsonDoc         = JsonDocument.Parse(responseBody);
                    var root            = jsonDoc.RootElement;
                    var entrystatus     = root.GetProperty("meta");
                    var entryfailstatus = root.GetProperty("fail");

                    //error handling and updating status if status is 200 and no failures this means the e-mail was successfully added, if not it confirms status ok but there were failures
                    if (entrystatus.ToString() == "{\"status\":200}")
                    {
                        if (entryfailstatus.ToString() == "[]")
                        {
                            status.Content = ("E-mail address added successfully.");
                        }
                        else
                        {
                            status.Content = ("Status OK but failures present!");
                        }
                    }
                    else
                    {
                        status.Content = ("E-mail address not blocked, status failed.");
                    }
                }
                else
                {
                    status.Content = ("E-mail address entered is not valid!");
                }
            }
        }
Пример #56
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            spnStatus.Visible = true;

            lblMsg.Visible = false;
            string secret_key   = "ed70df7a017654499542ff0a5515812824b74142";
            string data         = "";
            string txnId        = Request["TxId"];
            string txnStatus    = Request["TxStatus"];
            string amount       = Request["amount"];
            string pgTxnId      = Request["pgTxnNo"];
            string issuerRefNo  = Request["issuerRefNo"];
            string authIdCode   = Request["authIdCode"];
            string firstName    = Request["firstName"];
            string lastName     = Request["lastName"];
            string pgRespCode   = Request["pgRespCode"];
            string zipCode      = Request["addressZip"];
            string resSignature = Request["signature"];

            bool flag = true;
            if (txnId != null)
            {
                data += txnId;
            }
            if (txnStatus != null)
            {
                data += txnStatus;
            }
            if (amount != null)
            {
                data += amount;
            }
            if (pgTxnId != null)
            {
                data += pgTxnId;
            }
            if (issuerRefNo != null)
            {
                data += issuerRefNo;
            }
            if (authIdCode != null)
            {
                data += authIdCode;
            }
            if (firstName != null)
            {
                data += firstName;
            }
            if (lastName != null)
            {
                data += lastName;
            }
            if (pgRespCode != null)
            {
                data += pgRespCode;
            }
            if (zipCode != null)
            {
                data += zipCode;
            }

            System.Security.Cryptography.HMACSHA1 myhmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(secret_key));

            System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(data));
            string signature = BitConverter.ToString(myhmacsha1.ComputeHash(stream)).Replace("-", "").ToLower();

            if (resSignature != null && !signature.Equals(resSignature))
            {
                flag = false;
            }
            if (flag == true)
            {
                //Response.Write("Thank You for using citrus payment Your Unique Transaction Status:" + Convert.ToString(txnStatus));
                if (Session["Bed"] != null || Session["Surgery"] != null || Session["AppointmentDetail"] != null || Session["HealthCheck-upComprehensive"] != null || Session["OutstandingBillPayment"] != null || Session["permenantRegistration"] != null || Session["ConsultationAppointment"] != null)
                {
                    DataAccessEntities sessionData = new DataAccessEntities();
                    if (Session["Bed"] != null)
                    {
                        sessionData = (DataAccessEntities)Session["Bed"];
                    }
                    else if (Session["Surgery"] != null)
                    {
                        sessionData = (DataAccessEntities)Session["Surgery"];
                    }
                    else if (Session["AppointmentDetail"] != null)
                    {
                        sessionData = (DataAccessEntities)Session["AppointmentDetail"];
                    }
                    else if (Session["HealthCheck-upComprehensive"] != null)
                    {
                        sessionData = (DataAccessEntities)Session["HealthCheck-upComprehensive"];
                    }
                    else if (Session["OutstandingBillPayment"] != null)
                    {
                        sessionData = (DataAccessEntities)Session["OutstandingBillPayment"];
                    }
                    else if (Session["permenantRegistration"] != null)
                    {
                        sessionData = (DataAccessEntities)Session["permenantRegistration"];
                    }
                    else if (Session["ConsultationAppointment"] != null)
                    {
                        sessionData = (DataAccessEntities)Session["ConsultationAppointment"];
                    }

                    //double Damount = Convert.ToDouble(amount);

                    sessionData.Tranrefid  = Convert.ToString(issuerRefNo);
                    sessionData.Transtatus = Convert.ToString(txnStatus);
                    sessionData.Amount     = Convert.ToInt32(Session["Amount"]);
                    sessionData.UserId     = user.UserID;

                    lblUserName.Text    = user.DisplayName;
                    lblMNo.Text         = user.Username; //= Convert.ToString(user.UserID);
                    lblTxtnId.Text      = sessionData.Transactionid = Convert.ToString(txnId);
                    lblPaidAgainst.Text = sessionData.FacilityName;
                    lblDateTime.Text    = Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy"));
                    lblAmount.Text      = Convert.ToString(Session["Amount"]) + ".00 INR";

                    if (txnStatus != null)
                    {
                        PatIndex objDeposit = new PatIndex();
                        if (Session["Bed"] != null)
                        {
                            if (txnStatus == "CANCELED")
                            {
                                Session["Bed"] = null;
                                Response.Redirect("/Bed-Booking");
                            }
                            var detaisl = objPatIndex.SaveDeposit(lblTxtnId.Text, lblMNo.Text, Convert.ToDouble(Session["Amount"]), Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy")), sessionData.FacilityName);

                            if (detaisl != null && !string.IsNullOrEmpty(detaisl.MRNO))
                            {
                                sessionData.JeevaStatus = detaisl.MRNO;
                            }

                            objBusinessLogic.SavePaymentBedSurgery(sessionData);
                            ServiceBookingSendEmail(user.DisplayName, user.Email, sessionData.FacilityName, sessionData.Category, lblDateTime.Text, Convert.ToString(Session["Amount"]) + ".00 INR", "BedBookingPayment");
                            Session["Bed"] = null;
                        }

                        else if (Session["Surgery"] != null)
                        {
                            if (txnStatus == "CANCELED")
                            {
                                Session["Surgery"] = null;
                                Response.Redirect("/surgery-booking");
                            }
                            var detaisl = objPatIndex.SaveDeposit(lblTxtnId.Text, lblMNo.Text, Convert.ToDouble(Session["Amount"]), Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy")), sessionData.FacilityName);

                            if (detaisl != null && !string.IsNullOrEmpty(detaisl.MRNO))
                            {
                                sessionData.JeevaStatus = detaisl.MRNO;
                            }

                            objBusinessLogic.SavePaymentBedSurgery(sessionData);
                            ServiceBookingSendEmail(user.DisplayName, user.Email, sessionData.FacilityName, sessionData.Category, lblDateTime.Text, Convert.ToString(Session["Amount"]) + ".00 INR", "SurgeryBookingPayment");
                            Session["Surgery"] = null;
                        }
                        else if (Session["HealthCheck-upComprehensive"] != null)
                        {
                            if (txnStatus == "CANCELED")
                            {
                                Session["HealthCheck-upComprehensive"] = null;
                                Response.Redirect("/health-check-up-comprehensive");
                            }
                            var detaisl = objPatIndex.SaveDeposit(lblTxtnId.Text, lblMNo.Text, Convert.ToDouble(Session["Amount"]), Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy")), sessionData.FacilityName);

                            if (detaisl != null && !string.IsNullOrEmpty(detaisl.MRNO))
                            {
                                sessionData.JeevaStatus = detaisl.MRNO;
                            }

                            objBusinessLogic.SavePaymentBedSurgery(sessionData);
                            string _categoryName = sessionData.Category;
                            if (_categoryName == "Male" || _categoryName == "Female")
                            {
                                _categoryName = "Package B (" + sessionData.Category + ")";
                            }
                            ServiceBookingSendEmail(user.DisplayName, user.Email, sessionData.FacilityName, _categoryName, lblDateTime.Text, Convert.ToString(Session["Amount"]) + ".00 INR", "HealthCheckPayment");
                            Session["HealthCheck-upComprehensive"] = null;
                        }
                        else if (Session["OutstandingBillPayment"] != null)
                        {
                            if (txnStatus == "CANCELED")
                            {
                                Session["OutstandingBillPayment"] = null;
                                Response.Redirect("/outstandingbillpayment");
                            }

                            var detaisl = objPatIndex.SaveDeposit(lblTxtnId.Text, lblMNo.Text, Convert.ToDouble(Session["Amount"]), Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy")), sessionData.FacilityName);

                            if (detaisl != null && !string.IsNullOrEmpty(detaisl.MRNO))
                            {
                                sessionData.JeevaStatus = detaisl.MRNO;
                            }

                            objBusinessLogic.SavePaymentBedSurgery(sessionData);
                            OutStandingSendEmail(sessionData.FacilityName, Convert.ToString(Session["Amount"]) + ".00 INR", "OutstandingPayment");
                            Session["OutstandingBillPayment"] = null;
                        }
                        else if (Session["permenantRegistration"] != null)
                        {
                            if (txnStatus == "CANCELED")
                            {
                                Session["permenantRegistration"] = null;
                                Response.Redirect("/");
                            }
                            Session["permenantRegistration"] = null;
                            lblMsg.Visible = true;



                            string Gender = user.Profile.GetPropertyValue("Gender");
                            if (Gender == "Male")
                            {
                                Gender = "M";
                            }
                            else
                            {
                                Gender = "F";
                            }
                            string Age         = user.Profile.GetPropertyValue("Age");
                            string Address     = user.Profile.GetPropertyValue("Address");
                            string PhoneNumber = user.Profile.GetPropertyValue("PhoneNumber");

                            string[] X = PhoneNumber.Split('-');
                            PhoneNumber = X[1];

                            string Username;
                            string Fname;
                            string Lname;
                            string Email;

                            if (user.Username.Length > 20)
                            {
                                Username = user.Username.Substring(0, 20);
                            }
                            else
                            {
                                Username = user.Username;
                            }

                            if (user.FirstName.Length > 30)
                            {
                                Fname = user.FirstName.Substring(0, 30);
                            }
                            else
                            {
                                Fname = user.FirstName;
                            }

                            if (user.LastName.Length > 30)
                            {
                                Lname = user.LastName.Substring(0, 30);
                            }
                            else
                            {
                                Lname = user.LastName;
                            }
                            if (user.Email.Length > 50)
                            {
                                Email = user.Email.Substring(0, 50);
                            }
                            else
                            {
                                Email = user.Email;
                            }
                            if (Address.Length > 30)
                            {
                                Address = Address.Substring(0, 30);
                            }

                            if (PhoneNumber.Length > 12)
                            {
                                PhoneNumber = PhoneNumber.Substring(0, 12);
                            }


                            var PatientDetails = objPatIndex.UpdateorInsertPatient(user.Username, user.FirstName, user.LastName, Gender, Age, "01/01/2000", Address, Address, Address, PhoneNumber, Email);

                            if (!string.IsNullOrEmpty(PatientDetails.WEBPWD))
                            {
                                DataSet ds = objBusinessLogic.IsExistMRNumber(PatientDetails.MRNO);
                                if (ds.Tables[0].Rows.Count > 0)
                                {
                                    Clear();
                                    lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
                                    lblMsg.Text      = "You Are Allready Registered As A permanent User!";
                                }
                                else
                                {
                                    bool IsUserExist = objBusinessLogic.IsUserExist(PatientDetails.MRNO);
                                    if (!IsUserExist)
                                    {
                                        if (PatientDetails.PatSex == "M")
                                        {
                                            PatientDetails.PatSex = "Male";
                                        }
                                        else
                                        {
                                            PatientDetails.PatSex = "Female";
                                        }
                                        DataSet dsVal = InsertUpdateUserDetails(PatientDetails.MRNO, PatientDetails.PatFName, PatientDetails.PatLName, PatientDetails.PatEmail, PatientDetails.WEBPWD, PatientDetails.PatMobile, PatientDetails.PatSex, PatientDetails.PatAddr1, PatientDetails.PatAge);
                                        lblMNo.Text = PatientDetails.MRNO;


                                        var detaisl = objPatIndex.SaveDeposit(lblTxtnId.Text, lblMNo.Text, Convert.ToDouble(Session["Amount"]), Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy")), sessionData.FacilityName);

                                        if (detaisl != null && !string.IsNullOrEmpty(detaisl.MRNO))
                                        {
                                            sessionData.JeevaStatus = detaisl.MRNO;
                                        }

                                        objBusinessLogic.SavePaymentBedSurgery(sessionData);


                                        if (dsVal.Tables[0].Rows.Count > 0)
                                        {
                                            // SendMail & MSG

                                            try
                                            {
                                                PermanentUserSendEmail(PatientDetails.PatFName, PatientDetails.PatEmail, PatientDetails.MRNO, PatientDetails.WEBPWD, PhoneNumber, "PermanentRegistration");
                                                lblMsg.Text      = "You are now the permanent user! Please login with your MR Number that has been sent to your registered mobile number";
                                                lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000");
                                            }
                                            catch (Exception ex)
                                            {
                                                lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
                                                lblMsg.Text      = "SMS Service is stoped Due to technical problem!";
                                            }
                                            UserController.DeleteUser(ref user, false, false);
                                            UserController.RemoveUser(user);
                                            if (user.UserID != -1)
                                            {
                                                secure.SignOut();
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Clear();
                                        lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
                                        lblMsg.Text      = "UserName allready exist!";
                                    }
                                }
                            }
                            else
                            {
                                Clear();
                                lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
                                lblMsg.Text      = "You are already register as a permanent user, Please login with MR Number";
                            }
                        }
                        else if (Session["ConsultationAppointment"] != null || Session["AppointmentDetail"] != null)
                        {
                            if (txnStatus == "CANCELED")
                            {
                                Session["ConsultationAppointment"] = null;
                                Session["AppointmentDetail"]       = null;
                                Response.Redirect("/");
                            }
                            sessionData.FacilityName = "Appointment";
                            var detaisl = objPatIndex.SaveDeposit(lblTxtnId.Text, lblMNo.Text, Convert.ToDouble(Session["Amount"]), Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy")), sessionData.FacilityName);

                            if (detaisl != null && !string.IsNullOrEmpty(detaisl.MRNO))
                            {
                                sessionData.JeevaStatus = detaisl.MRNO;
                            }
                            sessionData.FacilityName = "Consultation Appointment";
                            objBusinessLogic.SavePaymentBookAppointment(sessionData);
                            AppointmentSendEmail(Convert.ToString(sessionData.PhoneNo), Convert.ToString(sessionData.MobileNo), Convert.ToString(sessionData.Location), Convert.ToString(sessionData.Address), Convert.ToString(sessionData.TimeDate), Convert.ToString(Session["Amount"]) + ".00 INR", Convert.ToString(sessionData.Description), sessionData.dName, "ConsultationAppointment");
                            Session["ConsultationAppointment"] = null;
                            Session["AppointmentDetail"]       = null;
                        }
                    }
                    else
                    {
                        plcDivSucces.Visible          = false;
                        plcDivError.Visible           = true;
                        spnStatus.Attributes["Class"] = "highlight";
                        spnStatus.InnerText           = "Payment Fail !";
                    }
                    Session["Amount"] = null;
                }
                else
                {
                    plcDivSucces.Visible          = false;
                    plcDivError.Visible           = true;
                    spnStatus.Attributes["Class"] = "highlight";
                    spnStatus.InnerText           = "Payment Fail !";
                }
            }
            else
            {
                Response.Write("Citrus Response Signature and Our (Merchant)Signature Mis - Match");
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //Need to replace the last part of URL("your-vanityUrlPart") with your Testing/Live URL

        //formPostUrl = "/comingsoon";
        //formPostUrl = "https://sandbox.citruspay.com/sslperf/jaslokhospital";
        //formPostUrl = "https://www.citruspay.com/jaslokhospital";

        string host          = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);
        string _httpProtocol = host.StartsWith("www.") ? "https://" : "http://";

        if (host.StartsWith("www."))
        {
            formPostUrl = System.Configuration.ConfigurationManager.AppSettings["fromPostUrl"];

            secret_key = System.Configuration.ConfigurationManager.AppSettings["secretkey_fromPostUrl"];
        }
        else
        {
            formPostUrl = System.Configuration.ConfigurationManager.AppSettings["fromSandBoxPostUrl"];
            secret_key  = System.Configuration.ConfigurationManager.AppSettings["secretkey_fromSandBoxPostUrl"];
        }

        vanityUrl = System.Configuration.ConfigurationManager.AppSettings["VanityUrl"];

        merchantTxnId = System.DateTime.Now.ToString("yyyyMMddHHmmssffff");

        //Need to change with your Secret Key
        // string secret_key = "66fc8c3cca181b8954338bb5d5bd0cbb18b99b6d";
        // string secret_key = "ed70df7a017654499542ff0a5515812824b74142";
        //Need to change with your Vanity URL Key from the citrus panel

        //Should be unique for every transaction

        if (Request.QueryString["reg"] != null)
        {
            objDAEntities.FacilityName   = "PermenantRegistration";
            objDAEntities.BookinDateTime = Convert.ToDateTime(DateTime.Now.ToString());
            //Session["permenantRegistration"] = objDAEntities;
            //Session["Amount"] = 100;
            objDAEntities.Amount = 100;
            orderAmount          = Convert.ToString(objDAEntities.Amount);
            objDAEntities.Guid   = System.Guid.NewGuid().ToString();
            Session["Guid"]      = "Reg-" + objDAEntities.Guid;
            objBusinessLogic.SaveInfoGuid(objDAEntities);
        }

        if (Request.QueryString["amount"] != null)
        {
            orderAmount = Request.QueryString["amount"];
            orderAmount = objBusinessLogic.Decrypt(HttpUtility.UrlDecode(orderAmount));
        }
        //orderAmount = Session["Amount"].ToString();
        //Need to change with your Order Amount

        currency = "INR";
        string data = vanityUrl + orderAmount + merchantTxnId + currency;

        System.Security.Cryptography.HMACSHA1 myhmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(secret_key));
        System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(data));
        securitySignature = BitConverter.ToString(myhmacsha1.ComputeHash(stream)).Replace("-", "").ToLower();
        UserInfo user = UserController.Instance.GetCurrentUserInfo();

        UserName = user.Username;
        //Session["Amount"] = null;

        returnUrl = _httpProtocol + Request.ServerVariables["SERVER_NAME"] + "/PaymentResponse.aspx";


        notifyUrl = returnUrl;
        //Response.Redirect("/PaymentResponse.aspx");
        //Response.Write("txm:" + merchantTxnId + "  " + securitySignature);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string txn_id = "";

        if (Session["CIT_MARTRANSACTIONID"] != null)
        {
            txn_id = Session["CIT_MARTRANSACTIONID"].ToString() + "T" + System.DateTime.Now.ToString("yyyyMMddHHmmssffff");
        }
        if (Session["CIT_AMOUNT"] != null)
        {
            citrusAmount.Value = HttpContext.Current.Session["CIT_AMOUNT"].ToString();
        }
        if (Session["CIT_NAME"] != null)
        {
            citrusFirstName.Value = Session["CIT_NAME"].ToString();
            citrusLastName.Value  = Session["CIT_NAME"].ToString();
        }
        if (Session["CIT_EMAIL"] != null)
        {
            citrusEmail.Value = HttpContext.Current.Session["CIT_EMAIL"].ToString();
        }
        if (Session["CIT_PHONE"] != null)
        {
            citrusMobile.Value = HttpContext.Current.Session["CIT_PHONE"].ToString();
        }

        string access_key = "DQPW4Y3F1ZP9BHKRU2J2";
        string bankid     = Request.QueryString["bid"].ToString();
        string secret_key = "2d2ed82733071d05c98378f5b989e423a218554a";

        //string return_url = "http://www.russsh.com/Payment/SampleResponse.aspx";

        //string vanityUrl = "russshpay";

        //Need to change with your Return URL
        string returnURL = "https://www.russsh.com/Task_Payment/PaymentResponse.aspx?BOOKID=" + txn_id;

        citrusReturnUrl.Value = "https://www.russsh.com/Task_Payment/PaymentResponse.aspx?BOOKID=" + txn_id;
        //Need to change with your Notify URL
        string notifyUrl = "https://www.russsh.com/Task_Payment/TransactionResponse.aspx";

        Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
        // txn_id = Session["CIT_MARTRANSACTIONID"].ToString() +"T"+System.DateTime.Now.ToString("yyyyMMddHHmmssffff");
        string amount      = Session["CIT_AMOUNT"].ToString();
        string data_string = "merchantAccessKey=" + access_key + "&transactionId=" + txn_id + "&amount=" + amount;

        byte[] key = Encoding.ASCII.GetBytes(secret_key);
        System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(key);
        System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(data_string));
        string signature = BitConverter.ToString(hmac.ComputeHash(stream)).Replace("-", "").ToLower();


        citrusMerchantTxnId.Value = txn_id;
        citrusAmount.Value        = amount;
        citrusSignature.Value     = signature;
        // bankid.Value = bankid;
        citrusAvailableOptions.Value = bankid;
        for (int i = 0; i <= citrusAvailableOptions.Items.Count - 1; i++)
        {
            if (citrusAvailableOptions.Items[i].Value == bankid)
            {
                citrusAvailableOptions.Items[i].Selected = true;
            }
        }
        citrusFirstName.Value     = Session["CIT_NAME"].ToString();
        citrusLastName.Value      = Session["CIT_NAME"].ToString();
        citrusEmail.Value         = Session["CIT_EMAIL"].ToString();
        citrusMobile.Value        = Session["CIT_PHONE"].ToString();
        citrusAmount.Value        = Session["CIT_AMOUNT"].ToString();
        citrusMerchantTxnId.Value = txn_id;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            spnStatus.Visible = true;
            lblMsg.Visible    = false;
            string secret_key   = (host.StartsWith("www.")) ? System.Configuration.ConfigurationManager.AppSettings["secretkey_fromPostUrl"] : System.Configuration.ConfigurationManager.AppSettings["secretkey_fromSandBoxPostUrl"];//"ed70df7a017654499542ff0a5515812824b74142";
            string data         = "";
            string txnId        = Request["TxId"];
            string txnStatus    = Request["TxStatus"];
            string amount       = Request["amount"];
            string pgTxnId      = Request["pgTxnNo"];
            string issuerRefNo  = Request["issuerRefNo"];
            string authIdCode   = Request["authIdCode"];
            string firstName    = Request["firstName"];
            string lastName     = Request["lastName"];
            string pgRespCode   = Request["pgRespCode"];
            string zipCode      = Request["addressZip"];
            string resSignature = Request["signature"];
            string _mrNumber    = Request["MrNumber"];

            bool flag = true;
            if (txnId != null)
            {
                data += txnId;
            }
            if (txnStatus != null)
            {
                data += txnStatus;
            }
            if (amount != null)
            {
                data += amount;
            }
            if (pgTxnId != null)
            {
                data += pgTxnId;
            }
            if (issuerRefNo != null)
            {
                data += issuerRefNo;
            }
            if (authIdCode != null)
            {
                data += authIdCode;
            }
            if (firstName != null)
            {
                data += firstName;
            }
            if (lastName != null)
            {
                data += lastName;
            }
            if (pgRespCode != null)
            {
                data += pgRespCode;
            }
            if (zipCode != null)
            {
                data += zipCode;
            }

            System.Security.Cryptography.HMACSHA1 myhmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(secret_key));

            System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(data));
            string signature = BitConverter.ToString(myhmacsha1.ComputeHash(stream)).Replace("-", "").ToLower();

            if (resSignature != null && !signature.Equals(resSignature))
            {
                flag = false;
            }
            if (flag == true)
            {
                string Tranrefid  = Convert.ToString(issuerRefNo);
                string Transtatus = Convert.ToString(txnStatus);
                //sessionData.Amount = Convert.ToInt32(Session["Amount"]);
                int UserId = user.UserID;
                lblUserName.Text    = user.DisplayName;
                lblMNo.Text         = user.Username; //= Convert.ToString(user.UserID);
                lblTxtnId.Text      = Convert.ToString(txnId);
                lblPaidAgainst.Text = string.Empty;
                lblDateTime.Text    = Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy"));
                lblAmount.Text      = string.Empty;
                // PR();
                if (txnStatus != null)
                {
                    if (Session["Guid"] != null)
                    {
                        DataSet AppointmentDs = new DataSet();
                        if (txnStatus == "CANCELED")
                        {
                            Session["Guid"] = null;
                            Response.Redirect("/");
                        }
                        string Guid = Session["Guid"].ToString();

                        string PageName = Guid.Substring(0, 3);

                        if (PageName == "App")
                        {
                            AppointmentDs = objBusinessLogic.SavePaymentBookAppointment(txnId, Tranrefid, Transtatus, Guid, JeevaStatus);
                            if (AppointmentDs.Tables[0].Rows.Count > 0)
                            {
                                double Amount      = Convert.ToDouble(AppointmentDs.Tables[0].Rows[0]["AMOUNT"]);
                                string ServiceName = Convert.ToString(AppointmentDs.Tables[0].Rows[0]["ServiceName"]);
                                int    PaymentId   = Convert.ToInt32(AppointmentDs.Tables[0].Rows[0]["PaymentId"]);
                                lblAmount.Text      = Convert.ToString(Amount);
                                lblPaidAgainst.Text = ServiceName;
                                // Send data to Napier Service for Save Deposit
                                JeevaStatus = SaveDeposit(txnId, lblMNo.Text, Amount, Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy")), ServiceName);
                                // Code To Update Jeeva status in Payment Table
                                if (!string.IsNullOrEmpty(JeevaStatus))
                                {
                                    DataTable dt = null;
                                    objBusinessLogic.UpdateStatus(JeevaStatus, PaymentId, lblMNo.Text, dt);
                                }
                                AppointmentSendEmail(Convert.ToString(AppointmentDs.Tables[0].Rows[0]["PhoneNo"]), Convert.ToString(AppointmentDs.Tables[0].Rows[0]["MobileNo"]), Convert.ToString(AppointmentDs.Tables[0].Rows[0]["Country"]), Convert.ToString(AppointmentDs.Tables[0].Rows[0]["StateName"]), Convert.ToString(AppointmentDs.Tables[0].Rows[0]["BookedDate"]), Convert.ToString(AppointmentDs.Tables[0].Rows[0]["AMOUNT"]) + ".00 INR", Convert.ToString(AppointmentDs.Tables[0].Rows[0]["Description"]), Convert.ToString(AppointmentDs.Tables[0].Rows[0]["DoctName"]), "ConsultationAppointment");
                                AppointmentDs.Tables[0].Rows.Clear();
                            }
                            Session["Guid"] = null;
                        }

                        else if (PageName == "Reg")
                        {
                            lblMsg.Visible = true;
                            string Gender = user.Profile.GetPropertyValue("Gender");
                            if (Gender == "Male")
                            {
                                Gender = "M";
                            }
                            else
                            {
                                Gender = "F";
                            }
                            string Age         = user.Profile.GetPropertyValue("Age");
                            string Address     = user.Profile.GetPropertyValue("Address");
                            string PhoneNumber = user.Profile.GetPropertyValue("PhoneNumber");

                            string[] X = PhoneNumber.Split('-');
                            PhoneNumber = X[1];

                            string Username;
                            string Fname;
                            string Lname;
                            string Email;

                            if (user.Username.Length > 20)
                            {
                                Username = user.Username.Substring(0, 20);
                            }
                            else
                            {
                                Username = user.Username;
                            }

                            if (user.FirstName.Length > 30)
                            {
                                Fname = user.FirstName.Substring(0, 30);
                            }
                            else
                            {
                                Fname = user.FirstName;
                            }

                            if (user.LastName.Length > 30)
                            {
                                Lname = user.LastName.Substring(0, 30);
                            }
                            else
                            {
                                Lname = user.LastName;
                            }
                            if (user.Email.Length > 50)
                            {
                                Email = user.Email.Substring(0, 50);
                            }
                            else
                            {
                                Email = user.Email;
                            }
                            if (Address.Length > 30)
                            {
                                Address = Address.Substring(0, 30);
                            }

                            if (PhoneNumber.Length > 12)
                            {
                                PhoneNumber = PhoneNumber.Substring(0, 12);
                            }


                            var PatientDetails = NapierService(user.Username, user.FirstName, user.LastName, Gender, Age, "01/01/2000", Address, Address, Address, PhoneNumber, Email);

                            //var PatientDetails = objPatIndex.UpdateorInsertPatient(user.Username, user.FirstName, user.LastName, Gender, Age, "01/01/2000", Address, Address, Address, PhoneNumber, Email);

                            if (!string.IsNullOrEmpty(PatientDetails.MRNO))
                            {
                                if (!string.IsNullOrEmpty(PatientDetails.WEBPWD))
                                {
                                    bool IsExistMRNumber = objBusinessLogic.IsExistMRNumber(PatientDetails.MRNO);
                                    if (IsExistMRNumber == true)
                                    {
                                        Clear();
                                        lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
                                        lblMsg.Text      = "You Are Allready Registered As A permanent User!";
                                    }
                                    else
                                    {
                                        bool IsUserExist = objBusinessLogic.IsUserExist(PatientDetails.MRNO);
                                        if (!IsUserExist)
                                        {
                                            if (PatientDetails.PatSex == "M")
                                            {
                                                PatientDetails.PatSex = "Male";
                                            }
                                            else
                                            {
                                                PatientDetails.PatSex = "Female";
                                            }
                                            DataSet dsVal = InsertUpdateUserDetails(PatientDetails.MRNO, PatientDetails.PatFName, PatientDetails.PatLName, PatientDetails.PatEmail, PatientDetails.WEBPWD, PatientDetails.PatMobile, PatientDetails.PatSex, PatientDetails.PatAddr1, PatientDetails.PatAge);
                                            lblMNo.Text = PatientDetails.MRNO;

                                            if (dsVal.Tables[0].Rows.Count > 0)
                                            {
                                                // SendMail & MSG
                                                try
                                                {
                                                    PermanentUserSendEmail(PatientDetails.PatFName, PatientDetails.PatEmail, PatientDetails.MRNO, PatientDetails.WEBPWD, PhoneNumber, "PermanentRegistration");
                                                }
                                                catch (Exception ex)
                                                {
                                                    lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
                                                    lblMsg.Text      = "SMS Service is stoped Due to technical problem!";

                                                    Exceptions.LogException(ex);
                                                }

                                                lblMsg.Text      = "You are now the permanent user! Please login with your MR Number that has been sent to your registered mobile number";
                                                lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000");
                                                UserController.DeleteUser(ref user, false, false);
                                                UserController.RemoveUser(user);
                                                if (user.UserID != -1)
                                                {
                                                    secure.SignOut();
                                                }
                                            }
                                        }
                                        else
                                        {
                                            Clear();
                                            lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
                                            lblMsg.Text      = "UserName already exist!";
                                        }
                                    }
                                }
                                else
                                {
                                    Clear();
                                    lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
                                    lblMsg.Text      = "You are already register as a permanent user, Please login with MR Number";
                                }
                            }
                            else
                            {
                                Clear();
                                lblMsg.Visible       = true;
                                lblMsg.ForeColor     = System.Drawing.ColorTranslator.FromHtml("#FF0000");
                                lblMsg.Text          = "Due to some technical problem MRNumber is not generated please contact Jaslok Hospital!";
                                plcDivSucces.Visible = true;
                                plcDivError.Visible  = false;
                            }

                            // code to save payment details of Per. Reg.
                            int    PaymentId   = 0;
                            int    Amount      = 100;
                            string ServiceName = "PermenantRegistration";
                            lblAmount.Text      = Convert.ToString(Amount);
                            lblPaidAgainst.Text = ServiceName;
                            // Send data to Napier Service for Save Deposit
                            JeevaStatus = SaveDeposit(txnId, lblMNo.Text, Amount, Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy")), ServiceName);

                            DataTable dt = new DataTable();
                            dt.Columns.AddRange(new DataColumn[9] {
                                new DataColumn("TRANSACTIONID"), new DataColumn("TRANREFID"), new DataColumn("TRANSTATUS"), new DataColumn("AMOUNT"), new DataColumn("USERID"), new DataColumn("PORTALID"), new DataColumn("JeevaStatus"), new DataColumn("MrNo"), new DataColumn("ServiceName")
                            });


                            //Add rows to DataTable.
                            dt.Rows.Add(txnId, Tranrefid, Transtatus, Amount, user.UserID, AppGlobal.PortalId, JeevaStatus, lblMNo.Text, ServiceName);

                            if (dt.Rows.Count > 0)
                            {
                                objBusinessLogic.UpdateStatus(JeevaStatus, PaymentId, lblMNo.Text, dt);
                            }
                        }

                        else
                        {
                            DataSet ds = objBusinessLogic.SavePaymentDetails(Guid, txnId, Tranrefid, Transtatus);
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                double Amount         = Convert.ToDouble(ds.Tables[0].Rows[0]["Amount"]);
                                string ServiceName    = Convert.ToString(ds.Tables[0].Rows[0]["ServiceName"]);
                                string ServicePackage = Convert.ToString(ds.Tables[0].Rows[0]["ServicePackage"]);
                                string BookDate       = Convert.ToString(ds.Tables[0].Rows[0]["BEDBOOKINDATETIME"]);
                                int    PaymentId      = Convert.ToInt32(ds.Tables[0].Rows[0]["PaymentId"]);
                                string processName    = Convert.ToString(ds.Tables[0].Rows[0]["processName"]);
                                lblAmount.Text      = Convert.ToString(Amount);
                                lblPaidAgainst.Text = ServiceName;
                                // Send data to Napier Service for Save Deposit
                                JeevaStatus = SaveDeposit(txnId, lblMNo.Text, Amount, Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy")), ServiceName);

                                // Code To Update Jeeva status in Payment Table
                                if (!string.IsNullOrEmpty(JeevaStatus))
                                {
                                    DataTable dt = null;
                                    objBusinessLogic.UpdateStatus(JeevaStatus, PaymentId, lblMNo.Text, dt);
                                }
                                // Conditions For Email
                                if (processName == "Bed" || processName == "Sur" || processName == "Hea")
                                {
                                    string TemplateName = string.Empty;
                                    if (processName == "Bed")
                                    {
                                        TemplateName = "BedBookingPayment";
                                    }
                                    else if (processName == "Sur")
                                    {
                                        TemplateName = "SurgeryBookingPayment";
                                    }
                                    else if (processName == "Hea")
                                    {
                                        TemplateName = "HealthCheckPayment";
                                    }

                                    ServiceBookingSendEmail(user.DisplayName, user.Email, ServiceName, ServicePackage, BookDate, Amount + ".00 INR", TemplateName);
                                }
                                else if (processName == "Out")
                                {
                                    OutStandingSendEmail(sessionData.FacilityName, Amount + ".00 INR", "OutstandingPayment");
                                }

                                ds.Tables[0].Rows.Clear();
                            }
                            Session["Guid"] = null;
                        }
                    }
                }
                else
                {
                    plcDivSucces.Visible          = false;
                    plcDivError.Visible           = true;
                    spnStatus.Attributes["Class"] = "highlight";
                    spnStatus.InnerText           = "Payment Fail !";
                }
            }
            else
            {
                Response.Write("Citrus Response Signature and Our (Merchant)Signature Mis - Match");
            }
        }

        catch (Exception ex)
        {
            Exceptions.LogException(ex);
        }
    }
Пример #60
0
    protected void Page_Load(object sender, EventArgs e)
    {
        con.ConnectionString = ConfigurationManager.ConnectionStrings["TESTQUEUEConnectionString"].ToString();
        string txn_id = "";

        if (Session["CIT_MARTRANSACTIONID"] != null)
        {
            if (Session["CIT_MARTRANSACTIONID"] != null)
            {
                txn_id = Session["CIT_MARTRANSACTIONID"].ToString() + "T" + System.DateTime.Now.ToString("yyyyMMddHHmmssffff");
            }
            if (Session["CIT_AMOUNT"] != null)
            {
                citrusAmount.Value = HttpContext.Current.Session["CIT_AMOUNT"].ToString();
            }
            if (Session["CIT_NAME"] != null)
            {
                citrusFirstName.Value = Session["CIT_NAME"].ToString();
                citrusLastName.Value  = Session["CIT_NAME"].ToString();
            }
            if (Session["CIT_EMAIL"] != null)
            {
                citrusEmail.Value = HttpContext.Current.Session["CIT_EMAIL"].ToString();
            }
            if (Session["CIT_PHONE"] != null)
            {
                citrusMobile.Value = HttpContext.Current.Session["CIT_PHONE"].ToString();
            }

            string access_key = "DQPW4Y3F1ZP9BHKRU2J2";
            string cdata      = "0";
            if (Request.QueryString["Data"] != "" && Request.QueryString["Data"] != null)
            {
                cdata = Request.QueryString["Data"].ToString();
                string[] words  = cdata.Split('_');
                string[] words2 = GetCardType(words[0].ToString().Substring(0, 6)).Split(',');

                citrusCardType.Value   = words2[1];
                citrusNumber.Value     = words[0];
                citrusCardHolder.Value = words[1];
                citrusExpiry.Value     = words[2] + "/" + words[3];
                citrusCvv.Value        = words[4];
                string _isSave = "0";
                _isSave = words[5];
                if (_isSave == "1")
                {
                    DataSet ds1 = new DataSet();
                    con.Open();
                    cmd             = new SqlCommand("CCD", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@ClientID", SqlDbType.Int).Value            = Convert.ToInt32(Session["CLIENT_ID"].ToString());
                    cmd.Parameters.Add("@CardNo", SqlDbType.NVarChar).Value         = MyExtenstionMethods.EncryptString(words[0]);
                    cmd.Parameters.Add("@CardHolderName", SqlDbType.NVarChar).Value = MyExtenstionMethods.EncryptString(words[1]);
                    cmd.Parameters.Add("@CardType", SqlDbType.NVarChar).Value       = MyExtenstionMethods.EncryptString(words2[1]);
                    cmd.Parameters.Add("@ExpiryMonth", SqlDbType.NVarChar).Value    = MyExtenstionMethods.EncryptString(words[2]);
                    cmd.Parameters.Add("@ExpiryYear", SqlDbType.NVarChar).Value     = MyExtenstionMethods.EncryptString(words[3]);
                    da = new SqlDataAdapter(cmd);
                    da.Fill(ds1);
                    DataTable dtable = ds1.Tables[0];
                }
                for (int i = 0; i <= citrusScheme.Items.Count - 1; i++)
                {
                    if (citrusScheme.Items[i].Value == words2[0])
                    {
                        citrusScheme.Items[i].Selected = true;
                    }
                }
            }

            //string bankid = Request.QueryString["bid"].ToString();
            string secret_key = "2d2ed82733071d05c98378f5b989e423a218554a";

            //string return_url = "http://www.russsh.com/Payment/SampleResponse.aspx";

            //string vanityUrl = "russshpay";

            //Need to change with your Return URL
            string returnURL = "https://www.russsh.com/Task_Payment/PaymentResponse.aspx?BOOKID=" + txn_id;
            citrusReturnUrl.Value = "https://www.russsh.com/Task_Payment/PaymentResponse.aspx?BOOKID=" + txn_id;
            //Need to change with your Notify URL
            string notifyUrl = "https://www.russsh.com/Task_Payment/TransactionResponse.aspx";

            Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            string amount      = Session["CIT_AMOUNT"].ToString();
            string data_string = "merchantAccessKey=" + access_key + "&transactionId=" + txn_id + "&amount=" + amount;

            byte[] key = Encoding.ASCII.GetBytes(secret_key);
            System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(key);
            System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(data_string));
            string signature = BitConverter.ToString(hmac.ComputeHash(stream)).Replace("-", "").ToLower();


            citrusMerchantTxnId.Value = txn_id;
            citrusAmount.Value        = amount;
            citrusSignature.Value     = signature;
            citrusFirstName.Value     = Session["CIT_NAME"].ToString();
            citrusLastName.Value      = Session["CIT_NAME"].ToString();
            citrusEmail.Value         = Session["CIT_EMAIL"].ToString();
            citrusMobile.Value        = Session["CIT_PHONE"].ToString();
            citrusAmount.Value        = Session["CIT_AMOUNT"].ToString();
            citrusMerchantTxnId.Value = txn_id;
        }
        else
        {
            Response.Redirect("../");
        }
    }