GetBytes() private method

private GetBytes ( char chars, int charCount, byte bytes, int byteCount ) : int
chars char
charCount int
bytes byte
byteCount int
return int
        protected string Encode(string value)
        {
            UTF8Encoding encoding = new UTF8Encoding();

            switch (_DataType.Encoding)
            {
                case "BASE64": return Convert.ToBase64String(encoding.GetBytes(value));
                case "7BIT":
                case "8BIT":                
                    value = Regex.Replace(value, @"[^\r]\n", "\r\n");
                    value = Regex.Replace(value, @"\r[^\n]", "\r\n");

                    bool is7Bit = _DataType.Encoding.Equals("7BIT");

                    List<byte> data = new List<byte>(encoding.GetBytes(value));
                    for (int i = data.Count - 1; i >= 0; i--)
                    {
                        if (data[i] == 0)
                            data.RemoveAt(i);

                        if (is7Bit && data[i] > 127)
                            data.RemoveAt(i);
                    }

                    return encoding.GetString(data.ToArray());
                default:
                    return value;
            }
        }
        public World Generate()
        {
            Console.WriteLine("Generating new World...");
            world.Day = 1;
            world.Width = 50;
            world.Height = 50;
            world.Tiles = GenerateMap(world.Width, world.Height);
            world.Registrations = new List<Registration>();
            world.Players = new List<Player>();
            world.Villages = new List<Village>();
            world.IPBans = new List<IPBan>();

            #if DEBUG
            System.Security.Cryptography.SHA256Managed sha256 = new System.Security.Cryptography.SHA256Managed();
            UTF8Encoding utf8Encoder = new UTF8Encoding();
            Player player = new Player();
            player.Name = "Majzlík";
            player.Login = "******";
            player.Password = sha256.ComputeHash(utf8Encoder.GetBytes("majzlik"));
            world.Players.Add(player);
            player = new Player();
            player.Name = "Setal";
            player.Login = "******";
            player.Password = sha256.ComputeHash(utf8Encoder.GetBytes("setal"));
            world.Players.Add(player);
            #endif
            Console.WriteLine("New World Generated");
            return world;
        }
        public void ValidateDdexWithXmlFile()
        {
            // Arrange
            var validator = new Mock<IDdexValidator>();
            var controller = new HomeController(validator.Object);
            var xmlMessage = TestSettings.Default.EmptyXml;

            var context = new Mock<ControllerContext>();
            var server = new Mock<HttpServerUtilityBase>();
            var request = new Mock<HttpRequestBase>();
            var files = new Mock<HttpFileCollectionBase>();
            var enc = new UTF8Encoding();

            var file1 = new Mock<HttpPostedFileBase>();
            file1.Setup(d => d.FileName).Returns("AudioSingle.33.xml");
            file1.Setup(d => d.InputStream).Returns(new MemoryStream(enc.GetBytes(Resources.AudioSingle_33)));
            file1.Setup(d => d.ContentLength).Returns(enc.GetBytes(Resources.AudioSingle_33).Length);

            context.Setup(x => x.HttpContext.Request).Returns(request.Object);
            context.Setup(x => x.HttpContext.Server).Returns(server.Object);
            context.Setup(x => x.HttpContext.Request.Files.Count).Returns(1);
            context.Setup(x => x.HttpContext.Request.Files[0]).Returns(file1.Object);
            controller.ControllerContext = context.Object;
            validator.Setup(x => x.Transform(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns("");

            // Act
            var result = controller.ValidateDdex("Audio Single", "10", xmlMessage) as ViewResult;

            // Assert
            Assert.IsNotNull(result);
        }
Beispiel #4
0
        public string Encrypt(string message)
        {
            byte[] results;
            UTF8Encoding utf8 = new UTF8Encoding();
            //to create the object for UTF8Encoding  class
            //TO create the object for MD5CryptoServiceProvider
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] deskey = md5.ComputeHash(utf8.GetBytes(Passphrase));
            //to convert to binary passkey
            //TO create the object for  TripleDESCryptoServiceProvider
            TripleDESCryptoServiceProvider desalg = new TripleDESCryptoServiceProvider();
            desalg.Key = deskey;//to  pass encode key
            desalg.Mode = CipherMode.ECB;
            desalg.Padding = PaddingMode.PKCS7;
            byte[] encryptData = utf8.GetBytes(message);
            //to convert the string to utf encoding binary

            try
            {

                //To transform the utf binary code to md5 encrypt
                ICryptoTransform encryptor = desalg.CreateEncryptor();
                results = encryptor.TransformFinalBlock(encryptData, 0, encryptData.Length);

            }
            finally
            {
                //to clear the allocated memory
                desalg.Clear();
                md5.Clear();
            }
            //to convert to 64 bit string from converted md5 algorithm binary code
            return Convert.ToBase64String(results);
        }
 public string EncryptString(string message)
 {
     byte[] results;
     var utf8 = new UTF8Encoding();
     var hashProvider = new MD5CryptoServiceProvider();
     var tdesKey = hashProvider.ComputeHash(utf8.GetBytes(secrectKey));
     var tdesAlgorithm = new TripleDESCryptoServiceProvider
     {
         Key = tdesKey,
         Mode = CipherMode.ECB,
         Padding = PaddingMode.PKCS7
     };
     var dataToEncrypt = utf8.GetBytes(message);
     try
     {
         var encryptor = tdesAlgorithm.CreateEncryptor();
         results = encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
     }
     finally
     {
         tdesAlgorithm.Clear();
         hashProvider.Clear();
     }
     return Convert.ToBase64String(results);
 }
        public static string Encrypt(string message)
        {
            byte[] results;
            UTF8Encoding utf8 = new UTF8Encoding();

            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] deskey = md5.ComputeHash(utf8.GetBytes(passphrase));

            TripleDESCryptoServiceProvider desalg = new TripleDESCryptoServiceProvider();
            desalg.Key = deskey;//to  pass encode key
            desalg.Mode = CipherMode.ECB;
            desalg.Padding = PaddingMode.PKCS7;
            byte[] encrypt_data = utf8.GetBytes(message);
            try
            {
                ICryptoTransform encryptor = desalg.CreateEncryptor();
                results = encryptor.TransformFinalBlock(encrypt_data, 0, encrypt_data.Length);
            }
            finally
            {
                desalg.Clear();
                md5.Clear();
            }
            return Convert.ToBase64String(results);
        }
Beispiel #7
0
        public static string GetDecryptedText(string EncryptedString)
        {
            string sdec = "";
            try
            {
                string smsg = EncryptedString;

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                System.Text.Encoding utf = new System.Text.UTF8Encoding();

                byte[] key = utf.GetBytes("12348765");
                byte[] iv ={ 1, 2, 3, 4, 8, 7, 6, 5 };

                ICryptoTransform decryptor = des.CreateDecryptor(key, iv);

                byte[] bmsg = utf.GetBytes(smsg);

                byte[] benc1 = System.Convert.FromBase64String(EncryptedString);
                byte[] bdec = decryptor.TransformFinalBlock(benc1, 0, benc1.Length);
                sdec = utf.GetString(bdec);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            return sdec;
        }
Beispiel #8
0
 private string GetSignature (string canonicalString)
 {
     Encoding ae = new UTF8Encoding();
     HMACSHA1 signature = new HMACSHA1(ae.GetBytes(m_awsSecretKey));
     string b64 = Convert.ToBase64String(signature.ComputeHash(ae.GetBytes(canonicalString.ToCharArray())));
     return HttpUtility.UrlEncode(b64);
 }
Beispiel #9
0
		/// <summary>
		/// Creates a signature useful in making GoBucket requests. It automatically includes the secret key
		/// as the first item in the sigature, and the date.
		/// </summary>
		/// <param name="verb">VERB for this REST call</param>
		/// <param name="endpoint">The endpoint name being called</param>
		/// <param name="ingredients">Items to include to generate the signature</param>
		public string CreateSignature(string verb, string endpoint, IEnumerable<string> ingredients=null) {
			var encoding = new System.Text.UTF8Encoding();
			byte[] secretKeyBytes = encoding.GetBytes(this.secretKey);
			var algorithm = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha256);

			StringBuilder fullContents = new StringBuilder();
			fullContents.Append(this.secretKey);
			fullContents.Append(verb);
			fullContents.Append(DateTime.UtcNow.ToString("yyyy-MM-dd"));
			fullContents.Append(endpoint);

			if (ingredients != null) {
				foreach (string ingredient in ingredients) {
					fullContents.Append(ingredient);
				}
			}

			byte[] contentBytes = encoding.GetBytes(fullContents.ToString());

			using (CryptographicHash hasher = algorithm.CreateHash(secretKeyBytes)) {
				hasher.Append(contentBytes);
				byte[] hashedContents = hasher.GetValueAndReset();
				return Convert.ToBase64String(hashedContents);
			}
		}
Beispiel #10
0
        public static String read(byte[] cypher, string KeyString, string IVString)
        {
            var sRet = "";

            var encoding = new UTF8Encoding();
            var Key = encoding.GetBytes(KeyString);
            var IV = encoding.GetBytes(IVString);

            using (var rj = new RijndaelManaged())
            {
                try
                {
                    rj.Padding = PaddingMode.PKCS7;
                    rj.Mode = CipherMode.CBC;
                    rj.KeySize = 256;
                    rj.BlockSize = 256;
                    rj.Key = Key;
                    rj.IV = IV;
                    var ms = new MemoryStream(cypher);

                    using (var cs = new CryptoStream(ms, rj.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
                    {
                        using (var sr = new StreamReader(cs))
                        {
                            sRet = sr.ReadLine();
                        }
                    }
                }
                finally
                {
                    rj.Clear();
                }
            }
            return sRet;
        }
        private string GenerateSignature(string httpMethod, string secret, string apiUrl, string parameters)
        {
            string encodedUrl = UrlHelper.Encode(apiUrl);
            string encodedParameters = UrlHelper.Encode(parameters);

            //generate the basestring
            string basestring = httpMethod + "&" + encodedUrl + "&" + encodedParameters;

            //hmac-sha1 encryption:
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

            //create key (request_token can be an empty string)
            string key = consumerSecret + "&" + secret;
            byte[] keyByte = encoding.GetBytes(key);

            //create message to encrypt
            byte[] messageBytes = encoding.GetBytes(basestring);

            //encrypt message using hmac-sha1 with the provided key
            HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);
            byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);

            //signature is the base64 format for the genarated hmac-sha1 hash
            string signature = System.Convert.ToBase64String(hashmessage);

            //encode the signature to make it url safe and return the encoded url
            return UrlHelper.Encode(signature);
        }
        public static string EncryptData(string Message)
        {
            byte[] Results;
            string passphrase = ReadCert();

            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;
            byte[] DataToEncrypt = UTF8.GetBytes(Message);
            try
            {
                ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
                Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
            }
            finally
            {
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }
            return Convert.ToBase64String(Results);
        }
 public static string SignAndEncode(string value, string sharedKey)
 {
     MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
     UTF8Encoding utf8 = new UTF8Encoding();
     string signature = BytesToHexString(md5.ComputeHash(utf8.GetBytes(sharedKey + value)));
     string hexString = BytesToHexString(utf8.GetBytes(value));
     return signature + hexString;
 }
 public static string Hash(string key, string message)
 {
     UTF8Encoding encoding = new UTF8Encoding();
     var messageBytes = encoding.GetBytes(message);
     var md5Hasher = new HMACMD5(encoding.GetBytes(key));
     var hashBytes = md5Hasher.ComputeHash(messageBytes);
     return new string(hashBytes.SelectMany(b => b.ToString("X2")).ToArray()).ToLower();
 }
        public static String sign(String data, String secretKey)
        {
            UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] keyByte = encoding.GetBytes(secretKey);

            HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);
            byte[] messageBytes = encoding.GetBytes(data);
            return Convert.ToBase64String(hmacsha256.ComputeHash(messageBytes));
        }
Beispiel #16
0
 private void button1_Click(object sender, EventArgs e)
 {
     MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
     SHA1CryptoServiceProvider sh1 = new SHA1CryptoServiceProvider();
     UTF8Encoding utf8 = new UTF8Encoding();
     string s = BitConverter.ToString(md5.ComputeHash(utf8.GetBytes(textBox1.Text)));
     string s2 = BitConverter.ToString(sh1.ComputeHash(utf8.GetBytes(textBox1.Text)));
     MessageBox.Show(s + Environment.NewLine + s2);
 }
        /// <summary>
        /// Calculates the HMAC256 string based on the given string and secret access key.
        /// </summary>
        /// <param name="stringToSign">The string to sign.</param>
        /// <param name="secretAccessKey">The secret access key to sign the string with.</param>
        /// <returns>The calculated HMAC256 string.</returns>
        private static string CalculateHMAC256(string stringToSign, string secretAccessKey)
        {
            UTF8Encoding encoding = new UTF8Encoding();

            HMACSHA256 hmac = new HMACSHA256(encoding.GetBytes(secretAccessKey));
            byte[] hash = hmac.ComputeHash(encoding.GetBytes(stringToSign));

            return Convert.ToBase64String(hash);
        }
 private static string ComputeDigest(string message, string secret)
 {
     var encoding = new UTF8Encoding();
     using (var hmacsha256 = new HMACSHA256(encoding.GetBytes(secret)))
     {
         var hashedMessage = hmacsha256.ComputeHash(encoding.GetBytes(message));
         return Convert.ToBase64String(hashedMessage);
     }
 }
Beispiel #19
0
 //
 // Static Methods
 // This code was taken directly from Security:: in Assembly-CSharp.dll found in pocketmine.apk/assets/data/Managed/...
 // That dll was disassembled with monodis
 public static string ComputeHash(string message)
 {
     UTF8Encoding uTF8Encoding = new UTF8Encoding ();
     byte[] bytes = uTF8Encoding.GetBytes (secret);
     HMACSHA1 hMACSHA = new HMACSHA1 (bytes);
     byte[] bytes2 = uTF8Encoding.GetBytes (message);
     byte[] array = hMACSHA.ComputeHash (bytes2);
     return Convert.ToBase64String (array);
 }
Beispiel #20
0
        protected XmlDictionaryReader ProcessRequest(String request)
        {
            _action = request;
            String r = "";

            if (_connectionOptions.Region != Region.CN && _connectionOptions.IsSecure)
                r = String.Format(_httpsApiUrl, _connectionOptions.Region.ToString().ToLower(), _controller, _action);
            else if (_connectionOptions.Region != Region.CN)
                r = String.Format(_apiUrl, _connectionOptions.Region.ToString().ToLower(), _controller, _action);
            else if (_connectionOptions.Region == Region.CN && _connectionOptions.IsSecure)
                r = String.Format(_httpsCnApiUrl, _controller, _action);
            else
                r = String.Format(_cnApiUrl, _controller, _action);

            _wr = WebRequest.Create(r);

            if (_connectionOptions.AuthenticationOptions.IsAuthenticated)
            {
                BattlenetAuthenticationOptions authOptions = _connectionOptions.AuthenticationOptions;
                DateTime currentTime = DateTime.UtcNow;
                String stringToSign = _wr.Method + "\n" + currentTime.ToString("R") + "\n" + r + "\n"; // from wow-api-docs
                UTF8Encoding encoding = new UTF8Encoding();
                byte[] bytesToSign =  encoding.GetBytes(stringToSign);
                HMACSHA1 hasher = new HMACSHA1(encoding.GetBytes(authOptions.PrivateKey));
                hasher.ComputeHash(bytesToSign);
                String auth = String.Format("BNET {0}:{1}", authOptions.PublicKey, Convert.ToBase64String(hasher.Hash));
                _wr.Headers.Set(HttpRequestHeader.Authorization, auth);
            }
            XmlDictionaryReader xdr = null;

            try
            {
                HttpWebResponse wres = (HttpWebResponse)_wr.GetResponse();

                xdr = JsonReaderWriterFactory.CreateJsonReader(wres.GetResponseStream(), new XmlDictionaryReaderQuotas());
            }
            catch (WebException ex)
            {
                XmlDictionaryReader x = JsonReaderWriterFactory.CreateJsonReader(ex.Response.GetResponseStream(), new XmlDictionaryReaderQuotas());
                HttpStatusCode code = ((HttpWebResponse)ex.Response).StatusCode;
                String m = null;
                if (code == HttpStatusCode.ServiceUnavailable)
                {
                    m = "Service temporarily unavailable";
                }
                else if (code == HttpStatusCode.InternalServerError)
                {
                    m = XElement.Load(x).Element("reason").Value;
                }
                BattlenetConnectionException e = new BattlenetConnectionException(m, code);

                throw e;
            }

            return xdr;
        }
 public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
 {
     UTF8Encoding encoding = new UTF8Encoding(false);
     byte[] bytes = encoding.GetBytes(" " + this.Name + "=\"");
     hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
     bytes = encoding.GetBytes(System.Security.Cryptography.Xml.Utils.EscapeAttributeValue(this.Value));
     hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
     bytes = encoding.GetBytes("\"");
     hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
 }
Beispiel #22
0
 public static string Calculate(string data, string secret)
 {
     var encoding = new System.Text.UTF8Encoding();
     byte[] keyByte = encoding.GetBytes(secret);
     byte[] messageBytes = encoding.GetBytes(data);
     using (var hmacsha = new HMACSHA1(keyByte))
     {
         byte[] hashmessage = hmacsha.ComputeHash(messageBytes);
         return HexEncode(hashmessage).ToLower();
     }
 }
Beispiel #23
0
        private string GetHash(string password)
        {
            const string key = "key";
            var encoding = new UTF8Encoding();

            using (var hasher = new HMACSHA256(encoding.GetBytes(key)))
            {
                var hashedBytes = hasher.ComputeHash(encoding.GetBytes(password));
                return BytesToHex(hashedBytes);
            }
        }
Beispiel #24
0
        /// <summary>
        /// Creates a Sha512 HMAC hash of an inputted string.
        /// </summary>
        /// <param name="input">The string to create the hash from.</param>
        internal static string ComputeHmacSha512Hash(string input, string secret)
        {
            var utf8Encoding = new UTF8Encoding();
            var inputBytes = utf8Encoding.GetBytes(input);
            var secretBytes = utf8Encoding.GetBytes(secret);

            var hmacSha512 = new HMACSHA512(secretBytes);
            var hash = hmacSha512.ComputeHash(inputBytes);

            return BitConverter.ToString(hash).Replace("-", "");
        }
Beispiel #25
0
        public static byte[] hash_hmac_sha256(String message, String secret)
        {
            secret = secret ?? "";

            var encoding = new System.Text.UTF8Encoding();
            byte[] keyByte = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);
            var hmacsha256 = new HMACSHA256(keyByte);
            byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
            return hashmessage;
        }
Beispiel #26
0
 /// <summary>
 /// Encrypts the string to a byte array using the MD5 Encryption 
 /// Algorithm with an additional Salted Hash.
 /// <see cref="System.Security.Cryptography.MD5CryptoServiceProvider"/>
 /// </summary>
 /// <param name="ToEncrypt">System.String.  Usually a password.</param>
 /// <returns>System.Byte[]</returns>
 public static byte[] MD5SaltedHashEncryption(string ToEncrypt)
 {
     MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
     byte[] hashedbytes;
     byte[] saltedhash;
     UTF8Encoding textencoder = new UTF8Encoding();
     hashedbytes = md5.ComputeHash(textencoder.GetBytes(ToEncrypt));
     ToEncrypt += textencoder.GetString(hashedbytes);
     saltedhash = md5.ComputeHash(textencoder.GetBytes(ToEncrypt));
     md5.Clear();
     return saltedhash;
 }
Beispiel #27
0
 private void button1_Click(object sender, EventArgs e)
 {
     MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
     UTF8Encoding utf8 = new UTF8Encoding();
     TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
     tDes.Key = md5.ComputeHash(utf8.GetBytes(textBox1.Text));
     tDes.Mode = CipherMode.ECB;
     tDes.Padding = PaddingMode.PKCS7;
     ICryptoTransform trans = tDes.CreateEncryptor();
     encrypted = trans.TransformFinalBlock(utf8.GetBytes(textBox2.Text), 0, utf8.GetBytes(textBox2.Text).Length);
     textBox3.Text = BitConverter.ToString(encrypted);
 }
Beispiel #28
0
        /// <summary>
        /// 由于RSA的rgb参数不能超过字符串长度为117,进行分截加密,获取公钥
        /// </summary>
        /// <param name="str">The STR.</param>
        /// <returns></returns>
        public static string RSAEncrypt(string str, string publcikeypath)
        {
            string ls_str = string.Empty;
            string ls_temp = string.Empty;
            string ls_encrypt_str = string.Empty;
            string publickey;
            byte[] byte_encrypt;
            int ll_num = 0;
            ls_str = str;
            System.Text.Encoding utf8 = new System.Text.UTF8Encoding();
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            try
            {
                StreamReader reader = new StreamReader(publcikeypath);
                publickey = reader.ReadToEnd();
                RSA.FromXmlString(publickey);
            }
            catch (Exception ex)
            {
                MessageBox.Show("加密文件没有在当前执行目录:" + ex.Message);
                return string.Empty;
            }

            if (ls_str == string.Empty || ls_str == "")
                return ls_encrypt_str;
            do
            {
                if (ls_str.Length > 100)
                {
                    ls_temp = ls_str.Substring(0, 100);
                    ls_str = ls_str.Substring(100);
                    byte_encrypt = utf8.GetBytes(ls_temp);
                    byte_encrypt = RSA.Encrypt(byte_encrypt, false);
                    ls_temp = System.Convert.ToBase64String(byte_encrypt);
                    ll_num = ll_num + 1;
                    ls_encrypt_str = ls_encrypt_str + "<" + ll_num.ToString() + ">" + ls_temp + "</" + ll_num.ToString() + ">";
                }
                else
                {
                    ls_temp = ls_str;
                    byte_encrypt = utf8.GetBytes(ls_temp);
                    byte_encrypt = RSA.Encrypt(byte_encrypt, false);
                    ls_temp = System.Convert.ToBase64String(byte_encrypt);
                    ll_num = ll_num + 1;
                    ls_encrypt_str = ls_encrypt_str + "<" + ll_num.ToString() + ">" + ls_temp + "</" + ll_num.ToString() + ">";
                    break;
                }

            } while (2 > 1);
            return ls_encrypt_str;

        }
Beispiel #29
0
 public byte[] ReadBytes(bool isBom)
 {
     if (string.IsNullOrEmpty(Content))
     {
         return Data;
     }
     UTF8Encoding WithBOM = new System.Text.UTF8Encoding(isBom);
     if (isBom)
     {
         return BufferUtils.MergeBytes(new byte[] { 0xEF, 0xBB, 0xBF }, WithBOM.GetBytes(Content));
     }
     return WithBOM.GetBytes(Content);
 }
Beispiel #30
0
        public static string GetHASMString(string content) 
        {
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] keyBytes = encoding.GetBytes(AppSettings.HashKey); 
            byte[] messageBytes = encoding.GetBytes(content); 

            HMACSHA256 hmacsha256 = new HMACSHA256(keyBytes); 

            byte[] hashmessage = hmacsha256.ComputeHash(messageBytes); 
            string hmac3 = ByteToString(hashmessage); 

            return hmac3; 
        }
        /// <summary>
        /// Encrypts a string
        /// </summary>
        /// <param name="stringToEncrypt">String to encrypt</param>
        /// <param name="encryptionKey">Key used to encrypt</param>
        /// <returns>Encrypted string</returns>
        public static string EncryptString(string stringToEncrypt, string encryptionKey)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();

            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(encryptionKey));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the encoder
            TDESAlgorithm.Key     = TDESKey;
            TDESAlgorithm.Mode    = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]
            byte[] DataToEncrypt = UTF8.GetBytes(stringToEncrypt);

            // Step 5. Attempt to encrypt the string
            try {
                ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
                Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
            } finally {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            // Step 6. Return the encrypted string as a base64 encoded string
            return(Convert.ToBase64String(Results));
        }
        private ResultDTO POST(string url, MachineLearningDTO datas)
        {
            string         resultStream = "";
            HttpWebRequest request      = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "POST";

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            var jsonContent = JsonConvert.SerializeObject(datas);

            Byte[] byteArray = encoding.GetBytes(jsonContent);

            request.ContentLength = byteArray.Length;
            request.ContentType   = "application/json";

            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }
            long length = 0;

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    // got response

                    length = response.ContentLength;

                    using (Stream responseStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                        resultStream = reader.ReadToEnd();
                        return(JsonConvert.DeserializeObject <ResultDTO>(resultStream));
                    }
                }
            }
            catch (WebException ex)
            {
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    resultStream = reader.ReadToEnd();
                    return(JsonConvert.DeserializeObject <ResultDTO>(resultStream));
                }
                throw;
            }
        }
Beispiel #33
0
        private void btnDHaz_Click(object sender, EventArgs e)
        {
            text = txtIn.Text.ToUpper();
            Encoding encoding = new System.Text.UTF8Encoding();

            txtOut.Clear();
            int len = text.Length;

            byte[] textB = encoding.GetBytes(text);
            text = BitConverter.ToString(textB);
            text = txtIn.Text.ToUpper();
            text = text.ToString().Replace("-", "");
            text = text.Replace("A", "2" + H4ZKey);
            text = text.Replace("B", "22" + H4ZKey);
            text = text.Replace("C", "222" + H4ZKey);
            text = text.Replace("D", "3" + H4ZKey);
            text = text.Replace("E", "33" + H4ZKey);
            text = text.Replace("F", "333" + H4ZKey);
            text = text.Replace("G", "4" + H4ZKey);
            text = text.Replace("H", "44" + H4ZKey);
            text = text.Replace("I", "444" + H4ZKey);
            text = text.Replace("J", "5" + H4ZKey);
            text = text.Replace("K", "55" + H4ZKey);
            text = text.Replace("L", "555" + H4ZKey);
            text = text.Replace("M", "6" + H4ZKey);
            text = text.Replace("N", "66" + H4ZKey);
            text = text.Replace("O", "666" + H4ZKey);
            text = text.Replace("P", "7" + H4ZKey);
            text = text.Replace("Q", "77" + H4ZKey);
            text = text.Replace("R", "777" + H4ZKey);
            text = text.Replace("S", "7777" + H4ZKey);
            text = text.Replace("T", "8" + H4ZKey);
            text = text.Replace("U", "88" + H4ZKey);
            text = text.Replace("V", "888" + H4ZKey);
            text = text.Replace("W", "9" + H4ZKey);
            text = text.Replace("X", "99" + H4ZKey);
            text = text.Replace("Y", "999" + H4ZKey);
            text = text.Replace("Z", "9999" + H4ZKey);
            text = text.Replace(" ", "0" + H4ZKey);
            //text = text.Replace(".", "00" + H4ZKey);
            //encoding = new System.Text.UTF8Encoding();
            //txtOut.Clear();
            //len = text.Length;
            //textB = encoding.GetBytes(text);
            //text = BitConverter.ToString(textB);
            //text = text.ToString().Replace("-", "");
            text        = text.ToLower();
            txtOut.Text = text;
        }
Beispiel #34
0
        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            try
            {
                //Console.WriteLine(sender);
                dtPlan  selectedPlan = Shift1Dgv.SelectedItem as dtPlan;
                dynamic postApiBody  = new JObject();
                postApiBody.timeWorkId      = 0;
                postApiBody.activeDate      = selectedPlan.activeDate;
                postApiBody.deviceId        = selectedPlan.deviceId;
                postApiBody.productId       = selectedPlan.productId;
                postApiBody.productDetailId = selectedPlan.productDetailId;
                postApiBody.updUsrId        = 1;
                postApiBody.palletAmount    = 1;
                string jsonData = JsonConvert.SerializeObject(postApiBody);
                //Console.WriteLine(jsonData);

                HttpWebRequest request =
                    (HttpWebRequest)WebRequest.Create(@"http://" +
                                                      Properties.Settings.Default.serverIp + ":" +
                                                      Properties.Settings.Default.serverPort +
                                                      @"/robot/rest/" + "plan/createPlanPallet");

                request.Method      = "POST";
                request.ContentType = "application/json";

                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                Byte[] byteArray = encoding.GetBytes(jsonData);
                request.ContentLength = byteArray.Length;
                using (Stream dataStream = request.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Flush();
                }

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    int          result = 0;
                    int.TryParse(reader.ReadToEnd(), out result);
                    Console.WriteLine("PalletId=" + result);
                }
            }
            catch (Exception ex)
            {
                logFile.Error(ex.Message);
            }
        }
Beispiel #35
0
        //POST json data to value
        private static string PostEncodedValueToAPI(string guid, string encodedValue, string algorithmName)
        {
            PostEncodedValueRequest postValues = new PostEncodedValueRequest();

            postValues.emailAddress = "*****@*****.**";
            postValues.encodedValue = encodedValue;
            postValues.name         = "Moises David Martinez Padilla";
            postValues.repoUrl      = "https://github.com/moisesmartinez/AADevChallenge";
            postValues.webhookUrl   = "http://aawebhookhandler.apphb.com/WebhookHandler";

            //Create json string
            string jsonContent = JsonConvert.SerializeObject(postValues);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(postEncodedValueURL, guid, algorithmName));

            request.Method      = "POST";
            request.ContentType = "application/json";
            request.Accept      = "application/json";

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(jsonContent);

            request.ContentLength = byteArray.Length;

            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }
            long length = 0;

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    length = response.ContentLength;

                    using (Stream responseStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                        return(reader.ReadToEnd());
                    }
                }
            }
            catch (WebException ex)
            {
                // Log exception and throw as for GET example above
                throw;
            }
        }
Beispiel #36
0
        public static String PostAPISMSGateway(String url, String jsonContent)
        {
            String Result = "";

            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "POST";

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(jsonContent);

            request.ContentLength = byteArray.Length;
            request.ContentType   = @"application/x-www-form-urlencoded";

            try
            {
                using (Stream dataStream = request.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                }
                long length = 0;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    length = response.ContentLength;
                    Stream responseStream = response.GetResponseStream();
                    var    streamReader   = new StreamReader(responseStream);
                    Result = streamReader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                Result = ex.ToString();

                using (WebResponse response = ex.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;
                    Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                    using (Stream data = response.GetResponseStream())
                        using (var reader = new StreamReader(data))
                        {
                            // text is the response body
                            string text = reader.ReadToEnd();
                        }
                }
            }

            return(Result);
        }
Beispiel #37
0
        private WorkflowInstance createWorkflowFormXomlString(string xomlstring, string rulesstring, Dictionary <string, object> list)
        {
            Guid guid = Guid.NewGuid();

            try
            {
                System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();

                byte[] a = utf8.GetBytes(rulesstring);

                System.IO.MemoryStream m1 = new System.IO.MemoryStream(a);

                XmlReader rules = XmlReader.Create(m1);

                byte[] b = utf8.GetBytes(xomlstring);

                System.IO.MemoryStream m2 = new System.IO.MemoryStream(b);

                XmlReader xoml = XmlReader.Create(m2);

                System.Workflow.Runtime.WorkflowInstance instance;

                instance = wfRuntime.CreateWorkflow(xoml, rules, list, guid);
                if (instance != null)
                {
                    instance.Start();
                }

                return(instance);
            }
            catch (System.Workflow.ComponentModel.Compiler.WorkflowValidationFailedException ex)
            {
                System.Console.WriteLine("err:" + ex.Message);
                return(null);
            }
        }
        /// <summary>
        /// <para>
        /// <param name="value">string</param>
        /// </para>
        /// DeserializeFromXml
        /// <example> Truc T = CToXmlString.DeserializeFromXml(" xml ");</example>///
        /// <returns>T</returns>
        /// </summary>
        public static T DeserializeFromXml <T>(string value)
        {
            T             result;
            MemoryStream  memStream    = new MemoryStream();
            XmlSerializer mySerializer = new XmlSerializer(typeof(T));

            System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
            byte[] bytearray             = enc.GetBytes(value);
            memStream.Write(bytearray, 0, bytearray.Length);
            memStream.Seek(0, System.IO.SeekOrigin.Begin);
            result       = (T)mySerializer.Deserialize(memStream);
            memStream    = null;
            mySerializer = null;
            return(result);
        }
        public static Uri GetHmacedUri(string uri, string key, string[] paramsToVerify)
        {
            UriBuilder          result         = new UriBuilder(uri);
            NameValueCollection param          = HttpUtility.ParseQueryString(result.Query);
            NameValueCollection verifiedParams = HttpUtility.ParseQueryString(string.Empty);

            foreach (string str in paramsToVerify)
            {
                verifiedParams[str] = HttpUtility.UrlEncode(param[str]);
            }

            string pathAndQuery = result.Path + "?" + verifiedParams.ToString();

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[]     keyByte    = encoding.GetBytes(key);
            HMACSHA512 hmacsha512 = new HMACSHA512(keyByte);

            byte[] computeHash = hmacsha512.ComputeHash(encoding.GetBytes(pathAndQuery));
            string hash        = BitConverter.ToString(computeHash).Replace("-", string.Empty).ToLower();

            verifiedParams["hmac"] = hash;
            result.Query           = verifiedParams.ToString();
            return(result.Uri);
        }
Beispiel #40
0
        public async Task PostTicket()
        {
            string data = "testing the client";

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] bytes = encoding.GetBytes(data);

            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri("http://test.colpipe.com/T4TestWebApi/");
            var content = new ByteArrayContent(bytes);
            var t       = await client.PostAsync("/api/Tickets", content);

            var tt = t.RequestMessage.Content.ToString();
        }
Beispiel #41
0
        public static string getEncCredentials(string username, string password, string domain)
        {
            string strDomain   = domain;
            string strUsername = username;
            string strPassword = password;

            string strRawCredentials = strDomain + "\\" + strUsername + ":" + strPassword;

            //Need to base64 encode the credentials
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteSource        = encoding.GetBytes(strRawCredentials);
            string strEncCredentials = System.Convert.ToBase64String(byteSource);

            return(strEncCredentials);
        }
Beispiel #42
0
        /// <summary>
        /// Método responsável por converter uma String contendo a estrutura de um XML em um XMLDocument
        /// </summary>
        /// <returns>XMLDocument com o retorno</returns>
        internal static XmlDocument StringXmlToXMLDocument(string strXml)
        {
            byte[] byteArray = new byte[strXml.Length];
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byteArray = encoding.GetBytes(strXml);
            MemoryStream memoryStream = new MemoryStream(byteArray);

            memoryStream.Seek(0, SeekOrigin.Begin);

            XmlDocument xml = new XmlDocument();

            xml.Load(memoryStream);

            return(xml);
        }
Beispiel #43
0
        public string Hash()
        {
            var email       = Email.Trim().ToLower();
            var encoder     = new System.Text.UTF8Encoding();
            var md5         = new System.Security.Cryptography.MD5CryptoServiceProvider();
            var hashedBytes = md5.ComputeHash(encoder.GetBytes(email));
            var sb          = new System.Text.StringBuilder(hashedBytes.Length * 2);

            for (var i = 0; i < hashedBytes.Length; i++)
            {
                sb.Append(hashedBytes[i].ToString("X2"));
            }

            return(sb.ToString().ToLower());
        }
Beispiel #44
0
        public static nfs_argop4 generateRequest(String path)
        {
            REMOVE4args args = new REMOVE4args();

            args.target = new component4();
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            args.target.value = new utf8str_cs(new utf8string(encoding.GetBytes(path)));

            nfs_argop4 op = new nfs_argop4();

            op.argop    = nfs_opnum4.OP_REMOVE;
            op.opremove = args;

            return(op);
        }
        /// <summary>
        /// Extension method for encrypting a string to its MD5 equivalent.  Saltless.
        /// </summary>
        /// <param name="strToEncrypt">The STR to encrypt.</param>
        /// <returns></returns>
        public static string ToMd5(this string strToEncrypt)
        {
            System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
            byte[] bytes = ue.GetBytes(strToEncrypt);

            // encrypt bytes
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            byte[] hashBytes = md5.ComputeHash(bytes);

            // Convert the encrypted bytes back to a string (base 16)
            string hashString = hashBytes.Aggregate("", (current, t) => current + Convert.ToString(t, 16).PadLeft(2, '0'));

            return(hashString.PadLeft(32, '0'));
        }
Beispiel #46
0
        public string getToken()
        {
            SpotifyTokenClass token = new SpotifyTokenClass();
            string            url5  = "https://accounts.spotify.com/api/token";
            var clientid            = "ac2334eae23a489b98e2add0def561cb";
            var clientsecret        = "4a8e15146f2c412cb8ce5de158e77522";

            //request to get the access token
            var encode_clientid_clientsecret = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", clientid, clientsecret)));

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url5);

            webRequest.Method      = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Accept      = "application/json";
            webRequest.Headers.Add("Authorization: Basic " + encode_clientid_clientsecret);

            var request = ("grant_type=client_credentials");

            byte[] req_bytes = Encoding.ASCII.GetBytes(request);
            webRequest.ContentLength = req_bytes.Length;

            Stream strm = webRequest.GetRequestStream();

            strm.Write(req_bytes, 0, req_bytes.Length);
            strm.Close();

            HttpWebResponse            resp           = (HttpWebResponse)webRequest.GetResponse();
            String                     json           = "";
            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(SpotifyTokenClass));

            using (Stream respStr = resp.GetResponseStream())
            {
                using (StreamReader rdr = new StreamReader(respStr, Encoding.UTF8))
                {
                    //should get back a string i can then turn to json and parse for accesstoken
                    json = rdr.ReadToEnd();
                    rdr.Close();
                }
            }
            System.Text.Encoding _encodingWeb = new System.Text.UTF8Encoding();
            MemoryStream         ms           = new MemoryStream(_encodingWeb.GetBytes(json));
            SpotifyTokenClass    oRootObject  = (SpotifyTokenClass)jsonSerializer.ReadObject(ms);

            _currentToken = oRootObject.token_type + " " + oRootObject.access_token;

            return(_currentToken);
        }
        /// <summary>
        /// Encrypt some text and return an encrypted byte array.
        /// </summary>
        /// <param name="TextValue"></param>
        /// <returns></returns>
        private static byte[] Encrypt(string TextValue)
        {
            byte[] encrypted = null;

            try
            {
                if (TextValue == null)
                {
                    return(null);
                }
                lock (_locker_encrypt)
                {
                    //Translates our text value into a byte array.
                    Byte[] bytes = UTFEncoder.GetBytes(TextValue);

                    //Used to stream the data in and out of the CryptoStream.
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        /*
                         * We will have to write the unencrypted bytes to the stream,
                         * then read the encrypted result back from the stream.
                         */
                        #region Write the decrypted value to the encryption stream
                        using (CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write))
                        {
                            cs.Write(bytes, 0, bytes.Length);
                            cs.FlushFinalBlock();
                            #endregion

                            #region Read encrypted value back out of the stream
                            memoryStream.Position = 0;
                            encrypted             = new byte[memoryStream.Length];
                            memoryStream.Read(encrypted, 0, encrypted.Length);
                            #endregion

                            //Clean up.
                            cs.Close();
                            memoryStream.Close();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "TextValue = " + TextValue);
            }
            return(encrypted);
        }
Beispiel #48
0
        // POST a JSON string
        public static string Post(string url, string jsonContent)
        {
            url = GetCompleteUrl(url);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "POST";

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(jsonContent);

            request.ContentLength = byteArray.Length;
            request.ContentType   = @"application/json";

            try
            {
                using (Stream dataStream = request.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                }
                try
                {
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        using (Stream responseStream = response.GetResponseStream())
                        {
                            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                            return(reader.ReadToEnd());
                        }
                    }
                }
                catch (WebException ex)
                {
                    using (Stream responseStream = ex.Response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                        return("*" + reader.ReadToEnd());
                    }

                    throw;
                }
            }
            catch (Exception ex)
            {
                //recordLog.WriteLogFile(ex.ToString());
                return("*" + ex.Message);
            }
        }
        public string Requete(string command, string value = "", string value2 = "")
        {
            string         url     = string.Format("http://{0}/jsonrpc.js", PackageHost.GetSettingValue("ServerUrl"));
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            if (PackageHost.TryGetSettingValue <string>("ServerUser", out string user))
            {
                if (PackageHost.TryGetSettingValue <string>("ServerPassword", out string password))
                {
                    string credentials = string.Format("{0}:{1}", PackageHost.GetSettingValue("ServerUser"), PackageHost.GetSettingValue("ServerPassword"));
                    request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
                    request.PreAuthenticate = true;
                }
                else
                {
                    PackageHost.WriteError("Impossible de récupérer le setting 'Password' en string");
                }
            }
            request.Method      = "POST";
            request.ContentType = @"application/json";
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(command);
            request.ContentLength = byteArray.Length;
            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        return(reader.ReadToEnd());
                    }
                }
            }
            catch (WebException ex)
            {
                using (var errorResponse = (HttpWebResponse)ex.Response)
                {
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        return(reader.ReadToEnd());
                    }
                }
            }
        }
        public static string DecryptString(string Message)
        {
            string Passphrase = "atec";

            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();

            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the decoder
            TDESAlgorithm.Key     = TDESKey;
            TDESAlgorithm.Mode    = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]

            Message = Message.Replace("KKK", "+");
            Message = Message.Replace("JJJ", "/");
            Message = Message.Replace("III", "\\");


            byte[] DataToDecrypt = Convert.FromBase64String(Message);

            // Step 5. Attempt to decrypt the string
            try
            {
                ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            // Step 6. Return the decrypted string in UTF8 format
            return(UTF8.GetString(Results));
        }
Beispiel #51
0
        private KeyValuePair <bool, string> CallAPI(string data)
        {
            KeyValuePair <bool, string> result = new KeyValuePair <bool, string>(true, string.Empty);
            HttpWebRequest request             = (HttpWebRequest)WebRequest.Create(apiUrl);

            request.Timeout = 6000;
            request.Headers.Add("auth-token", apiToken);
            request.Method = "POST";

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(data);

            request.ContentLength = byteArray.Length;
            request.ContentType   = @"application/json";

            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                        result = new KeyValuePair <bool, string>(true, reader.ReadToEnd());
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null && ((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.BadRequest)
                {
                    using (Stream stream = ex.Response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                        result = new KeyValuePair <bool, string>(false, reader.ReadToEnd());
                    }
                }
                else
                {
                    throw ex;
                }
            }
            return(result);
        }
    public string checkStatusss(string orderId)
    {
        //string url = "https://stage-secure-gateway.hipay-tpp.com/rest/v1/transaction?orderid="+orderId;
        string url = "http://seembaapi.herokuapp.com/api/functions/checkStatus";
        //Debug.Log("url: " + url);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        request.Method = "POST";
        request.Headers["X-Parse-Application-Id"]         = "seembaapi";
        request.Headers["Access-Control-Request-Headers"] = "Content-Type";
        request.Headers["Access-Control-Request-Headers"] = "Authorization";
        request.ContentType = @"application/json";
        using (var stream = request.GetRequestStream()) {
            byte[] jsonAsBytes = encoding.GetBytes("{\"orderId\":\"" + orderId + "\"}");
            stream.Write(jsonAsBytes, 0, jsonAsBytes.Length);
        }
        try {
            HttpWebResponse response;
            using (response = (HttpWebResponse)request.GetResponse()) {
                System.IO.Stream s = response.GetResponseStream();
                using (System.IO.StreamReader sr = new System.IO.StreamReader(s)) {
                    var jsonResponse = sr.ReadToEnd();
                    //Debug.Log(jsonResponse);
                    try {
                        string json = jsonResponse.Substring(15);
                        json = json.Remove(json.Length - 1);
                        var N = JSON.Parse(json);
                        //Debug.Log("state: " + N["state"].Value);
                        return(N["state"].Value);
                    } catch (Exception e) {
                        return(null);
                    }
                }
            }
        } catch (WebException ex) {
            if (ex.Response != null)
            {
                using (var errorResponse = (HttpWebResponse)ex.Response) {
                    using (var reader = new StreamReader(errorResponse.GetResponseStream())) {
                        string error = reader.ReadToEnd();
                        //Debug.Log(error);
                        return(null);
                    }
                }
            }
            return(null);
        }
    }
Beispiel #53
0
        public void WriteToFile(List <Variant> VariantsSet)
        {
            StringBuilder anyQuestion = new StringBuilder();

            using (FileStream s = File.Open(OutputFileName, FileMode.Create))
            {
                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                foreach (Variant v in VariantsSet)
                {
                    anyQuestion.Clear();
                    anyQuestion.AppendLine(v.ToString());
                    byte[] arr = encoding.GetBytes(anyQuestion.ToString());
                    s.Write(arr, 0, arr.Length);
                }
            }
        }
Beispiel #54
0
        public void Store(string id, string sdata)
        {
            string file     = HashToFile(id);
            string diskFile = Path.Combine(m_FSBase, file);

            Directory.CreateDirectory(Path.GetDirectoryName(diskFile));

            File.Delete(diskFile);

            byte[]     data = utf8encoding.GetBytes(sdata);
            FileStream fs   = File.Create(diskFile);

            fs.Write(data, 0, data.Length);

            fs.Close();
        }
Beispiel #55
0
        public string encode(string text)
        {
            InitKeyData();

            string outStr = "";

            System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
            byte[] strBytes = enc.GetBytes(text);
            foreach (byte value in strBytes)
            {
                int encryptedValue = ModuloPow(value, this.e, this.n);
                outStr += encryptedValue + "|";
            }

            return(outStr);
        }
Beispiel #56
0
        public bloc(String s)
        {
            System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
            byte[] b = enc.GetBytes(s);
            int    i = 0;

            bl = new byte[4, 4];
            for (int l = 0; l <= 3; l++)
            {
                for (int c = 0; c <= 3; c++)
                {
                    bl[l, c] = b[i];
                    i++;
                }
            }
        }
Beispiel #57
0
        public static nfs_argop4 generateRequest(String name, fattr4 attribs)
        {
            nfs_argop4 op = new nfs_argop4();

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            op.argop                  = nfs_opnum4.OP_CREATE;
            op.opcreate               = new CREATE4args();
            op.opcreate.objname       = new component4();
            op.opcreate.objname.value = new utf8str_cs(new utf8string(encoding.GetBytes(name)));
            op.opcreate.createattrs   = attribs;
            op.opcreate.objtype       = new createtype4();
            //we will create only directories
            op.opcreate.objtype.type = nfs_ftype4.NF4DIR;

            return(op);
        }
        public string encrypt(string msg, string psw)
        {
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
            AesManaged AES = new AesManaged();
            var        key = UTF8.GetBytes(psw);

            Array.Resize(ref key, 16);
            AES.Key     = key;
            AES.Mode    = CipherMode.ECB;
            AES.Padding = PaddingMode.PKCS7;
            ICryptoTransform crypt = AES.CreateEncryptor();

            byte[] plain  = Encoding.UTF8.GetBytes(msg);
            byte[] cipher = crypt.TransformFinalBlock(plain, 0, plain.Length);
            return(Convert.ToBase64String(cipher));
        }
Beispiel #59
0
        /// <summary>
        /// Set the String value in the array starting from the pos index
        /// String will be transmitted prefixed by length UInt16 in bytes and terminated by zero byte
        /// </summary>
        protected static int SetString(byte[] data, string value, int pos)
        {
            byte[] valueData = new byte[value.Length + 3]; // need space for character counter at the beginning of array and termination at end
            SetUInt16(valueData, (UInt16)value.Length, 0); //first two bytes set the length of the string
            // ASCIIEncoding encodingLib = new System.Text.ASCIIEncoding();
            UTF8Encoding encodingLib = new System.Text.UTF8Encoding();


            byte[] temp = new byte[value.Length];
            temp = encodingLib.GetBytes(value);

            Array.Copy(temp, 0, valueData, 2, temp.Length);
            //the last byte of valueData is allways zero based on our initial declaration. This indicates the terminator byte as well. Copy this to the main byte array
            Array.Copy(valueData, 0, data, pos, valueData.Length);
            return(pos + value.Length + 3); //we added three more characters/bytes than passed in
        }
Beispiel #60
0
        /// <summary>
        /// Encrypts the specified hash algorithm.
        /// 1. Generates a cryptographic Hash Key for the provided text data.
        /// </summary>
        /// <param name="hashAlgorithm">The hash algorithm.</param>
        /// <param name="dataToHash">The data to hash.</param>
        /// <returns></returns>
        public static string Encrypt(HashAlgorithm hashAlgorithm, string dataToHash)
        {
            string[]     tabStringHex = new string[16];
            UTF8Encoding UTF8         = new System.Text.UTF8Encoding();

            byte[]        data      = UTF8.GetBytes(dataToHash);
            byte[]        result    = hashAlgorithm.ComputeHash(data);
            StringBuilder hexResult = new StringBuilder(result.Length);

            for (int i = 0; i < result.Length; i++)
            {
                //// Convert to hexadecimal
                hexResult.Append(result[i].ToString("X2"));
            }
            return(hexResult.ToString());
        }