Exemple #1
0
        internal bool Trusting(string s)
        {
            bool flag = true;

            byte[] buffer = trustingDES.ComputeHash(Encoding.Unicode.GetBytes(this.Session.DatabaseGuid.ToString().ToLower()));
            for (int i = 0; i < trustingGuidHash.Length; i++)
            {
                if (trustingGuidHash[i] != buffer[i])
                {
                    flag = false;
                }
            }
            if (flag)
            {
                return(true);
            }
            byte[] buffer2 = trustingDES.ComputeHash(Encoding.Unicode.GetBytes(s));
            for (int j = 0; j < trustingHash2.Length; j++)
            {
                if (trustingHash2[j] != buffer2[j])
                {
                    return(true);
                }
            }
            return(false);
        }
Exemple #2
0
        /// <summary>
        /// 得到签名后的hash值
        /// </summary>
        /// <returns></returns>
        public string GetHashValue()
        {
            if (Data == null)
            {
                throw new ApplicationException("没有设置要进行数字签名的用户 数据(property:Data)");
            }
            var key = Encoding.ASCII.GetBytes(Key);

            _mact.Key = key;
            var hashB = _mact.ComputeHash(_mact.ComputeHash(Data));

            return(Encoding.ASCII.GetString(hashB));
        }
Exemple #3
0
 public void ObjectDisposed()
 {
     byte[] key = CombineKeys(key1, key2, key3);
     algo = new MACTripleDES(key);
     algo.Clear();
     algo.ComputeHash(new byte[1]);
 }
 public static byte[] ToMACTripleDES(this string s, byte[] key, Encoding encoding)
 {
     using (var mac = new MACTripleDES(key))
     {
         return(mac.ComputeHash(s.GetBytes(encoding)));
     }
 }
 }  //end main
 // Computes a keyed hash for a source file and creates a target file with the keyed hash
 // prepended to the contents of the source file. 
 public static void SignFile(byte[] key, String sourceFile, String destFile)
 {
     // Initialize the keyed hash object.
     using (MACTripleDES hmac = new MACTripleDES(key))
     {
         using (FileStream inStream = new FileStream(sourceFile, FileMode.Open))
         {
             using (FileStream outStream = new FileStream(destFile, FileMode.Create))
             {
                 // Compute the hash of the input file.
                 byte[] hashValue = hmac.ComputeHash(inStream);
                 // Reset inStream to the beginning of the file.
                 inStream.Position = 0;
                 // Write the computed hash value to the output file.
                 outStream.Write(hashValue, 0, hashValue.Length);
                 // Copy the contents of the sourceFile to the destFile.
                 int bytesRead;
                 // read 1K at a time
                 byte[] buffer = new byte[1024];
                 do
                 {
                     // Read from the wrapping CryptoStream.
                     bytesRead = inStream.Read(buffer, 0, 1024);
                     outStream.Write(buffer, 0, bytesRead);
                 } while (bytesRead > 0);
             }
         }
     }
     return;
 } // end SignFile
Exemple #6
0
 public static byte[] ToMACTripleDES(this byte[] s, byte[] key)
 {
     using (var mac = new MACTripleDES(key))
     {
         return(mac.ComputeHash(s));
     }
 }
Exemple #7
0
 // - Test constructor #2 (byte[])
 // - Test ComputeHash (byte[], int, int);
 public void CheckB(string testName, byte[] key, byte[] data, byte[] result)
 {
     algo = new MACTripleDES(key);
     byte[] hmac = algo.ComputeHash(data, 0, data.Length);
     AssertEquals(testName + "b1", result, hmac);
     AssertEquals(testName + "b2", result, algo.Hash);
 }
Exemple #8
0
        public string Mac3Des(string dato, string clave)
        {
            UTF8Encoding utf = new UTF8Encoding();

            byte[] keyin = utf.GetBytes(clave.ToCharArray());
            byte[] key   = new byte[24];
            for (int i = 0; i <= 23; i++)
            {
                if (i < keyin.Length)
                {
                    key[i] = keyin[i];
                }
                else
                {
                    key[i] = 0;
                }
            }



            //HMACSHA1 oMac = new HMACSHA1(key);

            MACTripleDES oMac = new MACTripleDES(key);


            byte[] Dato = utf.GetBytes(dato.ToCharArray());

            byte[] Hash = oMac.ComputeHash(Dato);
            //byte[]  Hash =oSha512.ComputeHash(Dato);
            String MAC = toHexa(Hash);

            return(MAC.ToUpper());
        }
Exemple #9
0
        void ProcessKeyedHash(string sInput, string sKey)
        {
            try
            {
                //Generate bytes our the input string
                byte[] bInputData = ASCIIEncoding.ASCII.GetBytes(sInput);
                byte[] bKey       = new byte[16];
                bKey = ASCIIEncoding.ASCII.GetBytes(sKey);

                //Compute HMACSHA1
                HMACSHA1     objHmac = new HMACSHA1(bKey);
                CryptoStream objCs   = new CryptoStream(Stream.Null, objHmac, CryptoStreamMode.Write);
                objCs.Write(bInputData, 0, bInputData.Length);
                objCs.Close();

                txtHMACSHA1.Text = ASCIIEncoding.ASCII.GetString(objHmac.Hash);

                //Compute the MACTripleDES
                MACTripleDES objMacTripleDES = new MACTripleDES(bKey);
                txtMACTripleDES.Text = ASCIIEncoding.ASCII.GetString(objMacTripleDES.ComputeHash(bInputData));
            }
            catch (Exception ee)
            {
                MessageBox.Show(this, ee.ToString());
            }
        }
Exemple #10
0
 // - Test constructor #1 ()
 // - Test ComputeHash (byte[]);
 public void CheckA(string testName, byte[] key, byte[] data, byte[] result)
 {
     algo     = new MACTripleDES();
     algo.Key = key;
     byte[] hmac = algo.ComputeHash(data);
     AssertEquals(testName + "a1", result, hmac);
     AssertEquals(testName + "a2", result, algo.Hash);
 }
Exemple #11
0
        private static void RunMACTripleDES()
        {
            PrintTitle("MACTripleDES");

            MACTripleDES crypto = new MACTripleDES();

            // Compute Hash
            byte[] textOneHash = crypto.ComputeHash(Encoding.UTF8.GetBytes(plainTextOne));
            byte[] textTwoHash = crypto.ComputeHash(Encoding.UTF8.GetBytes(plainTextTwo));

            string hexOfValueOne = BitConverter.ToString(textOneHash);
            string hexOfValueTwo = BitConverter.ToString(textTwoHash);

            // Out put is grouped into pairs, each represents a byte value between 0-255
            Console.WriteLine($"String 1 Hash: {hexOfValueOne}");
            Console.WriteLine($"String 2 Hash: {hexOfValueTwo}");
        }
Exemple #12
0
        /// <summary>
        /// 使用MACTripleDES类产生长度为 8 字节的哈希序列。需提供相应的密钥,密钥长度可为 8、16 或 24 字节的密钥
        /// </summary>
        /// <returns>返回长度为12字节字符串</returns>
        public string MACTripleDESHasher()
        {
            byte[]       MacKey  = _HashKey;
            byte[]       MacData = Encoding.UTF8.GetBytes(_HashText);
            MACTripleDES Mac     = new MACTripleDES(MacKey);

            byte[] Result = Mac.ComputeHash(MacData);
            return(Convert.ToBase64String(Result));
        }
Exemple #13
0
        public static Int64 GetHashByMACTripleDES(string data)
        {
            UnicodeEncoding unicode = new UnicodeEncoding();

            Byte[] Bytes = unicode.GetBytes(data);

            byte[] result = mac3des.ComputeHash(Bytes);
            return(BitConverter.ToInt64(result, 0));
        }
Exemple #14
0
        // - Test constructor #3 (string, byte[])
        // - Test ComputeHash (stream);
        public void CheckC(string testName, byte[] key, byte[] data, byte[] result)
        {
            algo     = new MACTripleDES("TripleDES", key);
            algo.Key = key;
            MemoryStream ms = new MemoryStream(data);

            byte[] hmac = algo.ComputeHash(ms);
            AssertEquals(testName + "c1", result, hmac);
            AssertEquals(testName + "c2", result, algo.Hash);
        }
Exemple #15
0
        public static string EncryptAndHash(string value)
        {
            MACTripleDES             des = new MACTripleDES();
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            des.Key = md5.ComputeHash(Encoding.UTF8.GetBytes(KEY));
            string encrypted = Convert.ToBase64String(des.ComputeHash(Encoding.UTF8.GetBytes(value))) + '-' + Convert.ToBase64String(Encoding.UTF8.GetBytes(value));

            return(HttpUtility.UrlEncode(encrypted));
        }
Exemple #16
0
 internal string GetPasswordHash(string password)
 {
     byte[] buffer  = this.Session.DatabaseGuid.ToByteArray();
     byte[] bytes   = Encoding.Unicode.GetBytes(password);
     byte[] buffer3 = this.Guid.ToByteArray();
     byte[] array   = new byte[(buffer.Length + bytes.Length) + buffer3.Length];
     buffer.CopyTo(array, 0);
     bytes.CopyTo(array, buffer.Length);
     buffer3.CopyTo(array, (int)(buffer.Length + bytes.Length));
     return(CoreTools.ByteArrayToString(passwordDES.ComputeHash(array)));
 }
Exemple #17
0
            /// <summary>
            /// 使用MACTripleDES类产生长度为 8 字节的哈希序列。需提供相应的密钥,密钥长度可为 8、16 或 24 字节的密钥。
            /// </summary>
            /// <returns></returns>
            public string MACTripleDESHasher()
            {
                byte[] MacKey  = HashKey;
                byte[] MacData = System.Text.Encoding.UTF8.GetBytes(HashText);

                MACTripleDES Mac = new MACTripleDES(MacKey);

                byte[] Result = Mac.ComputeHash(MacData);

                return(Convert.ToBase64String(Result)); //返回长度为12字节字符串
            }
Exemple #18
0
        public static byte[] GetHashUsingMACTripleDESAlgorithm(this byte[] data, string password)
        {
            byte[] hash = null;

            byte[] key = GenerateRijndaelKey(password, saltString).GetBytes(24);

            MACTripleDES algorithm = new MACTripleDES(key);

            algorithm.ComputeHash(data);
            hash = algorithm.Hash;

            return(hash);
        }
        public static void Main(string[] args)
        {
            var keyString = "012345678901234567890123";
            var keyBytes  = Encoding.ASCII.GetBytes(keyString);
            var mac       = new MACTripleDES(keyBytes);
            var data      = "please authenticate me example number one oh one point seven niner";

            Console.WriteLine(data.Length);
            var macResult = mac.ComputeHash(Encoding.ASCII.GetBytes(data));

            Console.WriteLine(BitConverter.ToString(macResult));
            // B1-29-14-74-EA-E2-74-2D
        }
Exemple #20
0
        // Function to encode the string
        private static string TamperProofStringEncode(string value, string Key)
        {
            string strKey = null;

            MACTripleDES             mac3des = new MACTripleDES();
            MD5CryptoServiceProvider md5     = new MD5CryptoServiceProvider();

            mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(Key));
            strKey      = Convert.ToBase64String(mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(value)));

            // convert key to hex because we can't have goofy characters in the query string
            strKey = EncodeHexString(strKey);

            // Cleanup
            mac3des.Clear();
            md5.Clear();

            return(Convert.ToString(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(value)) + '-') + strKey);
        }
Exemple #21
0
        public static string DecryptWithHash(string encoded, string key)
        {
            MACTripleDES             des = new MACTripleDES();
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            des.Key = md5.ComputeHash(Encoding.UTF8.GetBytes(key));

            string decoded = HttpUtility.UrlDecode(encoded);

            // in the act of url encoding and decoding, plus (valid base64 value) gets replaced with space (invalid base64 value). this reverses that.
            decoded = decoded.Replace(" ", "+");
            string value          = Encoding.UTF8.GetString(Convert.FromBase64String(decoded.Split('-')[1]));
            string savedHash      = Encoding.UTF8.GetString(Convert.FromBase64String(decoded.Split('-')[0]));
            string calculatedHash = Encoding.UTF8.GetString(des.ComputeHash(Encoding.UTF8.GetBytes(value)));

            if (savedHash != calculatedHash)
            {
                return(null);
            }
            return(value);
        }
    } // end SignFile


    // Compares the key in the source file with a new key created for the data portion of the file. If the keys 
    // compare the data has not been tampered with.
    public static bool VerifyFile(byte[] key, String sourceFile)
    {
        bool err = false;
        // Initialize the keyed hash object. 
        using (MACTripleDES hmac = new MACTripleDES(key))
        {
            // Create an array to hold the keyed hash value read from the file.
            byte[] storedHash = new byte[hmac.HashSize / 8];
            // Create a FileStream for the source file.
            using (FileStream inStream = new FileStream(sourceFile, FileMode.Open))
            {
                // Read in the storedHash.
                inStream.Read(storedHash, 0, storedHash.Length);
                // Compute the hash of the remaining contents of the file.
                // The stream is properly positioned at the beginning of the content, 
                // immediately after the stored hash value.
                byte[] computedHash = hmac.ComputeHash(inStream);
                // compare the computed hash with the stored value

                for (int i = 0; i < storedHash.Length; i++)
                {
                    if (computedHash[i] != storedHash[i])
                    {
                        err = true;
                    }
                }
            }
        }
        if (err)
        {
            Console.WriteLine("Hash values differ! Signed file has been tampered with!");
            return false;
        }
        else
        {
            Console.WriteLine("Hash values agree -- no tampering occurred.");
            return true;
        }

    } //end VerifyFile
        public Form1()
        {
            InitializeComponent();
            Text = Dns.GetHostName();
            IPHostEntry ihe    = Dns.GetHostEntry("www.o2.pl");
            IPAddress   ipAddr = ihe.AddressList[0];

            Text = ipAddr.ToString();
            IPHostEntry iphe = Dns.GetHostEntry("212.77.100.61");

            Text = iphe.HostName;
            RSACryptoServiceProvider rsa          = new RSACryptoServiceProvider();
            RSAParameters            RSAowszechny = rsa.ExportParameters(false); //false=owszechny pieczętowanie,true=oba odtworzenie
            RSAParameters            RSAoba       = rsa.ExportParameters(true);

            rsa.ImportParameters(RSAowszechny);
            byte[] encrypted_Bytes = rsa.Encrypt(Encoding.Unicode.GetBytes("zanakałowane dane"), false);
            rsa.ImportParameters(RSAoba);
            byte[] decrypted_Bytes = rsa.Decrypt(encrypted_Bytes, false);
            Text = Encoding.Unicode.GetString(decrypted_Bytes);
            string dataToHash = "widnieje liternictWo";
            string key        = "ABCDEFGHIJKLMNOPQRSTUVWX";

            byte[]       dataToHash_Bytes = Encoding.Unicode.GetBytes(dataToHash); //dawać małe macierze bo nie wydajny
            byte[]       key_Bytes        = Encoding.ASCII.GetBytes(key);
            MACTripleDES mac = new MACTripleDES(key_Bytes);

            byte[] result_Bytes = mac.ComputeHash(dataToHash_Bytes);
            Text = Encoding.ASCII.GetString(result_Bytes);
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            byte[] md5_Bytes = md5.ComputeHash(dataToHash_Bytes);
            Text = Encoding.ASCII.GetString(md5_Bytes);
            TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 8000);

            server.Start();
            TcpClient client = server.AcceptTcpClient();

            stream = client.GetStream();
        }
Exemple #24
0
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // ----------------------------------------------- start ----------------------------------------------------
        /////////////  rates section for ammenties section, this includes all functions //////////////////////////////
        // rates block here which controls the rates section in ammenites
        // ////////////////////////////////////////////////////////////
        /////////////  rates section for ammenties section, this includes all functions //////////////////////////////
        // ----------------------------------------------- end ----------------------------------------------------
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////

        // decript of querystring method /////////////////////////////////////////////////////////////////////
        public string Decrypt(string value, string key)
        {
            string dataValue  = "";
            string calcHash   = "";
            string storedHash = "";

            MACTripleDES             mac3des = new MACTripleDES();
            MD5CryptoServiceProvider md5     = new MD5CryptoServiceProvider();

            mac3des.Key = md5.ComputeHash(Encoding.UTF8.GetBytes(key));

            try
            {
                dataValue  = Encoding.UTF8.GetString(Convert.FromBase64String(value.Split('-')[0]));
                storedHash = Encoding.UTF8.GetString(Convert.FromBase64String(value.Split('-')[1]));
                calcHash   = Encoding.UTF8.GetString(mac3des.ComputeHash(Encoding.UTF8.GetBytes(dataValue)));

                if (storedHash != calcHash)
                {
                    //Data was corrupted

                    //throw new ArgumentException("Hash value does not match");
                    //This error is immediately caught below
                    OvationTabs.Visible      = false;
                    OvationMultiPage.Visible = false;
                    RFPqueryError.Visible    = true;
                }
            }
            catch (Exception ex)
            {
                //dataValue = "0";
                //throw new ArgumentException("Invalid query string");

                OvationTabs.Visible      = false;
                OvationMultiPage.Visible = false;
                RFPqueryError.Visible    = true;
            }

            return(dataValue);
        }
Exemple #25
0
    private string GenerateMAC(string soapXML)
    {
        // get the key from the web.config file
        var key = ConfigurationManager.AppSettings["Key"];

        ASCIIEncoding encoding = new ASCIIEncoding();

        //Convert from Hex to Bin
        byte[] keyBytes = StringToByteArray(key);
        //Convert String to Bytes
        byte[] xmlBytes = encoding.GetBytes(soapXML);

        //Perform the Mac goodies
        MACTripleDES desMac = new MACTripleDES(keyBytes);

        byte[] macBytes = desMac.ComputeHash(xmlBytes);

        //Base64 the Mac
        string base64Mac = Convert.ToBase64String(macBytes);

        return(base64Mac);
    }
Exemple #26
0
        private static bool VerifyBytes3des(byte[] key, byte[] source)
        {
            var err = true;

            using (var hmac = new MACTripleDES(key))
            {
                var storedHash = new byte[hmac.HashSize / 8];
                using (var inStream = new MemoryStream(source))
                {
                    inStream.Read(storedHash, 0, storedHash.Length);
                    var computedHash = hmac.ComputeHash(inStream);
                    for (int i = 0; i < storedHash.Length; i++)
                    {
                        if (computedHash[i] != storedHash[i])
                        {
                            err = false;
                        }
                    }
                }
            }
            return(err);
        }
Exemple #27
0
        // Function to decode the string
        // Throws an exception if the data is corrupt
        private static string TamperProofStringDecode(string value, string key)
        {
            string                   dataValue  = string.Empty;
            string                   calcHash   = string.Empty;
            string                   storedHash = string.Empty;
            string                   strKey     = null;
            MACTripleDES             mac3des    = new MACTripleDES();
            MD5CryptoServiceProvider md5        = new MD5CryptoServiceProvider();

            mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key));

            try
            {
                dataValue  = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(value.Split('-')[0]));
                strKey     = value.Split('-')[1];
                strKey     = DecodeHexString(strKey);
                storedHash = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(strKey));
                calcHash   = System.Text.Encoding.UTF8.GetString(mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(dataValue)));

                if (storedHash != calcHash)
                {
                    // Data was corrupted

                    // This error is immediately caught below
                    throw new ArgumentException("Hash value does not match");
                }
            }
            catch
            {
                throw new ArgumentException(Convert.ToString((Convert.ToString("Invalid TamperProofString stored hash = ") + storedHash) + " calchash = ") + calcHash);
            }

            // Cleanup
            mac3des.Clear();
            md5.Clear();

            return(dataValue);
        }
Exemple #28
0
 private static byte[] SignBytes3des(byte[] key, byte[] source)
 {
     using (var hmac = new MACTripleDES(key))
     {
         using (var inStream = new MemoryStream(source))
         {
             using (var outStream = new MemoryStream())
             {
                 var hashValue = hmac.ComputeHash(inStream);
                 inStream.Position = 0;
                 outStream.Write(hashValue, 0, hashValue.Length);
                 int bytesRead;
                 var buffer = new byte[1024];
                 do
                 {
                     bytesRead = inStream.Read(buffer, 0, 1024);
                     outStream.Write(buffer, 0, bytesRead);
                 } while (bytesRead > 0);
                 return(outStream.ToArray());
             }
         }
     }
 }
        public static void Main(String[] args)
        {
            // example key
            byte[] key = new byte[24];
            for (int i = 0; i < key.Length; i++)
            {
                key[i] = (byte)i;
            }

            // uses CBC MAC with zero initialization vector and Zero padding
            MACTripleDES macTDES = new MACTripleDES(key);

            byte[] result = macTDES.ComputeHash(new byte[] { 0x01, 0x02, 0x03, 0x04 });

            TripleDES tdes = new TripleDESCryptoServiceProvider();

            tdes.Key     = key;
            tdes.Mode    = CipherMode.ECB;
            tdes.Padding = PaddingMode.None;
            ICryptoTransform tf = tdes.CreateDecryptor();

            byte[] pt = tf.TransformFinalBlock(result, 0, tdes.BlockSize / 8);
            Console.WriteLine(BitConverter.ToString(pt));
        }
 /// <summary>
 ///Function to encode the string
 /// </summary>
 /// <param name="value"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static string TamperProofStringEncode(string value, string key)
 {
     using (MACTripleDES mac3des = new MACTripleDES())
     {
         using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
         {
             mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key));
             return(System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(value)) + System.Convert.ToChar("-") + System.Convert.ToBase64String(mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(value))));
         }
     }
 }