Ejemplo n.º 1
0
        public static AESKeyData GenerateKeyDataFromNonces(byte[] serverNonce, byte[] newNonce) {
            using (SHA1 hash = new SHA1Managed()) {
                var nonces = new byte[48];

                newNonce.CopyTo(nonces, 0);
                serverNonce.CopyTo(nonces, 32);
                byte[] hash1 = hash.ComputeHash(nonces);

                serverNonce.CopyTo(nonces, 0);
                newNonce.CopyTo(nonces, 16);
                byte[] hash2 = hash.ComputeHash(nonces);

                nonces = new byte[64];
                newNonce.CopyTo(nonces, 0);
                newNonce.CopyTo(nonces, 32);
                byte[] hash3 = hash.ComputeHash(nonces);

                using (var keyBuffer = new MemoryStream(32))
                using (var ivBuffer = new MemoryStream(32)) {
                    keyBuffer.Write(hash1, 0, hash1.Length);
                    keyBuffer.Write(hash2, 0, 12);

                    ivBuffer.Write(hash2, 12, 8);
                    ivBuffer.Write(hash3, 0, hash3.Length);
                    ivBuffer.Write(newNonce, 0, 4);

                    return new AESKeyData(keyBuffer.ToArray(), ivBuffer.ToArray());
                }
            }
        }
Ejemplo n.º 2
0
        public WardenRandom(byte[] seed)
        {
            Data1 = new byte[0x14];
            Data2 = new byte[0x14];
            Data3 = new byte[0x14];

            int length1 = (int)seed.Length >> 1;
            int length2 = seed.Length - length1;

            byte[] seed1 = new byte[length1];
            byte[] seed2 = new byte[length2];

            for (int i = 0; i < length1; i++)
                seed1[i] = seed[i];
            for (int i = 0; i < length2; i++)
                seed2[i] = seed[i + length1];

            SHA1 sha = new SHA1Managed();
            Data2 = sha.ComputeHash(seed1);
            Data3 = sha.ComputeHash(seed2);

            sha.Initialize();
            sha.TransformBlock(Data2, 0, Data2.Length, Data2, 0);
            sha.TransformBlock(Data1, 0, Data1.Length, Data1, 0);
            sha.TransformFinalBlock(Data3, 0, Data3.Length);

            Data1 = sha.Hash;

            sha.Initialize();
        }
Ejemplo n.º 3
0
        public string GenerateMySQ5LHash(string key)
        {
            byte[] keyArray = Encoding.UTF8.GetBytes(key);
            SHA1Managed enc = new SHA1Managed();
            byte[] encodedKey = enc.ComputeHash(enc.ComputeHash(keyArray));
            StringBuilder myBuilder = new StringBuilder(encodedKey.Length);

            foreach (byte b in encodedKey)
                myBuilder.Append(b.ToString("X2"));

            return "*" + myBuilder.ToString();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Generate a new hash for RealVault orders
        /// </summary>
        /// <param name="normalPassword"></param>
        /// <param name="merchantId"></param>
        /// <param name="orderId"></param>
        /// <param name="amount"></param>
        /// <param name="currency"></param>
        /// <param name="card"></param>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public static String GenerateSHA1Hash(string hashInput, string sharedSecret)
        {
            SHA1 sha = new SHA1Managed();

            String hashStage1 =
                hexEncode(sha.ComputeHash(Encoding.UTF8.GetBytes(hashInput))) + "." +
                sharedSecret;

            String hashStage2 =
                hexEncode(sha.ComputeHash(Encoding.UTF8.GetBytes(hashStage1)));

            return hashStage2;
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            string pubKey = ConfigurationManager.AppSettings["pubKey"];
            string priKey = ConfigurationManager.AppSettings["priKey"];
            string input = ConfigurationManager.AppSettings["input"];
            string user = ConfigurationManager.AppSettings["user"];

            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                SHA1Managed sha = new SHA1Managed();
                rsa.FromXmlString(priKey);
                Console.WriteLine("begin to encode:");
                RSAPKCS1SignatureFormatter signFormatter = new RSAPKCS1SignatureFormatter(rsa);
                signFormatter.SetHashAlgorithm("SHA1");
                byte[] source = System.Text.ASCIIEncoding.UTF8.GetBytes(input);
                byte[] result = sha.ComputeHash(source);
                byte[] b = signFormatter.CreateSignature(result);
                var signature = Convert.ToBase64String(b);

                string outputFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sn", input + ".key");
                FileInfo fi = new FileInfo(outputFile);
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }
                StreamWriter sw = new StreamWriter(fi.OpenWrite(), Encoding.UTF8);
                sw.Write(signature);
                sw.Close();
                Console.WriteLine();
                Console.WriteLine(signature);

                using (RSACryptoServiceProvider rsa2 = new RSACryptoServiceProvider())
                {
                    rsa2.FromXmlString(pubKey);
                    RSAPKCS1SignatureDeformatter decodeFormatter = new RSAPKCS1SignatureDeformatter(rsa2);
                    decodeFormatter.SetHashAlgorithm("SHA1");
                    byte[] key = Convert.FromBase64String(signature);
                    byte[] name = sha.ComputeHash(ASCIIEncoding.UTF8.GetBytes(input));
                    if (decodeFormatter.VerifySignature(name, key))
                    {
                        Console.WriteLine("===========can be decoded");
                    }
                    else
                    {
                        Console.WriteLine("===CANOT be decoded..................");
                    }
                }
            }
        }
Ejemplo n.º 6
0
 public static string SHA1(string stringToHash)
 {
     System.Security.Cryptography.SHA1Managed sha1Obj = new System.Security.Cryptography.SHA1Managed();
     byte[] bytesToHash = System.Text.Encoding.UTF8.GetBytes(stringToHash);
     bytesToHash = sha1Obj.ComputeHash(bytesToHash);
     return(BitConverter.ToString(bytesToHash).Replace("-", "").ToUpper());
 }
Ejemplo n.º 7
0
        public bool CompareStringToHash(string s, string hash)
        {
            var hashData = Convert.FromBase64String(hash);
            // First, pluck the four-byte salt off of the end of the hash
            var saltData = new byte[SaltSize];
            Array.Copy(hashData, hashData.Length - saltData.Length, saltData, 0, saltData.Length);

            var passwordData = Encoding.UTF8.GetBytes(s);

            // Append the salt to the end of the original
            var saltedPasswordData = new byte[passwordData.Length + saltData.Length];
            Array.Copy(passwordData, 0, saltedPasswordData, 0, passwordData.Length);
            Array.Copy(saltData, 0, saltedPasswordData, passwordData.Length, saltData.Length);

            // Create a new SHA-1 instance and compute the hash
            var sha = new SHA1Managed();
            var newHashData = sha.ComputeHash(saltedPasswordData);

            // Add salt bytes onto end of the original hash for storage
            var newHashSaltData = new byte[newHashData.Length + saltData.Length];
            Array.Copy(newHashData, 0, newHashSaltData, 0, newHashData.Length);
            Array.Copy(saltData, 0, newHashSaltData, newHashData.Length, saltData.Length);
            // Compare and return
            return (Convert.ToBase64String(hashData).Equals(Convert.ToBase64String(newHashSaltData)));
        }
Ejemplo n.º 8
0
        public static bool CompareCode(string regcode)
        {
            if (regcode == null || regcode == "")
            {
                return false;
            }
            try
            {
                string toolcode = GetDiskVolumeSerialNumber() + GetCpuSerialNumber();
                string pubkey = "<RSAKeyValue><Modulus>xe3teTUwLgmbiwFJwWEQnshhKxgcasglGsfNVFTk0hdqKc9i7wb+gG7HOdPZLh65QyBcFfzdlrawwVkiPEL5kNTX1q3JW5J49mTVZqWd3w49reaLd8StHRYJdyGAL4ZovBhSTThETi+zYvgQ5SvCGkM6/xXOz+lkMaEgeFcjQQs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
                string prikey = "<RSAKeyValue><Modulus>xe3teTUwLgmbiwFJwWEQnshhKxgcasglGsfNVFTk0hdqKc9i7wb+gG7HOdPZLh65QyBcFfzdlrawwVkiPEL5kNTX1q3JW5J49mTVZqWd3w49reaLd8StHRYJdyGAL4ZovBhSTThETi+zYvgQ5SvCGkM6/xXOz+lkMaEgeFcjQQs=</Modulus><Exponent>AQAB</Exponent><P>5flMAd7IrUTx92yomBdJBPDzp1Kclpaw4uXB1Ht+YXqwLW/9icI6mcv7d2O0kuVLSWj8DPZJol9V8AtvHkC3oQ==</P><Q>3FRA9UWcFrVPvGR5bewcL7YqkCMZlybV/t6nCH+gyMfbEvgk+p04F+j8WiHDykWj+BahjScjwyF5SGADbrfJKw==</Q><DP>b4WOU1XbERNfF3JM67xW/5ttPNX185zN2Ko8bbMZXWImr1IgrD5RNqXRo1rphVbGRKoxmIOSv7flr8uLrisKIQ==</DP><DQ>otSZlSq2qomgvgg7PaOLSS+F0TQ/i1emO0/tffhkqT4ah7BgE97xP6puJWZivjAteAGxrxHH+kPY0EY1AzRMNQ==</DQ><InverseQ>Sxyz0fEf5m7GrzAngLDRP/i+QDikJFfM6qPyr3Ub6Y5RRsFbeOWY1tX3jmV31zv4cgJ6donH7W2dSBPi67sSsw==</InverseQ><D>nVqofsIgSZltxTcC8fA/DFz1kxMaFHKFvSK3RKIxQC1JQ3ASkUEYN/baAElB0f6u/oTNcNWVPOqE31IDe7ErQelVc4D26RgFd5V7dSsF3nVz00s4mq1qUBnCBLPIrdb0rcQZ8FUQTsd96qW8Foave4tm8vspbM65iVUBBVdSYYE=</D></RSAKeyValue>";

                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {

                    rsa.FromXmlString(pubkey);

                    RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsa);

                    f.SetHashAlgorithm("SHA1");

                    SHA1Managed sha = new SHA1Managed();

                    byte[] name = sha.ComputeHash(ASCIIEncoding.ASCII.GetBytes(toolcode));
                    byte[] key = Convert.FromBase64String(regcode);

                    return f.VerifySignature(name, key);
                }
            }
            catch
            {
                return false;
            }
        }
Ejemplo n.º 9
0
 static void Main(string[] args)
 {
     if (args.Length != 1)
     {
         Console.WriteLine("You need to specify a filename as a single argument");
     }
     else
     {
         string file = args[0];
         if (File.Exists(file) == false)
         {
             Console.WriteLine("Argument is not a valid filename");
         }
         else
         {
             FileStream fs = new FileStream(@file, FileMode.Open);
             using (SHA1Managed sha1 = new SHA1Managed())
             {
                 byte[] hash = sha1.ComputeHash(fs);
                 StringBuilder sb = new StringBuilder(hash.Length);
                 foreach (byte b in hash)
                 {
                     sb.AppendFormat("{0:X2}", b);
                 }
                 Console.WriteLine(sb.ToString());
             }
         }
     }
 }
Ejemplo n.º 10
0
 public static string GetHash(byte[] bytes)
 {
     using (var sha1 = new SHA1Managed())
     {
         return string.Join("", sha1.ComputeHash(bytes).Select(b => b.ToString("x2")));
     }
 }
Ejemplo n.º 11
0
        private string HashValues(string Value1, string Value2, string HashingAlgorithm)
        {
            string sHashingAlgorithm = "";
            if (String.IsNullOrEmpty(HashingAlgorithm))
                sHashingAlgorithm = "SHA-1";
            else
                sHashingAlgorithm = HashingAlgorithm;

            byte[] arrByte;

            if (sHashingAlgorithm == "SHA-1")
            {
                SHA1Managed hash = new SHA1Managed();
                arrByte = hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes(Value1 + Value2));
            }
            else
            {
                SHA256Managed hash = new SHA256Managed();
                arrByte = hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes(Value1 + Value2));
            }

            string s = "";
            for (int i = 0; i < arrByte.Length; i++)
            {
                s += arrByte[i].ToString("x2");
            }
            return s;
        }
Ejemplo n.º 12
0
 public bool EncryptFile(string filePath, string savePath, string keyStr)
 {
     DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     if (keyStr == "")
         keyStr = key;
     FileStream fs = File.OpenRead(filePath);
     byte[] inputByteArray = new byte[fs.Length];
     fs.Read(inputByteArray, 0, (int)fs.Length);
     fs.Close();
     byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);
     SHA1 ha = new SHA1Managed();
     byte[] hb = ha.ComputeHash(keyByteArray);
     sKey = new byte[8];
     sIV = new byte[8];
     for (int i = 0; i < 8; i++)
         sKey[i] = hb[i];
     for (int i = 8; i < 16; i++)
         sIV[i - 8] = hb[i];
     des.Key = sKey;
     des.IV = sIV;
     MemoryStream ms = new MemoryStream();
     CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
     cs.Write(inputByteArray, 0, inputByteArray.Length);
     cs.FlushFinalBlock();
     fs = File.OpenWrite(savePath);
     foreach (byte b in ms.ToArray())
     {
         fs.WriteByte(b);
     }
     fs.Close();
     cs.Close();
     ms.Close();
     return true;
 }
Ejemplo n.º 13
0
		public override string Transform(string key)
		{
			SHA1Managed sh = new SHA1Managed();
			byte[] data = sh.ComputeHash(Encoding.Unicode.GetBytes(key));

			return Convert.ToBase64String(data, Base64FormattingOptions.None);
		}
Ejemplo n.º 14
0
        public static SeekableCryptoStream CreateUltraSecureStream(string pswd, int seglen, Stream btr)
        {
            SHA1 mt = new SHA1Managed();
            byte[] hash = mt.ComputeHash(Encoding.UTF8.GetBytes(pswd));
            List<char> tlist = new List<char>(pswd.ToCharArray());
            tlist.Reverse();
            string reversed = new string(tlist.ToArray());
            //Create stream 0
            Aes rdale = new AesManaged();

            Rfc2898DeriveBytes derivitive = new Rfc2898DeriveBytes(reversed + pswd + hash[5].ToString(), hash);
            rdale.Key = derivitive.GetBytes(32);
            derivitive = new Rfc2898DeriveBytes(hash, Encoding.Unicode.GetBytes(pswd), 16);
            rdale.IV = derivitive.GetBytes(16);
            SeekableCryptoStream mstr = new SeekableCryptoStream(new SegmentReader(btr, rdale, seglen));
            //Create stream 1
            Aes secondale = new AesManaged();
            derivitive = new Rfc2898DeriveBytes(pswd + reversed + hash[2].ToString(), Encoding.BigEndianUnicode.GetBytes(pswd));
            secondale.Key = derivitive.GetBytes(32);
            derivitive = new Rfc2898DeriveBytes(hash, Encoding.Unicode.GetBytes(pswd), 16);
            secondale.IV = derivitive.GetBytes(16);
            //No clue why this has to be less than 16384, but it does....
            Console.WriteLine("WARNING: Insecure test algorithm. Uncomment line below to secure it");
           //TODO: DOESN't work with 2 for some reason....
            mstr = new SeekableCryptoStream(new SegmentReader(mstr, rdale, seglen));
            return mstr;
        }
Ejemplo n.º 15
0
 public void TestSHA1()
 {
     byte[] data = new byte[256];
     byte[] result;
     var shaM = new SHA1Managed();
     result = shaM.ComputeHash(data);
 }
Ejemplo n.º 16
0
Archivo: SHA1.cs Proyecto: r15ch13/trv
 public static string GetString(string str, Encoding enc)
 {
     try
     {
         using (SHA1Managed sha = new SHA1Managed())
         {
             byte[] hash = (enc == null) ? sha.ComputeHash(Encoding.UTF8.GetBytes(str)) : sha.ComputeHash(enc.GetBytes(str));
             //return Utils.StringHelper.ByteArrayToHexString(hash);
             return "";
         }
     }
     catch (Exception ex)
     {
         throw new CryptoException(ex.Message, ex);
     }
 }
Ejemplo n.º 17
0
 public static Hash FromFile(string path)
 {
     SHA1 sha = new SHA1Managed();
     byte[] arr = FileUtils.GetAllBytes(path);
     byte[] result = sha.ComputeHash(arr);
     return new Hash(result);
 }
 public virtual string GenerateId(string handle)
 {
     var sha = new SHA1Managed();
     var handleBytes = Encoding.UTF8.GetBytes(handle);
     var hashBytes = sha.ComputeHash(handleBytes);
     return BitConverter.ToString(hashBytes, 0, 9).Replace("-", "");
 }
Ejemplo n.º 19
0
        public void AddFile(DeduplicatorState state, FileInfo sourceFile, string destinationPath)
        {
            if (state.DestinationToFileHash.ContainsKey(destinationPath))
            {
                // File has already been added.
                return;
            }

            // Read the source file.
            var memory = new MemoryStream();
            using (var stream = new BufferedStream(new FileStream(sourceFile.FullName, FileMode.Open, FileAccess.Read, FileShare.None), 1200000))
            {
                stream.CopyTo(memory);
            }

            // Hash the memory stream.
            var sha1 = new SHA1Managed();
            memory.Seek(0, SeekOrigin.Begin);
            var hashBytes = sha1.ComputeHash(memory);
            var hashString = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
            memory.Seek(0, SeekOrigin.Begin);

            // Add to the file hash -> source map if not already present.
            if (!state.FileHashToSource.ContainsKey(hashString))
            {
                state.FileHashToSource.Add(hashString, memory);
            }
            else
            {
                memory.Dispose();
            }

            state.DestinationToFileHash.Add(destinationPath, hashString);
        }
Ejemplo n.º 20
0
        public static TapeRecord ReadRecord(Stream file)
        {
            ReadAndVerifySignature(file, ReadableHeaderStart, "Start");
            var dataLength = ReadReadableInt64(file);
            ReadAndVerifySignature(file, ReadableHeaderEnd, "Header-End");

            var data = new byte[dataLength];
            file.Read(data, 0, (int) dataLength);

            ReadAndVerifySignature(file, ReadableFooterStart, "Footer-Start");

            ReadReadableInt64(file); //length verified
            var recVersion = ReadReadableInt64(file);
            var hash = ReadReadableHash(file);
            using (var managed = new SHA1Managed())
            {

                var computed = managed.ComputeHash(data);

                if (!computed.SequenceEqual(hash))
                    throw new InvalidOperationException("Hash corrupted");
            }
            ReadAndVerifySignature(file, ReadableFooterEnd, "End");

            return new TapeRecord(recVersion, data);
        }
Ejemplo n.º 21
0
Archivo: DB.cs Proyecto: cpbuck12/Db
 }/*
 private string Hash(byte[] buffer)
 {
     SHA1Managed sha1 = new SHA1Managed();
     byte[] hashBytes = sha1.ComputeHash(buffer);
     return BufferToString(hashBytes);
 }
 private string Hash(FileStream stream)
 {
     SHA1Managed sha1 = new SHA1Managed();
     byte[] hashBytes = sha1.ComputeHash(stream);
     return BufferToString(hashBytes);
 }
 // TODO: refactor, this is a copy/paste from ObjectForScripting
 private string Hash(FileInfo fileInfo)
 {
     SHA1Managed sha1 = new SHA1Managed();
     FileStream inFile = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read);
     return Hash(inFile);
 }*/
 private string FileHash(byte[] buffer)
 {
     MemoryStream ms = new MemoryStream(buffer,false);
     SHA1Managed sha1 = new SHA1Managed();
     return string.Concat(from b in sha1.ComputeHash(ms)
                          select b.ToString("X2"));
 }
Ejemplo n.º 22
0
 /// <summary>
 /// SHA1非对称加密.用于密码加密,使用SHA1Managed类产生长度为160位哈希值.
 /// </summary>
 /// <param name="text">传入一个任意长字符串.</param>
 /// <returns>返回长度为28字节的字符串.</returns>
 public static string GetSHA1(string text)
 {
     byte[] byteSHA1 = System.Text.Encoding.UTF8.GetBytes(text);
     var sha1 = new SHA1Managed();
     byte[] result = sha1.ComputeHash(byteSHA1);
     return Convert.ToBase64String(result);
 }
Ejemplo n.º 23
0
 internal static string CalculateSHA1(string text)
 {
     SHA1Managed s = new SHA1Managed();
     UTF8Encoding enc = new UTF8Encoding();
     s.ComputeHash(enc.GetBytes(text.ToCharArray()));
     return BitConverter.ToString(s.Hash).Replace("-", "");
 }
Ejemplo n.º 24
0
        static void GenKey(string baseName, out byte[] desKey, out byte[] desIV)
        {
            byte[] secretBytes = { 6, 29, 66, 6, 2, 68, 4, 7, 70 };

            byte[] baseNameBytes = new ASCIIEncoding().GetBytes(baseName);

            byte[] hashBytes = new byte[secretBytes.Length + baseNameBytes.Length];

            // copy secret byte to start of hash array
            for (int i = 0; i < secretBytes.Length; i++)
            {
                hashBytes[i] = secretBytes[i];
            }

            // copy filename byte to end of hash array
            for (int i = 0; i < baseNameBytes.Length; i++)
            {
                hashBytes[i + secretBytes.Length] = baseNameBytes[i];
            }

            SHA1Managed sha = new SHA1Managed();

            // run the sha1 hash
            byte[] hashResult = sha.ComputeHash(hashBytes);

            desKey = new byte[8];
            desIV = new byte[8];

            for (int i = 0; i < 8; i++)
            {
                desKey[i] = hashResult[i];
                desIV[i] = hashResult[8 + i];
            }
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Empaqquete un DIscoInfo
 /// </summary>
 /// <param name="info">DicoInfo</param>
 /// <returns>Ampaquetage</returns>
 public static string DiscoInfoToVersion(DiscoInfo info)
 {
     StringBuilder builder = new StringBuilder(256);
     DiscoIdentity[] identities = info.GetIdentities();
     string[] ids = new string[identities.Length];
     for (int i = 0; i < identities.Length; i++)
     {
         ids[i] = string.Format("{0}/{1}", identities[i].Category, identities[i].Type);
     }
     Array.Sort(ids);
     foreach (string id in ids)
     {
         builder.AppendFormat("{0}<", id);
     }
     DiscoFeature[] features = info.GetFeatures();
     string[] feas = new string[features.Length];
     for (int i = 0; i < features.Length; i++)
     {
         feas[i] = features[i].Var;
     }
     Array.Sort(feas);
     foreach (string fea in feas)
     {
         builder.AppendFormat("{0}<", fea);
     }
     SHA1Managed sha1 = new SHA1Managed();
     byte[] hash = sha1.ComputeHash(Encoding.Unicode.GetBytes(builder.ToString()));
     return Convert.ToBase64String(hash);
 }
Ejemplo n.º 26
0
 public string GenerateSha1Hash(string str)
 {
     SHA1Managed sha1 = new SHA1Managed();
     var hash = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
     string hex = BitConverter.ToString(hash);
     return hex.Replace("-", "").ToLower();
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Computes hash for password
 /// </summary>
 /// <param name="password">Password to encrypt</param>
 /// <returns>Encrypted password</returns>
 public static string ComputeHash(string password)
 {
     SHA1Managed sha = new SHA1Managed();
       byte[] data = Encoding.Unicode.GetBytes(password);
       string hash = Convert.ToBase64String(sha.ComputeHash(data));
       return hash;
 }
Ejemplo n.º 28
0
        private String CreateWsseHeader()
        {
            // HTTPリクエスト毎に生成するセキュリティ・トークン(ランダム文字列)
            byte[] b_nonce = new byte[8];
            Random rand = new Random();
            rand.NextBytes( b_nonce );

            // nonce 生成時の日
            string created = DateTime.Now.ToUniversalTime().ToString( "o" );
            byte[] b_created = Encoding.UTF8.GetBytes( created );

            byte[] b_password = Encoding.UTF8.GetBytes( Password );
            SHA1Managed sh1 = new SHA1Managed();
            sh1.Initialize();

            // Join
            byte[] origin = new byte[b_nonce.Length + b_created.Length + b_password.Length];
            Array.Copy( b_nonce, 0, origin, 0, b_nonce.Length );
            Array.Copy( b_created, 0, origin, b_nonce.Length, b_created.Length );
            Array.Copy( b_password, 0, origin, b_nonce.Length + b_created.Length, b_password.Length );

            // Create Hash Value
            byte[] passwordDigest = sh1.ComputeHash( origin );

            string header = String.Format(
                "UsernameToken Username=\"{0}\", PasswordDigest=\"{1}\", Nonce=\"{2}\", Created=\"{3}\"",
                Username, Convert.ToBase64String( passwordDigest ), Convert.ToBase64String( b_nonce ), created );

            return header;
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Performs an SHA1 hash of an input byte array
 /// </summary>
 public static byte[] SHAHash( byte[] input )
 {
     using ( var sha = new SHA1Managed() )
     {
         return sha.ComputeHash( input );
     }
 }
Ejemplo n.º 30
0
 public string GenerateSHA1Hash(string str)
 {
     SHA1Managed sha1 = new SHA1Managed();
     var hash = sha1.ComputeHash(StringToAscii(str));
     string hex = BitConverter.ToString(hash);
     return hex.Replace("-", "").ToLower();
 }
Ejemplo n.º 31
0
 /// <summary>
 /// 加密字符串
 /// </summary>
 /// <param name="inputStr">输入字符串</param>
 /// <param name="keyStr">密码,可以为“”</param>
 /// <returns>输出加密后字符串</returns>
 public string EncryptString(string inputStr, string keyStr)
 {
     DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     if (keyStr == "")
         keyStr = key;
     byte[] inputByteArray = Encoding.Default.GetBytes(inputStr);
     byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);
     SHA1 ha = new SHA1Managed();
     byte[] hb = ha.ComputeHash(keyByteArray);
     sKey = new byte[8];
     sIV = new byte[8];
     for (int i = 0; i < 8; i++)
         sKey[i] = hb[i];
     for (int i = 8; i < 16; i++)
         sIV[i - 8] = hb[i];
     des.Key = sKey;
     des.IV = sIV;
     MemoryStream ms = new MemoryStream();
     CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
     cs.Write(inputByteArray, 0, inputByteArray.Length);
     cs.FlushFinalBlock();
     StringBuilder ret = new StringBuilder();
     foreach (byte b in ms.ToArray())
     {
         ret.AppendFormat("{0:X2}", b);
     }
     cs.Close();
     ms.Close();
     return ret.ToString();
 }
Ejemplo n.º 32
0
 //password hashing
 private string GetHash()
 {
     using (var hash = new System.Security.Cryptography.SHA1Managed())
     {
         var hashbytes = System.Text.Encoding.UTF8.GetBytes(Password);
         return(Convert.ToBase64String(hash.ComputeHash(hashbytes)));
     }
 }
Ejemplo n.º 33
0
        // Seeds PRNG with first 32 bits of hashed input from tf_randomSeed textbox
        private void glitchSpeak_Click(object sender, RoutedEventArgs e)
        {
            HashAlgorithm hasher = new System.Security.Cryptography.SHA1Managed();
            var           bytes  = hasher.ComputeHash(Encoding.Unicode.GetBytes(tf_randomSeed.Text));
            var           hash   = string.Join("", bytes.Select(x => x.ToString("x2")).ToArray());

            rand = new Random(Convert.ToInt32(hash.Substring(0, 8), 16));
        }
Ejemplo n.º 34
0
        public static string SHA1(string input)
        {
            System.Security.Cryptography.SHA1Managed sha1 = new System.Security.Cryptography.SHA1Managed();
            byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
            sha1.Dispose();
            StringBuilder sb = new StringBuilder(hash.Length * 2);

            foreach (byte b in hash) // can be "x2" if you want lowercase
            {
                sb.Append(b.ToString("x2"));
            }
            return(sb.ToString());
        }
Ejemplo n.º 35
0
 public static string SHA1file(byte[] buffer)
 {
     try
     {
         System.Security.Cryptography.SHA1Managed Sha1 = new System.Security.Cryptography.SHA1Managed();
         byte[] retVal = Sha1.ComputeHash(buffer);
         return(System.Convert.ToBase64String(retVal));
     }
     catch (Exception ex)
     {
         throw new Exception("SHA1file() fail, error:" + ex.Message);
     }
 }
Ejemplo n.º 36
0
 public static string SHA1file(string file)
 {
     try
     {
         FileStream fs = new FileStream(file, FileMode.Open);
         System.Security.Cryptography.SHA1Managed Sha1 = new System.Security.Cryptography.SHA1Managed();
         byte[] retVal = Sha1.ComputeHash(fs);
         fs.Close();
         return(System.Convert.ToBase64String(retVal));
     }
     catch (Exception ex)
     {
         throw new Exception("SHA1file() fail, error:" + ex.Message);
     }
 }
Ejemplo n.º 37
0
        /// <summary>
        /// 获取字符串的Hash字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToHashText(this string str)
        {
            if (String.IsNullOrEmpty(str))
            {
                return(String.Empty);
            }

            using (var sha1 = new System.Security.Cryptography.SHA1Managed())
            {
                byte[] textData = System.Text.Encoding.UTF8.GetBytes(str);

                byte[] hash = sha1.ComputeHash(textData);

                return(BitConverter.ToString(hash).Replace("-", String.Empty));
            }
        }
Ejemplo n.º 38
0
        private string HashFiles(IEnumerable <VstsFile> files)
        {
            StringBuilder builder = new StringBuilder();

            foreach (var f in files.OrderBy(f => f.Path))
            {
                builder.Append(f.Blob.Id);
                builder.Append(f.Path);
            }
            var bytes  = Encoding.UTF8.GetBytes(builder.ToString());
            var hasher = new System.Security.Cryptography.SHA1Managed();
            var hash   = hasher.ComputeHash(bytes);

            //really we want to encode as base36
            return(System.BitConverter.ToString(hash).Replace("-", "").ToLower());
        }
Ejemplo n.º 39
0
        internal static string getSha1Hash(string text)
        {
            if (String.IsNullOrEmpty(text))
            {
                return(String.Empty);
            }

            using (var sha1 = new System.Security.Cryptography.SHA1Managed())
            {
                byte[] textData = Encoding.UTF8.GetBytes(text);

                byte[] hash = sha1.ComputeHash(textData);

                return(BitConverter.ToString(hash).Replace("-", String.Empty));
            }
        }
Ejemplo n.º 40
0
        public byte[] GetPublicKeyToken()
        {
            if (public_key == null || public_key_token != null)
            {
                return(public_key_token);
            }

            HashAlgorithm ha = new System.Security.Cryptography.SHA1Managed();

            byte[] hash = ha.ComputeHash(public_key);
            // we need the last 8 bytes in reverse order
            public_key_token = new byte[8];
            Buffer.BlockCopy(hash, hash.Length - 8, public_key_token, 0, 8);
            Array.Reverse(public_key_token, 0, 8);
            return(public_key_token);
        }
Ejemplo n.º 41
0
        public static string GetSHA1Hash(string str)
        {
            Encoder enc = System.Text.Encoding.Unicode.GetEncoder();

            byte[] unicodeText = new byte[str.Length * 2];
            enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true);

            System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1Managed();

            byte[] result = sha.ComputeHash(unicodeText);

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString());
            }
            return(sb.ToString());
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Gets SHA1 hash of a byte array
        /// </summary>
        /// <param name="buffer">Byte array</param>
        /// <returns>SHA1 hash as string</returns>
        public static string SHA1(byte[] buffer)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();

            return(BitConverter.ToString(sha1.ComputeHash(buffer)).Replace("-", ""));
        }
Ejemplo n.º 43
0
 public static string GetHashSHA1(Stream data)
 {
     System.Security.Cryptography.SHA1Managed sha = new System.Security.Cryptography.SHA1Managed();
     byte[] result = sha.ComputeHash(data);
     return(Convert.ToBase64String(result));
 }
Ejemplo n.º 44
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
        {
            if (!request.Headers.Contains("Signature") && !request.Headers.Contains("SignatureCertChainUrl"))
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            var signatureCertChainUrl = request.Headers.GetValues("SignatureCertChainUrl").First().Replace("/../", "/");

            if (string.IsNullOrWhiteSpace(signatureCertChainUrl))
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            var certUrl = new Uri(signatureCertChainUrl);

            if (!((certUrl.Port == 443 && certUrl.IsDefaultPort) &&
                  certUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) &&
                  certUrl.Host.Equals("s3.amazonaws.com", StringComparison.OrdinalIgnoreCase) &&
                  certUrl.AbsolutePath.StartsWith("/echo.api/")))
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }


            // download the certificate
            using (var web = new System.Net.WebClient())
            {
                var certificate = web.DownloadData(certUrl);
                var cert        = new X509Certificate2(certificate);

                var expiryDate    = DateTime.MinValue;
                var effectiveDate = DateTime.MinValue;

                if (DateTime.TryParse(cert.GetExpirationDateString(), out expiryDate) &&
                    expiryDate < DateTime.UtcNow && DateTime.TryParse(cert.GetEffectiveDateString(), out effectiveDate) && effectiveDate < DateTime.UtcNow)
                {
                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
                }
                if (!cert.Subject.Contains("CN=echo-api.amazon.com"))
                {
                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
                }


                var signatureString = request.Headers.GetValues("Signature").First();

                byte[] signature = Convert.FromBase64String(signatureString);


                using (var sha1 = new System.Security.Cryptography.SHA1Managed())
                {
                    var body = await request.Content.ReadAsStringAsync();

                    var data = sha1.ComputeHash(Encoding.UTF8.GetBytes(body));

                    var rsa = (RSACryptoServiceProvider)cert.PublicKey.Key;

                    if (!rsa.VerifyHash(data, CryptoConfig.MapNameToOID("SHA1"), signature))
                    {
                        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
                    }
                }
            }

            return(await base.SendAsync(request, token));
        }
Ejemplo n.º 45
0
 // Получить код хеш устройства С:
 public static byte[] HashHardvare()
 {
     System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1Managed();
     return(sha.ComputeHash(HardwareKey()));
 }