Exemple #1
0
 internal static SHA512 CreateSHA512()
 {
     return(SHA512.Create());
 }
Exemple #2
0
 public static string GetSHA512FileSystemSafeHash(this string input) => GetFileSystemSafeHash(input, SHA512.Create());
 public void TestHMAC(byte[] k, byte[] d)
 {
     Assert.Equal(new HMACMD5(k).ComputeHash(d).AsEnumerable(), new GenericHMAC <MD5>(MD5.Create(), 64, k).ComputeHash(d));
     Assert.Equal(new HMACSHA1(k).ComputeHash(d).AsEnumerable(), new GenericHMAC <SHA1>(SHA1.Create(), 64, k).ComputeHash(d));
     Assert.Equal(new HMACSHA256(k).ComputeHash(d).AsEnumerable(), new GenericHMAC <SHA256>(SHA256.Create(), 64, k).ComputeHash(d));
     Assert.Equal(new HMACSHA512(k).ComputeHash(d).AsEnumerable(), new GenericHMAC <SHA512>(SHA512.Create(), 128, k).ComputeHash(d));
 }
 public HashService()
 {
     hasher = SHA512.Create();
 }
Exemple #5
0
 public static string GetSHA512Hash(this string input) => GetHash(input, SHA512.Create());
Exemple #6
0
        public static void Main(string[] args)
        {
            DateTime startTime = DateTime.Now;

            Console.WriteLine("Findup.exe v2.0 - By James Gentile - [email protected] - 2012.");
            Console.WriteLine("Findup.exe matches sizes, then SHA512 hashes to identify duplicate files.");
            Console.WriteLine(" ");
            string          optionskey = "-paths";
            List <FileInfo> files      = new List <FileInfo>();
            int             i          = 0;

            for (i = 0; i < args.Length; i++)
            {
                string argitem = args[i].ToLower();

                if ((System.String.Compare(argitem, "-help", true) == 0) || (System.String.Compare(argitem, "-h", true) == 0))
                {
                    Console.WriteLine("Usage:    findup.exe <file/directory #1..#N> [-recurse] [-noerr] [-x/-i/-xd/-id/-xf/-if] <files/directories/regex> [-regex] [-delete]");
                    Console.WriteLine(" ");
                    Console.WriteLine("Options:  -help     - displays this help message.");
                    Console.WriteLine("          -recurse  - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified.");
                    Console.WriteLine("          -noerr    - discards error messages.");
                    Console.WriteLine("          -delete   - delete each duplicate file with confirmation.");
                    Console.WriteLine("          -x        - eXcludes if full file path starts with (or RegEx matches if -xr) one of the items following this switch until another switch is used.");
                    Console.WriteLine("          -i        - include if full file path starts with (or Regex matches if -ir) one of the items following this switch until another switch is used.");
                    Console.WriteLine("          -xd       - eXcludes all directories (using RegEx if -xdr) including subdirs following this switch until another switch is used.");
                    Console.WriteLine("          -id       - Include only directories (using RegEx if -idr) including subdirs following this switch until another switch is used.");
                    Console.WriteLine("          -xf       - eXcludes all files (using RegEx if -xfr) following this switch until another switch is used.");
                    Console.WriteLine("          -if       - Include only files (using RegEx if -ifr) following this switch until another switch is used.");
                    Console.WriteLine("          [r]       - Use regex for include/exclude by appending an 'r' to the option, e.g. -ir, -ifr, -idr, -xr, -xfr, -xdr.");
                    Console.WriteLine("          -paths    - not needed unless you want to specify files/dirs after an include/exclude without using another non-exclude/non-include option.");
                    Console.WriteLine(" ");
                    Console.WriteLine("Examples: findup.exe c:\\finances -recurse -noerr");
                    Console.WriteLine("                     - Find dupes in c:\\finance.");
                    Console.WriteLine("                     - recurse all subdirs of c:\\finance.");
                    Console.WriteLine("                     - suppress error messages.");
                    Console.WriteLine("          findup.exe c:\\users\\alice\\plan.txt d:\\data -recurse -x d:\\data\\webpics");
                    Console.WriteLine("                     - Find dupes in c:\\users\\alice\\plan.txt, d:\\data");
                    Console.WriteLine("                     - recurse subdirs in d:\\data.");
                    Console.WriteLine("                     - exclude any files in d:\\data\\webpics and subdirs.");
                    Console.WriteLine("          findup.exe c:\\data *.txt c:\\reports\\quarter.doc -xr \"(jim)\" -regex");
                    Console.WriteLine("                     - Find dupes in c:\\data, *.txt in current directory and c:\\reports\\quarter.doc");
                    Console.WriteLine("                     - exclude any file with 'jim' in the name as specified by the Regex item \"(jim)\"");
                    Console.WriteLine("          findup.exe c:\\data *.txt c:\\reports\\*quarter.doc -xr \"[bf]\" -ir \"(smith)\" -regex");
                    Console.WriteLine("                     - Find dupes in c:\\data, *.txt in current directory and c:\\reports\\*quarter.doc");
                    Console.WriteLine("                     - Include only files with 'smith' and exclude any file with letters b or f in the name as specified by the Regex items \"[bf]\",\"(smith)\"");
                    Console.WriteLine("Note:     Exclude takes precedence over Include.");
                    Console.WriteLine("          -xdr,-idr,-xfr,-ifr are useful if for instance you want to apply a RegEx to only file names but not directory names or vice versa.");
                    Console.WriteLine("          if for instance you wanted all files that contained the letter \"d\" on your D: drive but didn't want the d:\\ to cause all files on the d:\\ ");
                    Console.WriteLine("          drive to be included, you would specify:");
                    Console.WriteLine("          findup.exe d:\\ -recurse -noerr -regex -ifr \"[d]\"  ");
                    return;
                }
                if (optionsbools.ContainsKey(argitem))
                {
                    optionsbools[argitem] = true;
                    optionskey            = "-paths";
                    continue;
                }
                if (optionspaths.ContainsKey(argitem) || optionsregex.ContainsKey(argitem))
                {
                    optionskey = argitem;
                    continue;
                }
                if (optionspaths.ContainsKey(optionskey))
                {
                    optionspaths[optionskey].Add(argitem);
                }
                else
                {
                    try {
                        Regex rgx = new Regex(argitem, RegexOptions.Compiled);
                        optionsregex[optionskey].Add(rgx);
                    }
                    catch (Exception e) { WriteErr("Regex compilation failed: " + e.Message); }
                }
            }
            if (optionspaths["-paths"].Count == 0)
            {
                WriteErr("No files, file specifications, or directories specified. Try findup.exe -help. Assuming current directory.");
                optionspaths["-paths"].Add(".");
            }
            Console.Write("Getting file info and sorting file list...");
            getFiles(optionspaths["-paths"], "*.*", optionsbools["-recurse"], files);

            if (files.Count < 2)
            {
                WriteErr("\nFindup.exe needs at least 2 files to compare. Try findup.exe -help");
                return;
            }

            files.Sort(new FileLengthComparer());
            Console.WriteLine("Completed!");

            Console.Write("Building dictionary of file sizes, SHA512 hashes and full paths...");

            var SizeHashName = new Dictionary <long, Dictionary <string, List <FileInfo> > >();

            for (i = 0; i < (files.Count - 1); i++)
            {
                if (files[i].Length != files[i + 1].Length)
                {
                    continue;
                }
                var breakout = false;
                while (true)
                {
                    try
                    {
                        var _SHA512 = SHA512.Create();
                        using (var fstream = File.OpenRead(files[i].FullName))
                        {
                            _SHA512.ComputeHash(fstream);
                        }
                        string SHA512string = "";
                        foreach (var c in _SHA512.Hash)
                        {
                            SHA512string += String.Format("{0:x2}", c);
                        }

                        if (!SizeHashName.ContainsKey(files[i].Length))
                        {
                            SizeHashName.Add(files[i].Length, new Dictionary <string, List <FileInfo> >());
                        }
                        if (!SizeHashName[files[i].Length].ContainsKey(SHA512string))
                        {
                            SizeHashName[files[i].Length][SHA512string] = new List <FileInfo>()
                            {
                            }
                        }
                        ;
                        SizeHashName[files[i].Length][SHA512string].Add(files[i]);
                    }
                    catch (Exception e) { WriteErr("Hash error: " + e.Message); }

                    if (breakout == true)
                    {
                        break;
                    }
                    i++;
                    if (i == (files.Count - 1))
                    {
                        breakout = true; continue;
                    }
                    breakout = (files[i].Length != files[i + 1].Length);
                }
            }

            Console.WriteLine("Completed!");

            foreach (var SizeGroup in SizeHashName)
            {
                foreach (var HashGroup in SizeGroup.Value)
                {
                    var SGK  = (long)SizeGroup.Key;
                    var HGVC = (long)HashGroup.Value.Count;
                    if (HGVC > 1)
                    {
                        Console.WriteLine("{0:N0} Duplicate files. {1:N0} Bytes each. {2:N0} Bytes total : ", HGVC, SGK, SGK * HGVC);
                        foreach (var Filenfo in HashGroup.Value)
                        {
                            Console.WriteLine(Filenfo.FullName);
                            numOfDupes++;
                            dupeBytes += Filenfo.Length;
                            if (optionsbools["-delete"])
                            {
                                if (DeleteDupe(Filenfo))
                                {
                                    bytesrecovered += Filenfo.Length;
                                }
                            }
                        }
                    }
                }
            }

            Console.WriteLine("\n ");
            Console.WriteLine("Files checked      : {0:N0}", files.Count);              // display statistics and return to OS.
            Console.WriteLine("Duplicate files    : {0:N0}", numOfDupes);
            Console.WriteLine("Duplicate bytes    : {0:N0}", dupeBytes);
            Console.WriteLine("Deleted duplicates : {0:N0}", deletedfiles);
            Console.WriteLine("Bytes recovered    : {0:N0}", bytesrecovered);
            Console.WriteLine("Execution time     : " + (DateTime.Now - startTime));
        }
        /*------------------------ FIELDS REGION ------------------------*/

        /*------------------------ METHODS REGION ------------------------*/
        public string ComputeHashFromStringToString(string valueToHash)
        {
            return(Encoding.UTF8.GetString(
                       SHA512.Create().ComputeHash(Encoding.UTF8.GetBytes(valueToHash))
                       ));
        }
 public Criptografia()
 {
     _algoritmo = SHA512.Create();
 }
Exemple #9
0
        public void SignVerify_InteroperableSameKeys_RoundTripsUnlessTampered(ECDsa ecdsa, HashAlgorithmName hashAlgorithm)
        {
            byte[] data = Encoding.UTF8.GetBytes("something to repeat and sign");

            // large enough to make hashing work though multiple iterations and not a multiple of 4KB it uses.
            byte[]       dataArray  = new byte[33333];
            MemoryStream dataStream = new MemoryStream(dataArray, true);

            while (dataStream.Position < dataArray.Length - data.Length)
            {
                dataStream.Write(data, 0, data.Length);
            }

            dataStream.Position = 0;

            byte[] dataArray2 = new byte[dataArray.Length + 2];
            dataArray.CopyTo(dataArray2, 1);
            ArraySegment <byte> dataSpan = new ArraySegment <byte>(dataArray2, 1, dataArray.Length);

            HashAlgorithm halg;

            if (hashAlgorithm == HashAlgorithmName.MD5)
            {
                halg = MD5.Create();
            }
            else if (hashAlgorithm == HashAlgorithmName.SHA1)
            {
                halg = SHA1.Create();
            }
            else if (hashAlgorithm == HashAlgorithmName.SHA256)
            {
                halg = SHA256.Create();
            }
            else if (hashAlgorithm == HashAlgorithmName.SHA384)
            {
                halg = SHA384.Create();
            }
            else if (hashAlgorithm == HashAlgorithmName.SHA512)
            {
                halg = SHA512.Create();
            }
            else
            {
                throw new Exception("Hash algorithm not supported.");
            }

            List <byte[]> signatures = new List <byte[]>(6);

            // Compute a signature using each of the SignData overloads.  Then, verify it using each
            // of the VerifyData overloads, and VerifyHash overloads.
            //
            // Then, verify that VerifyHash fails if the data is tampered with.

            signatures.Add(ecdsa.SignData(dataArray, hashAlgorithm));

            signatures.Add(ecdsa.SignData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, hashAlgorithm));

            signatures.Add(ecdsa.SignData(dataStream, hashAlgorithm));
            dataStream.Position = 0;

            signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataArray)));

            signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count)));

            signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataStream)));
            dataStream.Position = 0;

            foreach (byte[] signature in signatures)
            {
                Assert.True(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify 1");

                Assert.True(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify 2");

                Assert.True(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify 3");
                Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3A");
                dataStream.Position = 0;

                Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify 4");

                Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify 5");

                Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify 6");
                Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6A");
                dataStream.Position = 0;
            }

            int distinctSignatures = signatures.Distinct(new ByteArrayComparer()).Count();

            Assert.True(distinctSignatures == signatures.Count, "Signing should be randomized");

            foreach (byte[] signature in signatures)
            {
                signature[signature.Length - 1] ^= 0xFF; // flip some bits

                Assert.False(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify Tampered 1");

                Assert.False(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify Tampered 2");

                Assert.False(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify Tampered 3");
                Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3B");
                dataStream.Position = 0;

                Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify Tampered 4");

                Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify Tampered 5");

                Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify Tampered 6");
                Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6B");
                dataStream.Position = 0;
            }
        }
Exemple #10
0
        /// <summary>
        /// Computes the SHA-512 hash of the given string using UTF8 byte encoding.
        /// </summary>
        /// <param name="value">The input string.</param>
        /// <param name="createHasher">if set to <c>true</c> [create hasher].</param>
        /// <returns>
        /// The computes a Hash-based Message Authentication Code (HMAC)
        /// using the SHA512 hash function.
        /// </returns>
        public static byte[] ComputeSha512(string value, bool createHasher = false)
        {
            var inputBytes = Encoding.UTF8.GetBytes(value);

            return((createHasher ? SHA512.Create() : SHA512Hasher.Value).ComputeHash(inputBytes));
        }
Exemple #11
0
        public static byte[] GetCheckSum(byte[] file)
        {
            var sha = SHA512.Create();

            return(sha.ComputeHash(file));
        }
Exemple #12
0
 /// <summary>
 /// Initialise the CPRNG with the given key material, and default cypher (AES 256) and hash algorithm (SHA512), zero counter and supplied additional entropy source.
 /// </summary>
 public CypherBasedPrngGenerator(byte[] key, Func <byte[]> additionalEntropyGetter)
     : this(key, BlockCypherCryptoPrimitive.Aes256(), SHA512.Create(), new CypherCounter(16), 1024, additionalEntropyGetter)
 {
 }
Exemple #13
0
 /// <summary>
 /// Initialise the CPRNG with the given key material, and default cypher (AES 256) and hash algorithm (SHA512), and zero counter.
 /// </summary>
 public CypherBasedPrngGenerator(byte[] key)
     : this(key, BlockCypherCryptoPrimitive.Aes256(), SHA512.Create(), new CypherCounter(16), 1024, null)
 {
 }
        public static RootCommand WireUpSha512Commands(this RootCommand rootCommand)
        {
            var sha512Command     = new Command("sha512", "SHA512");
            var sha512HashCommand = new Command("hash", "Hash");

            sha512HashCommand.AddOption(new Option(new string[] { "--text", "-t" }, "Input Text")
            {
                Argument = new Argument <string>("text")
            });
            sha512HashCommand.AddOption(new Option(new string[] { "--input", "-i" }, "Input file path")
            {
                Argument = new Argument <FileInfo>("input")
            });
            sha512HashCommand.AddOption(new Option(new string[] { "--output", "-o" }, "Output file path")
            {
                Argument = new Argument <FileInfo>("output")
            });
            sha512HashCommand.Handler = CommandHandler.Create <string, FileInfo, FileInfo, IConsole>(async(text, input, output, console) =>
            {
                Stream outputStream = null;
                Stream inputStream  = null;
                try
                {
                    if (output == null)
                    {
                        outputStream = new MemoryStream();
                    }
                    else
                    {
                        outputStream = output.OpenWrite();
                    }

                    if (text != null)
                    {
                        inputStream = new MemoryStream(Encoding.UTF8.GetBytes(text));
                    }
                    if (input != null)
                    {
                        inputStream = input.OpenRead();
                    }

                    using var sha512 = SHA512.Create();
                    var hashBytes    = sha512.ComputeHash(inputStream);
                    if (output == null)
                    {
                        console.Out.WriteLine(hashBytes.ToHexString());
                    }
                    else
                    {
                        await outputStream.WriteAsync(hashBytes);
                    }
                }
                catch (Exception ex)
                {
                    console.Out.WriteLine(ex.Message);
                }
                finally
                {
                    if (inputStream != null)
                    {
                        await inputStream.DisposeAsync();
                    }
                    if (outputStream != null)
                    {
                        await outputStream.DisposeAsync();
                    }
                }
            });

            sha512Command.Add(sha512HashCommand);
            rootCommand.AddCommand(sha512Command);

            return(rootCommand);
        }
Exemple #15
0
 /// <summary>
 /// 验证 SHA512 值
 /// </summary>
 /// <param name="input"> 未加密的字符串 </param>
 /// <param name="encoding"> 字符编码 </param>
 /// <returns></returns>
 public static bool VerifySha512Value(string input, Encoding encoding)
 {
     return(VerifyHashValue(SHA512.Create(), input, Sha512Encrypt(input, encoding), encoding));
 }
Exemple #16
0
 /// <summary>
 /// SHA512 加密
 /// </summary>
 /// <param name="input"> 要加密的字符串 </param>
 /// <param name="encoding"> 字符编码 </param>
 /// <returns></returns>
 public static string Sha512Encrypt(string input, Encoding encoding)
 {
     return(HashEncrypt(SHA512.Create(), input, encoding));
 }