Ejemplo n.º 1
0
 [System.Security.SecuritySafeCritical]  // auto-generated 
 public HMACSHA384 (byte[] key) { 
     m_hashName = "SHA384";
     m_hash1 = new SHA384Managed(); 
     m_hash2 = new SHA384Managed();
     HashSizeValue = 384;
     BlockSizeValue = BlockSize;
     base.InitializeKey(key); 
 }
        [System.Security.SecuritySafeCritical]  // auto-generated
        public HMACSHA384 (byte[] key) {
            m_hashName = "SHA384";
#if FULL_AOT_RUNTIME
            m_hash1 = new SHA384Managed();
            m_hash2 = new SHA384Managed();
#else
            m_hash1 = GetHashAlgorithmWithFipsFallback(() => new SHA384Managed(), () => HashAlgorithm.Create("System.Security.Cryptography.SHA384CryptoServiceProvider"));
            m_hash2 = GetHashAlgorithmWithFipsFallback(() => new SHA384Managed(), () => HashAlgorithm.Create("System.Security.Cryptography.SHA384CryptoServiceProvider"));
#endif
            HashSizeValue = 384;
            BlockSizeValue = BlockSize;
            base.InitializeKey(key);
        }
Ejemplo n.º 3
0
	SHA384Managed (SHA384Managed other)
	{
		xBuf = new byte [other.xBuf.Length];
		Array.Copy (other.xBuf, xBuf, xBuf.Length);
		xBufOff = other.xBufOff;
		byteCount1 = other.byteCount1;
		byteCount2 = other.byteCount2;
		H1 = other.H1;
		H2 = other.H2;
		H3 = other.H3;
		H4 = other.H4;
		H5 = other.H5;
		H6 = other.H6;
		H7 = other.H7;
		H8 = other.H8;
		W = new ulong [other.W.Length];
		Array.Copy (other.W, W, W.Length);
		wOff = other.wOff;
	}
Ejemplo n.º 4
0
    //AIM: THIS FUNCTION IS USE to encrypt the string and create hask key using diff hash methods
    public string FromString(string input, HashType hashtype)
    {
        Byte[] clearBytes;
            Byte[] hashedBytes;
            string output = String.Empty;

            switch (hashtype)
            {
                case HashType.RIPEMD160:
                    clearBytes = new UTF8Encoding().GetBytes(input);
                    RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
                    hashedBytes = myRIPEMD160.ComputeHash(clearBytes);
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.MD5:
                    clearBytes = new UTF8Encoding().GetBytes(input);
                    hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA1:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                    sha1.ComputeHash(clearBytes);
                    hashedBytes = sha1.Hash;
                    sha1.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA256:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA256 sha256 = new SHA256Managed();
                    sha256.ComputeHash(clearBytes);
                    hashedBytes =sha256.Hash;

                    sha256.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA384:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA384 sha384 = new SHA384Managed();
                    sha384.ComputeHash(clearBytes);
                    hashedBytes = sha384.Hash;
                    sha384.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA512:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA512 sha512 = new SHA512Managed();
                    sha512.ComputeHash(clearBytes);
                    hashedBytes = sha512.Hash;
                    sha512.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
            }
            return output;
    }
        public static IHtmlString SRIResourceWithTags(this HtmlHelper helper, string linkWithTags)
        {
            if (_dictionary.ContainsKey(linkWithTags))
            {
                var foo = _dictionary[linkWithTags];
                if (foo != "local")
                {
                    return(new HtmlString(_dictionary[linkWithTags]));
                }
                else
                {
                    return(new HtmlString(linkWithTags));
                }
            }

            if (string.IsNullOrWhiteSpace(linkWithTags))
            {
                return(new HtmlString(string.Empty));
            }
            if (ConfigHelper.SriThrowIfUsed)
            {
                throw new Exception("SubResourceIntegrityHelper is in use for link: " + linkWithTags);
            }

            var filePath = ConfigHelper.SriFilePath;

            if (filePath != null && !filePath.Contains(Path.DirectorySeparatorChar))
            {
                try
                {
                    var p         = helper.ViewContext.Controller.ControllerContext.HttpContext.Server.MapPath("/");
                    var localPath = Path.Combine(p, filePath);
                    if (!File.Exists(localPath))
                    {
                        filePath = null;
                    }
                    else
                    {
                        filePath = localPath;
                    }
                }
                catch (Exception)
                {
                    try
                    {
                        var loc       = typeof(SubResourceIntegrityHelper).Assembly.Location;
                        var p         = Path.GetDirectoryName(loc);
                        var localPath = Path.Combine(p, filePath);
                        if (!File.Exists(localPath))
                        {
                            filePath = null;
                        }
                        else
                        {
                            filePath = localPath;
                        }
                    }
                    catch (Exception)
                    {
                        filePath = null;
                    }
                }
            }

            if (filePath != null)
            {
                if (File.Exists(filePath))
                {
                    var lines = File.ReadAllLines(filePath);
                    foreach (var line in lines)
                    {
                        if (!string.IsNullOrWhiteSpace(line) && line.Contains("\t"))
                        {
                            var parts = line.Split('\t');
                            if (parts.Length == 2)
                            {
                                if (!_dictionary.ContainsKey(parts[0]))
                                {
                                    _dictionary.Add(parts[0], parts[1]);
                                }
                            }
                        }
                    }
                }
                else
                {
                    try
                    {
                        if (filePath != null)
                        {
                            using (var fs = File.Create(filePath))
                            {
                            }
                        }
                    }
                    catch (Exception)
                    {
                        return(new HtmlString(
                                   "<script src=\"CAN NOT WRITE TO SubResourceIntegrityHelper_FilePath\" />"));
                    }
                }

                if (_dictionary.ContainsKey(linkWithTags))
                {
                    return(new HtmlString(_dictionary[linkWithTags]));
                }

                if (ConfigHelper.SriDownloadIfNotPresentInFile)
                {
                    var r = Regex.Match(linkWithTags, ".*(<script|<link){1}.*(src=\"|href=\"){1}([^\"]*)(.*)",
                                        RegexOptions.IgnoreCase);
                    if (r.Groups.Count == 5)
                    {
                        var isScript = string.Compare(r.Groups[1].Value, "<script",
                                                      StringComparison.InvariantCultureIgnoreCase) == 0;
                        var uriInLink = r.Groups[3].Value;
                        if (!string.IsNullOrWhiteSpace(uriInLink))
                        {
                            string uriToGet = null;
                            if (!(CultureInfo.CurrentCulture.CompareInfo.IndexOf(uriInLink, "integrity=\"", CompareOptions.IgnoreCase) >= 0))
                            {
                                bool isLocalUri = !uriInLink.StartsWith("http", true, CultureInfo.CurrentCulture);
                                if (isLocalUri)
                                {
                                    var basePath = ConfigHelper.SriInsteadOfTilde;
                                    if (string.IsNullOrWhiteSpace(basePath))
                                    {
                                        if (uriInLink.StartsWith("~"))
                                        {
                                            uriInLink = System.Web.VirtualPathUtility.ToAbsolute(uriInLink);
                                            if (isScript)
                                            {
                                                return(SRIScriptLink(helper, uriInLink));
                                            }
                                            else
                                            {
                                                return(SRICssLink(helper, uriInLink));
                                            }
                                        }
                                        if (!_dictionary.ContainsKey(linkWithTags))
                                        {
                                            _dictionary.Add(linkWithTags,
                                                            "local");                                     //vi undviker att spara till fil eftersom lokal sökväg inte bör existera annat än i utveckling
                                        }
                                        return(new HtmlString(linkWithTags));
                                    }
                                    if (uriInLink.StartsWith("~"))
                                    {
                                        uriInLink = uriInLink.Substring(1, uriInLink.Length - 1);
                                    }
                                    if (!basePath.EndsWith("/"))
                                    {
                                        basePath = basePath + "/";
                                    }
                                    if (uriInLink.StartsWith("/"))
                                    {
                                        uriInLink = uriInLink.Substring(1, uriInLink.Length - 1);
                                    }
                                    uriToGet = basePath + uriInLink;
                                }
                                else
                                {
                                    uriToGet = uriInLink;
                                }
                                bool   success = false;
                                byte[] bytes   = null;
                                using (var client = new WebClient())
                                {
                                    try
                                    {
                                        bytes   = client.DownloadData(uriToGet);
                                        success = true;
                                    }
                                    catch (Exception)
                                    {
                                        success = false;
                                    }
                                }
                                if (success)
                                {
                                    byte[] result = null;
                                    using (SHA384 shaM = new SHA384Managed())
                                    {
                                        result = shaM.ComputeHash(bytes);
                                        var    hashBase64 = Convert.ToBase64String(result);
                                        string pre, post;
                                        if (linkWithTags.Contains("/>"))
                                        {
                                            var index = linkWithTags.LastIndexOf(">");
                                            index = index - 1;
                                            pre   = linkWithTags.Substring(0, index);
                                            post  = "/>";
                                        }
                                        else
                                        {
                                            var index = linkWithTags.IndexOf(">");
                                            pre  = linkWithTags.Substring(0, index);
                                            post = linkWithTags.Substring(index);
                                        }
                                        StringBuilder sb = new StringBuilder();
                                        sb.Append(pre);
                                        sb.Append(" ");
                                        sb.Append("integrity=\"");
                                        sb.Append("sha384-");
                                        sb.Append(hashBase64);
                                        sb.Append("\"");
                                        if (!linkWithTags.Contains("crossorigin=\""))
                                        {
                                            sb.Append(" crossorigin=\"anonymous\"");
                                        }
                                        sb.Append(" ");
                                        sb.Append(post);

                                        var theNewLink = sb.ToString();

                                        if (!_dictionary.ContainsKey(linkWithTags))
                                        {
                                            try
                                            {
                                                using (var fs = File.Open(filePath, FileMode.Append))
                                                {
                                                    using (var sw = new StreamWriter(fs))
                                                    {
                                                        sw.WriteLine(linkWithTags + "\t" + theNewLink);
                                                    }
                                                }
                                                _dictionary.Add(linkWithTags, theNewLink);
                                            }
                                            catch (Exception)
                                            {
                                                return(new HtmlString(
                                                           "<script src=\"CAN NOT WRITE TO SubResourceIntegrityHelper_FilePath\" />"));
                                            }
                                        }
                                        return(new HtmlString(theNewLink));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(new HtmlString(linkWithTags));
        }
Ejemplo n.º 6
0
    public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes)
    {
        // If salt is not specified, generate it.
        if (saltBytes == null)
        {
            // Define min and max salt sizes.
            int minSaltSize = 4;
            int maxSaltSize = 8;

            // Generate a random number for the size of the salt.
            Random random   = new Random();
            int    saltSize = random.Next(minSaltSize, maxSaltSize);

            // Allocate a byte array, which will hold the salt.
            saltBytes = new byte[saltSize];

            // Initialize a random number generator.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            // Fill the salt with cryptographically strong byte values.
            rng.GetNonZeroBytes(saltBytes);
        }

        // Convert plain text into a byte array.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        // Allocate array, which will hold plain text and salt.
        byte[] plainTextWithSaltBytes =
            new byte[plainTextBytes.Length + saltBytes.Length];

        // Copy plain text bytes into resulting array.
        for (int i = 0; i < plainTextBytes.Length; i++)
        {
            plainTextWithSaltBytes[i] = plainTextBytes[i];
        }

        // Append salt bytes to the resulting array.
        for (int i = 0; i < saltBytes.Length; i++)
        {
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
        }

        HashAlgorithm hash;

        // Make sure hashing algorithm name is specified.
        if (hashAlgorithm == null)
        {
            hashAlgorithm = "";
        }

        // Initialize appropriate hashing algorithm class.
        switch (hashAlgorithm.ToUpper())
        {
        case "SHA384":
            hash = new SHA384Managed();
            break;

        case "SHA512":
            hash = new SHA512Managed();
            break;

        default:
            hash = new MD5CryptoServiceProvider();
            break;
        }

        // Compute hash value of our plain text with appended salt.
        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

        // Create array which will hold hash and original salt bytes.
        byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                            saltBytes.Length];

        // Copy hash bytes into resulting array.
        for (int i = 0; i < hashBytes.Length; i++)
        {
            hashWithSaltBytes[i] = hashBytes[i];
        }

        // Append salt bytes to the result.
        for (int i = 0; i < saltBytes.Length; i++)
        {
            hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
        }

        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(hashWithSaltBytes);

        // Return the result.
        return(hashValue);
    }
        /// <summary>
        /// Generates hash string for given value and algorith with encoding type
        /// Supported Algorithm: SHA1, SHA256, SHA384, MD5 and SHA512
        /// Supported Encoding Types: HEX and BASE_64
        /// </summary>
        /// <param name="Content">Content for hash</param>
        /// <param name="algorithm">Supported Algorithm: SHA1, SHA256, SHA384, MD5 and SHA512</param>
        /// <param name="et">Supported Encoding Types: HEX and BASE_64</param>
        /// <returns>Generated hash</returns>
        public static string GenerateHashString(string Content, Algorithm algorithm, EncodingType et)
        {
            string _content;

            if (Content == null || Content.Equals(string.Empty))
            {
                throw new CryptographicException(ERR_NO_CONTENT);
            }

            HashAlgorithm hashAlgorithm = null;

            switch (algorithm)
            {
            case Algorithm.SHA1:
                hashAlgorithm = new SHA1CryptoServiceProvider();
                break;

            case Algorithm.SHA256:
                hashAlgorithm = new SHA256Managed();
                break;

            case Algorithm.SHA384:
                hashAlgorithm = new SHA384Managed();
                break;

            case Algorithm.SHA512:
                hashAlgorithm = new SHA512Managed();
                break;

            case Algorithm.MD5:
                hashAlgorithm = new MD5CryptoServiceProvider();
                break;

            default:
                throw new CryptographicException(ERR_INVALID_PROVIDER);
            }

            try
            {
                byte[] hash = ComputeHash(hashAlgorithm, Content);
                if (et == EncodingType.HEX)
                {
                    _content = BytesToHex(hash);
                }
                else
                {
                    _content = System.Convert.ToBase64String(hash);
                }
                hashAlgorithm.Clear();
                return(_content);
            }
            catch (CryptographicException cge)
            {
                throw cge;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                hashAlgorithm.Clear();
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// public override void GenerateKey(string secretKey, AlgorithmKeyType type)
        /// </summary>
        /// <param name="secretKey"></param>
        /// <param name="type"></param>
        public override void GenerateKey(string secretKey, AlgorithmKeyType type)
        {
            Key = new byte[24];
            IV  = new byte[8];
            byte[] bKey = Encoding.UTF8.GetBytes(secretKey);
            switch (type)
            {
            case AlgorithmKeyType.MD5:    //16 byte
                using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
                {
                    md5.ComputeHash(bKey);
                    byte[] rmd5 = md5.Hash;
                    for (int i = 0; i < 16; i++)
                    {
                        Key[i] = rmd5[i];
                    }
                    for (int j = 15; j >= 8; j--)
                    {
                        IV[15 - j] = rmd5[j];
                    }
                }
                break;

            case AlgorithmKeyType.SHA1:    //20 byte
                using (SHA1Managed sha1 = new SHA1Managed())
                {
                    sha1.ComputeHash(bKey);
                    byte[] rsha1 = sha1.Hash;
                    for (int i = 0; i < 20; i++)
                    {
                        Key[i] = rsha1[i];
                    }
                    for (int j = 16; j > 8; j--)
                    {
                        IV[16 - j] = rsha1[j];
                    }
                }
                break;

            case AlgorithmKeyType.SHA256:    //32 byte
                using (SHA256Managed sha256 = new SHA256Managed())
                {
                    sha256.ComputeHash(bKey);
                    byte[] rsha256 = sha256.Hash;
                    for (int i = 0; i < 24; i++)
                    {
                        Key[i] = rsha256[i];
                    }
                    for (int j = 31; j >= 24; j--)
                    {
                        IV[31 - j] = rsha256[j];
                    }
                }
                break;

            case AlgorithmKeyType.SHA384:    //48 byte
                using (SHA384Managed sha384 = new SHA384Managed())
                {
                    sha384.ComputeHash(bKey);
                    byte[] rsha384 = sha384.Hash;
                    for (int i = 0; i < 24; i++)
                    {
                        Key[i] = rsha384[i];
                    }
                    for (int j = 47; j > 39; j--)
                    {
                        IV[47 - j] = rsha384[j];
                    }
                }
                break;

            case AlgorithmKeyType.SHA512:    //64 byte
                using (SHA512Managed sha512 = new SHA512Managed())
                {
                    sha512.ComputeHash(bKey);
                    byte[] rsha512 = sha512.Hash;
                    for (int i = 0; i < 24; i++)
                    {
                        Key[i] = rsha512[i];
                    }
                    for (int j = 63; j > 55; j--)
                    {
                        IV[63 - j] = rsha512[j];
                    }
                }
                break;

            default:
                break;
            }
        }
 protected override void SetUp()
 {
     hash = new SHA384Managed();
 }
Ejemplo n.º 10
0
        public static string HashFile(string filepath, HashTypes hashtype = HashTypes.Md5)
        {
            if (File.Exists(filepath))
            {
                try
                {
                    using (FileStream fs = new FileStream(filepath, FileMode.Open))
                        using (BufferedStream bs = new BufferedStream(fs))
                        {
                            switch (hashtype)
                            {
                            case HashTypes.Md5:
                                using (var md = MD5.Create())
                                {
                                    var comp = md.ComputeHash(bs);
                                    var hash = new StringBuilder();
                                    foreach (byte b in comp)
                                    {
                                        hash.Append(b.ToString("X2"));
                                    }

                                    return(hash.ToString());
                                }

                            case HashTypes.Sha1:
                                using (SHA1Managed sha = new SHA1Managed())
                                {
                                    var comp = sha.ComputeHash(bs);
                                    var hash = new StringBuilder(comp.Length * 2);
                                    foreach (byte b in comp)
                                    {
                                        hash.Append(b.ToString("X2"));
                                    }

                                    return(hash.ToString());
                                }

                            case HashTypes.Sha256:
                                using (SHA256Managed sha = new SHA256Managed())
                                {
                                    var comp = sha.ComputeHash(bs);
                                    var hash = new StringBuilder(comp.Length * 2);
                                    foreach (byte b in comp)
                                    {
                                        hash.Append(b.ToString("X2"));
                                    }

                                    return(hash.ToString());
                                }

                            case HashTypes.Sha384:
                                using (SHA384Managed sha = new SHA384Managed())
                                {
                                    var comp = sha.ComputeHash(bs);
                                    var hash = new StringBuilder(comp.Length * 2);
                                    foreach (byte b in comp)
                                    {
                                        hash.Append(b.ToString("X2"));
                                    }

                                    return(hash.ToString());
                                }

                            case HashTypes.Sha512:
                                using (SHA512Managed sha = new SHA512Managed())
                                {
                                    var comp = sha.ComputeHash(bs);
                                    var hash = new StringBuilder(comp.Length * 2);
                                    foreach (byte b in comp)
                                    {
                                        hash.Append(b.ToString("X2"));
                                    }

                                    return(hash.ToString());
                                }

                            default:
                                return("hashError");
                            }
                        }
                }
                catch (Exception)
                {
                    return("hashError");
                }
            }
            return("fileNotFound");
        }
Ejemplo n.º 11
0
        private static string ComputeHash(string plainText,
                                          string hashAlgorithm,
                                          byte[] saltBytes)
        {
            if (saltBytes == null)
            {
                int minSaltSize = 4;
                int maxSaltSize = 8;


                Random random   = new Random();
                int    saltSize = random.Next(minSaltSize, maxSaltSize);


                saltBytes = new byte[saltSize];


                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();


                rng.GetNonZeroBytes(saltBytes);
            }


            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);


            byte[] plainTextWithSaltBytes =
                new byte[plainTextBytes.Length + saltBytes.Length];

            for (int i = 0; i < plainTextBytes.Length; i++)
            {
                plainTextWithSaltBytes[i] = plainTextBytes[i];
            }

            for (int i = 0; i < saltBytes.Length; i++)
            {
                plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
            }

            HashAlgorithm hash;

            if (hashAlgorithm == null)
            {
                hashAlgorithm = "";
            }

            switch (hashAlgorithm.ToUpper())
            {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
            }

            byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

            byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                                saltBytes.Length];

            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashWithSaltBytes[i] = hashBytes[i];
            }

            for (int i = 0; i < saltBytes.Length; i++)
            {
                hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
            }

            string hashValue = Convert.ToBase64String(hashWithSaltBytes);

            return(hashValue);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Hashes a byte array through SHA-384.
 /// </summary>
 /// <param name="input">The byte array for which to calculate the hash</param>
 /// <returns>The SHA-384 digest.</returns>
 public static byte[] SHA384(byte[] input)
 {
     using SHA384Managed sha384 = new SHA384Managed();
     return(sha384.ComputeHash(input));
 }
Ejemplo n.º 13
0
        public string ComputeHash(string plaintext, string hashalgo, byte[] saltbyte)
        {
            if (saltbyte == null)
            {
                Random rand     = new Random();
                int    saltsize = rand.Next(2, 10);
                saltbyte = new byte[saltsize];
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                rng.GetNonZeroBytes(saltbyte);
            }
            byte[] plaintextbytes     = Encoding.UTF8.GetBytes(plaintext);
            byte[] plaintextsaltbytes = new byte[plaintextbytes.Length + saltbyte.Length];
            for (int i = 0; i < plaintextbytes.Length; i++)
            {
                plaintextsaltbytes[i] = plaintextbytes[i];
            }
            for (int i = 0; i < saltbyte.Length; i++)
            {
                plaintextsaltbytes[i + plaintextbytes.Length] = saltbyte[i];
            }


            HashAlgorithm hash;

            if (hashalgo == null)
            {
                hashalgo = "";
            }

            switch (hashalgo.ToUpper())
            {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
            }

            byte[] hashbytes = hash.ComputeHash(plaintextsaltbytes);

            byte[] hashWithSaltBytes = new byte[hashbytes.Length +
                                                saltbyte.Length];

            for (int i = 0; i < hashbytes.Length; i++)
            {
                hashWithSaltBytes[i] = hashbytes[i];
            }

            for (int i = 0; i < saltbyte.Length; i++)
            {
                hashWithSaltBytes[hashbytes.Length + i] = saltbyte[i];
            }

            string hashValue = Convert.ToBase64String(hashWithSaltBytes);

            return(hashValue);
        }
        /// <summary>
        /// Calculates the hash of a data using SHA hash algorithm.
        /// </summary>
        /// <param name="data">The data to hash.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="length">The length.</param>
        /// <param name="hashSize">Size of the hash.</param>
        /// <returns>
        /// Calculated hash
        /// </returns>
        private static byte[] CalculateHashSha(this byte[] data, int offset, int length, int hashSize)
        {
            data.CannotBeNullOrEmpty();
            offset.MustBeGreaterThanOrEqualTo(0);
            length.MustBeGreaterThanOrEqualTo(0);
            hashSize.MustBeOneOf(128, 256, 384, 512);

            byte[] hashRaw = null;

            if (data != null)
            {
                if (hashSize == 128)
                {
#pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1.
                    using (HashAlgorithm sha = new SHA1CryptoServiceProvider())
#pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1.
                    {
                        hashRaw = CalculateHash(data, offset, length, sha);
                    }
                }
                else if (hashSize == 256)
                {
                    try
                    {
                        using (HashAlgorithm sha = new SHA256CryptoServiceProvider())
                        {
                            hashRaw = CalculateHash(data, offset, length, sha);
                        }
                    }
                    catch (PlatformNotSupportedException)
                    {
                        // Fall back to the managed version if the CSP
                        // is not supported on this platform.
                        using (HashAlgorithm sha = new SHA256Managed())
                        {
                            hashRaw = CalculateHash(data, offset, length, sha);
                        }
                    }
                }
                else if (hashSize == 384)
                {
                    try
                    {
                        using (HashAlgorithm sha = new SHA384CryptoServiceProvider())
                        {
                            hashRaw = CalculateHash(data, offset, length, sha);
                        }
                    }
                    catch (PlatformNotSupportedException)
                    {
                        // Fall back to the managed version if the CSP
                        // is not supported on this platform.
                        using (HashAlgorithm sha = new SHA384Managed())
                        {
                            hashRaw = CalculateHash(data, offset, length, sha);
                        }
                    }
                }
                else if (hashSize == 512)
                {
                    try
                    {
                        using (HashAlgorithm sha = new SHA512CryptoServiceProvider())
                        {
                            hashRaw = CalculateHash(data, offset, length, sha);
                        }
                    }
                    catch (PlatformNotSupportedException)
                    {
                        // Fall back to the managed version if the CSP
                        // is not supported on this platform.
                        using (HashAlgorithm sha = new SHA512Managed())
                        {
                            hashRaw = CalculateHash(data, offset, length, sha);
                        }
                    }
                }
            }

            return hashRaw;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Validates the signature using the public part of the asymmetric key given as parameter.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns><code>true</code> if the signature is present and can be verified using the given key.
        /// <code>false</code> if the signature is present, but can't be verified using the given key.</returns>
        /// <exception cref="InvalidOperationException">If the query is not signed, and therefore cannot have its signature verified. Use
        /// the <code>IsSigned</code> property to check for this situation before calling this method.</exception>
        public bool CheckSignature(AsymmetricAlgorithm key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (!(key is DSA || key is RSACryptoServiceProvider))
            {
                throw new ArgumentException("The key must be an instance of either DSA or RSACryptoServiceProvider.");
            }

            if (!IsSigned)
            {
                throw new InvalidOperationException("Query is not signed, so there is no signature to verify.");
            }

            byte[] hash      = null;
            string algorithm = null;
            var    toSign    = Encoding.UTF8.GetBytes(_signedquery);

            switch (SignatureAlgorithm)
            {
            case SignedXml.XmlDsigRSASHA1Url:
            case SignedXml.XmlDsigDSAUrl:
                hash      = new SHA1Managed().ComputeHash(toSign);
                algorithm = "SHA1";
                break;

            case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256":
                hash      = new SHA256Managed().ComputeHash(toSign);
                algorithm = "SHA256";
                break;

            case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384":
                hash      = new SHA384Managed().ComputeHash(toSign);
                algorithm = "SHA384";
                break;

            case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512":
                hash      = new SHA512Managed().ComputeHash(toSign);
                algorithm = "SHA512";
                break;

            default:
                hash      = new SHA256Managed().ComputeHash(toSign);
                algorithm = "SHA256";
                break;
            }

            if (key is RSACryptoServiceProvider)
            {
                RSACryptoServiceProvider rsaClear = new RSACryptoServiceProvider();
                rsaClear.ImportParameters(((RSACryptoServiceProvider)key).ExportParameters(false));
                return(rsaClear.VerifyHash(hash, algorithm, DecodeSignature()));
            }
            else
            {
                var dsa = (DSA)key;
                return(dsa.VerifySignature(hash, DecodeSignature()));
            }
        }
Ejemplo n.º 16
0
 // Konstruktor initierar de tre objekt i klassen
 public HashGenerator()
 {
     sha256 = new SHA256Managed();
     sha384 = new SHA384Managed();
     sha512 = new SHA512Managed();
 }
Ejemplo n.º 17
0
 public SHA384Hash()
 {
     _objHashObject = new SHA384Managed();
 }
Ejemplo n.º 18
0
        public static string ComputeHash(string plainText, Supported_HA hash, byte[] salt)
        {
            int minSaltLength = 4, maxSaltLength = 16;

            byte[] saltBytes = null;
            if (salt != null)
            {
                saltBytes = salt;
            }
            else
            {
                saltBytes = SALT_BYTES;
            }

            byte[] plainData         = ASCIIEncoding.UTF8.GetBytes(plainText);
            byte[] plainDataWithSalt = new byte[plainData.Length + saltBytes.Length];

            for (int x = 0; x < plainData.Length; x++)
            {
                plainDataWithSalt[x] = plainData[x];
            }
            for (int n = 0; n < saltBytes.Length; n++)
            {
                plainDataWithSalt[plainData.Length + n] = saltBytes[n];
            }

            byte[] hashValue = null;

            switch (hash)
            {
            case Supported_HA.SHA256:
                SHA256Managed sha = new SHA256Managed();
                hashValue = sha.ComputeHash(plainDataWithSalt);
                sha.Dispose();
                break;

            case Supported_HA.SHA384:
                SHA384Managed sha1 = new SHA384Managed();
                hashValue = sha1.ComputeHash(plainDataWithSalt);
                sha1.Dispose();
                break;

            case Supported_HA.SHA512:
                SHA512Managed sha2 = new SHA512Managed();
                hashValue = sha2.ComputeHash(plainDataWithSalt);
                sha2.Dispose();
                break;
            }

            byte[] result = new byte[hashValue.Length + saltBytes.Length];
            for (int x = 0; x < hashValue.Length; x++)
            {
                result[x] = hashValue[x];
            }
            for (int n = 0; n < saltBytes.Length; n++)
            {
                result[hashValue.Length + n] = saltBytes[n];
            }

            return(Convert.ToBase64String(result));
        }
Ejemplo n.º 19
0
        public static string Hash(HashType hashAlgorithm, string text, byte[] salt)
        {
            int index;

            // Convert plain text into a byte array.
            byte[] textBytes = Encoding.UTF8.GetBytes(text);

            // Allocate array, which will hold plain text and salt.
            byte[] textWithSalt = new byte[textBytes.Length + salt.Length];

            // Copy plain text bytes into resulting array.
            for (index = 0; index < textBytes.Length; index++)
            {
                textWithSalt[index] = textBytes[index];
            }

            // Append salt bytes to the resulting array.
            for (index = 0; index < salt.Length; index++)
            {
                textWithSalt[textBytes.Length + index] = salt[index];
            }

            // Because we support multiple hashing algorithms, we must define
            // hash object as a common (abstract) base class. We will specify the
            // actual hashing algorithm class later during object creation.
            HashAlgorithm hash;

            // Initialize appropriate hashing algorithm class.
            switch (hashAlgorithm)
            {
            case HashType.SHA1:
                hash = new SHA1Managed();
                break;

            case HashType.SHA256:
                hash = new SHA256Managed();
                break;

            case HashType.SHA384:
                hash = new SHA384Managed();
                break;

            case HashType.SHA512:
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
            }

            // Compute hash value of our plain text with appended salt.
            byte[] hashBytes = hash.ComputeHash(textWithSalt);

            // Create array which will hold hash and original salt bytes.
            byte[] hashWithsalt = new byte[hashBytes.Length + salt.Length];

            // Copy hash bytes into resulting array.
            for (index = 0; index < hashBytes.Length; index++)
            {
                hashWithsalt[index] = hashBytes[index];
            }

            // Append salt bytes to the result.
            for (index = 0; index < salt.Length; index++)
            {
                hashWithsalt[hashBytes.Length + index] = salt[index];
            }

            // Convert result into a base64-encoded string.
            return(Encoding.Unicode.GetString(hashBytes) + Encoding.Unicode.GetString(salt));
        }
Ejemplo n.º 20
0
        public IList <byte> ComputeHashToBytes(string value)
        {
            HashAlgorithm sHA1Managed;
            IList <byte>  nums;
            var           nums1 = new List <byte>(Encoding.Unicode.GetBytes(value));

            switch (HashSize)
            {
            case EnumHashSize.SHA1:
            case EnumHashSize.FOLD32:
            case EnumHashSize.FOLD16:
            {
                sHA1Managed = new SHA1Managed();
                break;
            }

            case EnumHashSize.SHA256:
            {
                sHA1Managed = new SHA256Managed();
                break;
            }

            case EnumHashSize.SHA384:
            {
                sHA1Managed = new SHA384Managed();
                break;
            }

            case EnumHashSize.SHA512:
            {
                sHA1Managed = new SHA512Managed();
                break;
            }

            default:
            {
                throw new NotImplementedException();
            }
            }
            using (sHA1Managed)
            {
                var nums2 = new List <byte>(sHA1Managed.ComputeHash(nums1.ToArray()));
                int item;
                switch (HashSize)
                {
                case EnumHashSize.FOLD32:
                {
                    for (var i = 0; i < 4; i++)
                    {
                        item = 0;
                        for (var j = 0; j < 5; j++)
                        {
                            item = item + nums2[j * 4 + i];
                        }
                        nums2[i] = (byte)(item % 256);
                    }
                    nums2.RemoveRange(4, nums2.Count - 4);
                    break;
                }

                case EnumHashSize.FOLD16:
                {
                    for (var k = 0; k < 2; k++)
                    {
                        item = 0;
                        for (var l = 0; l < 10; l++)
                        {
                            item = item + nums2[l * 2 + k];
                        }
                        nums2[k] = (byte)(item % 256);
                    }
                    nums2.RemoveRange(2, nums2.Count - 2);
                    break;
                }
                }
                nums = nums2;
            }
            return(nums);
        }
        private byte[] ComputeHash(string password, byte[] passwordSalt)
        {
            // Convert plain text into a byte array.
            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

            // Allocate array, which will hold plain text and salt.
            byte[] passwordWithSaltBytes =
                new byte[passwordBytes.Length + passwordSalt.Length];

            // Copy plain text bytes into resulting array.
            for (int i = 0; i < passwordBytes.Length; i++)
            {
                passwordWithSaltBytes[i] = passwordBytes[i];
            }

            // Append salt bytes to the resulting array.
            for (int i = 0; i < passwordSalt.Length; i++)
            {
                passwordWithSaltBytes[passwordBytes.Length + i] = passwordSalt[i];
            }

            // Because we support multiple hashing algorithms, we must define
            // hash object as a common (abstract) base class. We will specify the
            // actual hashing algorithm class later during object creation.
            HashAlgorithm hash;

            // Initialize appropriate hashing algorithm class.
            switch (hashAlgorithm.ToUpper())
            {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
            }

            // Compute hash value of our plain text with appended salt.
            byte[] hashBytes = hash.ComputeHash(passwordWithSaltBytes);

            // Create array which will hold hash and original salt bytes.
            byte[] passwordHash = new byte[hashBytes.Length +
                                           passwordSalt.Length];

            // Copy hash bytes into resulting array.
            for (int i = 0; i < hashBytes.Length; i++)
            {
                passwordHash[i] = hashBytes[i];
            }

            // Append salt bytes to the result.
            for (int i = 0; i < passwordSalt.Length; i++)
            {
                passwordHash[hashBytes.Length + i] = passwordSalt[i];
            }

            // Convert result into a base64-encoded string.

            return(passwordHash);
        }
Ejemplo n.º 22
0
        public static string ComputeHash(string plainText, Supported_HA hash, byte[] salt)
        {
            int minSaltLength = 4;
            int maxSaltLength = 16;

            byte[] SaltBytes = null;

            if (salt != null)
            {
                SaltBytes = salt;
            }
            else
            {
                Random r          = new Random();
                int    SaltLength = r.Next(minSaltLength, maxSaltLength);
                SaltBytes = new byte[SaltLength];
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                rng.GetNonZeroBytes(SaltBytes);
                rng.Dispose();
            }

            byte[] plainData        = ASCIIEncoding.UTF8.GetBytes(plainText);
            byte[] plainDataAndSalt = new byte[plainData.Length + SaltBytes.Length];

            for (int x = 0; x < plainData.Length; x++)
            {
                plainDataAndSalt[x] = plainData[x];
            }
            for (int n = 0; n < SaltBytes.Length; n++)
            {
                plainDataAndSalt[plainData.Length + n] = SaltBytes[n];
            }

            byte[] hashValue = null;

            switch (hash)
            {
            case Supported_HA.SHA256:
                SHA256Managed sha256 = new SHA256Managed();
                hashValue = sha256.ComputeHash(plainDataAndSalt);
                sha256.Dispose();
                break;

            case Supported_HA.SHA384:
                SHA384Managed sha384 = new SHA384Managed();
                hashValue = sha384.ComputeHash(plainDataAndSalt);
                sha384.Dispose();
                break;

            case Supported_HA.SHA512:
                SHA512Managed sha512 = new SHA512Managed();
                hashValue = sha512.ComputeHash(plainDataAndSalt);
                sha512.Dispose();
                break;
            }

            byte[] result = new byte[hashValue.Length + SaltBytes.Length];

            for (int i = 0; i < hashValue.Length; i++)
            {
                result[i] = hashValue[i];
            }
            for (int j = 0; j < SaltBytes.Length; j++)
            {
                result[hashValue.Length + j] = SaltBytes[j];
            }

            return(Convert.ToBase64String(result));
        }
Ejemplo n.º 23
0
 public static string HashSHA384(this byte[] Data)
 {
     using (var SHA384 = new SHA384Managed())
         return(SHA384.ComputeHash(Data).GetText());
 }
Ejemplo n.º 24
0
        public static string HashString(string content, HashTypes hashtype = HashTypes.Md5)
        {
            try
            {
                switch (hashtype)
                {
                case HashTypes.Md5:
                    using (var md = MD5.Create())
                    {
                        var           comp = md.ComputeHash(Encoding.UTF8.GetBytes(content));
                        StringBuilder hash = new StringBuilder();
                        foreach (byte b in comp)
                        {
                            hash.Append(b.ToString("X2"));
                        }

                        return(hash.ToString());
                    }

                case HashTypes.Sha1:
                    using (SHA1Managed sha = new SHA1Managed())
                    {
                        var comp = sha.ComputeHash(Encoding.UTF8.GetBytes(content));
                        var hash = new StringBuilder(comp.Length * 2);
                        foreach (byte b in comp)
                        {
                            hash.Append(b.ToString("X2"));
                        }

                        return(hash.ToString());
                    }

                case HashTypes.Sha256:
                    using (SHA256Managed sha = new SHA256Managed())
                    {
                        var comp = sha.ComputeHash(Encoding.UTF8.GetBytes(content));
                        var hash = new StringBuilder(comp.Length * 2);
                        foreach (byte b in comp)
                        {
                            hash.Append(b.ToString("X2"));
                        }

                        return(hash.ToString());
                    }

                case HashTypes.Sha384:
                {
                    using (SHA384Managed sha = new SHA384Managed())
                    {
                        var comp = sha.ComputeHash(Encoding.UTF8.GetBytes(content));
                        var hash = new StringBuilder(comp.Length * 2);
                        foreach (byte b in comp)
                        {
                            hash.Append(b.ToString("X2"));
                        }

                        return(hash.ToString());
                    }
                }

                case HashTypes.Sha512:
                    using (SHA512Managed sha = new SHA512Managed())
                    {
                        var comp = sha.ComputeHash(Encoding.UTF8.GetBytes(content));
                        var hash = new StringBuilder(comp.Length * 2);
                        foreach (byte b in comp)
                        {
                            hash.Append(b.ToString("X2"));
                        }

                        return(hash.ToString());
                    }

                default:
                    return("hashError");
                }
            }
            catch (Exception)
            {
                return("hashError");
            }
        }
Ejemplo n.º 25
0
        public static string ComputeHash(string plainText,
                                         string hashAlgorithm,
                                         string salt)
        {
            byte[] saltBytes = Convert.FromBase64String(salt);

            // Convert plain text into a byte array.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // Allocate array, which will hold plain text and salt.
            byte[] plainTextWithSaltBytes =
                new byte[plainTextBytes.Length + saltBytes.Length];

            // Copy plain text bytes into resulting array.
            for (int i = 0; i < plainTextBytes.Length; i++)
            {
                plainTextWithSaltBytes[i] = plainTextBytes[i];
            }

            // Append salt bytes to the resulting array.
            for (int i = 0; i < saltBytes.Length; i++)
            {
                plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
            }

            // Because we support multiple hashing algorithms, we must define
            // hash object as a common (abstract) base class. We will specify the
            // actual hashing algorithm class later during object creation.
            HashAlgorithm hash;

            // Make sure hashing algorithm name is specified.
            if (hashAlgorithm == null)
            {
                hashAlgorithm = "";
            }

            // Initialize appropriate hashing algorithm class.
            switch (hashAlgorithm.ToUpper())
            {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
            }

            // Compute hash value of our plain text with appended salt.
            byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

            // Create array which will hold hash and original salt bytes.
            byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                                saltBytes.Length];

            // Copy hash bytes into resulting array.
            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashWithSaltBytes[i] = hashBytes[i];
            }

            // Append salt bytes to the result.
            for (int i = 0; i < saltBytes.Length; i++)
            {
                hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
            }

            // Convert result into a base64-encoded string.
            string hashValue = Convert.ToBase64String(hashWithSaltBytes);

            // Return the result.
            return(hashValue);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Generates a hash for the given plain text value and returns a
        /// base64-encoded result. Before the hash is computed, a random salt
        /// is generated and appended to the plain text. This salt is stored at
        /// the end of the hash value, so it can be used later for hash
        /// verification.
        /// </summary>
        /// <param name="plainText">
        /// Plaintext value to be hashed. The function does not check whether
        /// this parameter is null.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
        /// "SHA256", "SHA384", and "SHA512" (if any other value is specified
        /// MD5 hashing algorithm will be used). This value is case-insensitive.
        /// </param>
        /// <param name="saltBytes">
        /// Salt bytes. This parameter can be null, in which case a random salt
        /// value will be generated.
        /// </param>
        /// <returns>
        /// Hash value formatted as a base64-encoded string.
        /// </returns>
        public static string ComputeHash(string plainText,
                                         HashingAlgorithm hashAlgorithm,
                                         byte[] saltBytes)
        {
            // If salt is not specified, generate it on the fly.
            if (saltBytes == null)
            {
                // Define min and max salt sizes.
                int minSaltSize = 4;
                int maxSaltSize = 8;

                // Generate a random number for the size of the salt.
                Random random   = new Random();
                int    saltSize = random.Next(minSaltSize, maxSaltSize);

                // Allocate a byte array, which will hold the salt.
                saltBytes = new byte[saltSize];

                // Initialize a random number generator.
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

                // Fill the salt with cryptographically strong byte values.
                rng.GetNonZeroBytes(saltBytes);
            }

            // Convert plain text into a byte array.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // Allocate array, which will hold plain text and salt.
            byte[] plainTextWithSaltBytes =
                new byte[plainTextBytes.Length + saltBytes.Length];

            // Copy plain text bytes into resulting array.
            for (int i = 0; i < plainTextBytes.Length; i++)
            {
                plainTextWithSaltBytes[i] = plainTextBytes[i];
            }

            // Append salt bytes to the resulting array.
            for (int i = 0; i < saltBytes.Length; i++)
            {
                plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
            }

            // Because we support multiple hashing algorithms, we must define
            // hash object as a common (abstract) base class. We will specify the
            // actual hashing algorithm class later during object creation.
            HashAlgorithm hash;

            // Initialize appropriate hashing algorithm class.
            switch (hashAlgorithm)
            {
            case HashingAlgorithm.SHA1:
                hash = new SHA1Managed();
                break;

            case HashingAlgorithm.SHA256:
                hash = new SHA256Managed();
                break;

            case HashingAlgorithm.SHA384:
                hash = new SHA384Managed();
                break;

            case HashingAlgorithm.SHA512:
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
            }

            // Compute hash value of our plain text with appended salt.
            byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

            // Create array which will hold hash and original salt bytes.
            byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                                saltBytes.Length];

            // Copy hash bytes into resulting array.
            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashWithSaltBytes[i] = hashBytes[i];
            }

            // Append salt bytes to the result.
            for (int i = 0; i < saltBytes.Length; i++)
            {
                hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
            }

            // Convert result into a base64-encoded string.
            string hashValue = Convert.ToBase64String(hashWithSaltBytes);

            // Return the result.
            return(hashValue);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Generates a hash for the given plain text value and returns a
        /// base64-encoded result. Before the hash is computed, a random salt
        /// is generated and appended to the plain text. This salt is stored at
        /// the end of the hash value, so it can be used later for hash
        /// verification.
        /// </summary>
        /// <param name="plainText">
        /// Plaintext value to be hashed.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
        /// "SHA256", "SHA384", and "SHA512" (if any other value is specified
        /// MD5 hashing algorithm will be used). This value is case-insensitive.
        /// </param>
        /// <param name="saltBytes">
        /// Optinoal salt bytes to apply to the hash. If not passed the
        /// raw encoding is used.
        /// </param>
        /// <returns>
        /// Hash value formatted as a base64-encoded string.
        /// </returns>
        public static string ComputeHash(string plainText,
                                         string hashAlgorithm,
                                         byte[] saltBytes,
                                         bool useBinHex = false)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                return(plainText);
            }

            // Convert plain text into a byte array.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            byte[] plainTextWithSaltBytes;

            if (saltBytes != null)
            {
                // Allocate array, which will hold plain text and salt.
                plainTextWithSaltBytes =
                    new byte[plainTextBytes.Length + saltBytes.Length];

                // Copy plain text bytes into resulting array.
                for (int i = 0; i < plainTextBytes.Length; i++)
                {
                    plainTextWithSaltBytes[i] = plainTextBytes[i];
                }

                // Append salt bytes to the resulting array.
                for (int i = 0; i < saltBytes.Length; i++)
                {
                    plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
                }
            }
            else
            {
                plainTextWithSaltBytes = plainTextBytes;
            }

            HashAlgorithm hash;

            // Make sure hashing algorithm name is specified.
            if (hashAlgorithm == null)
            {
                hashAlgorithm = "";
            }

            // Initialize appropriate hashing algorithm class.
            switch (hashAlgorithm.ToUpper())
            {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                // default to MD5
                hash = new MD5CryptoServiceProvider();
                break;
            }


            byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

            if (useBinHex)
            {
                return(BinaryToBinHex(hashBytes));
            }

            return(Convert.ToBase64String(hashBytes));
        }
Ejemplo n.º 28
0
 public override void SetUp()
 {
     hash = new SHA384Managed();
 }
Ejemplo n.º 29
0
    public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes)
    {
        if (saltBytes == null)
        {
            int minSaltSize = 4;
            int maxSaltSize = 8;

            Random random = new Random();
            int saltSize = random.Next(minSaltSize, maxSaltSize);

            saltBytes = new byte[saltSize];

            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            rng.GetNonZeroBytes(saltBytes);
        }

        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];

        for (int i = 0; i < plainTextBytes.Length; i++)
            plainTextWithSaltBytes[i] = plainTextBytes[i];

        for (int i = 0; i < saltBytes.Length; i++)
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];

        HashAlgorithm hash;

        if (hashAlgorithm == null)
            hashAlgorithm = "";

        switch (hashAlgorithm.ToUpper())
        {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
        }

        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

        byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length];

        for (int i = 0; i < hashBytes.Length; i++)
            hashWithSaltBytes[i] = hashBytes[i];

        for (int i = 0; i < saltBytes.Length; i++)
            hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];

        string hashValue = Convert.ToBase64String(hashWithSaltBytes);

        return hashValue;
    }
Ejemplo n.º 30
0
        public static byte[] Sha384(byte[] data)
        {
            SHA384 sha = new SHA384Managed();

            return(sha.ComputeHash(data));
        }
Ejemplo n.º 31
0
	byte[] IHashAlgorithm.GetRunningHash ()
	{
		var copy = new SHA384Managed (this);
		copy.TransformFinalBlock (empty, 0, 0);
		return copy.Hash;
	}
Ejemplo n.º 32
0
        /// <summary>
        /// 获取Hash后的字节数组
        /// </summary>
        /// <param name="type">哈希类型</param>
        /// <param name="key">key</param>
        /// <param name="bytes">原字节数组</param>
        /// <returns></returns>
        public static byte[] GetHashedBytes(HashType type, byte[] bytes, byte[] key)
        {
            if (null == bytes || bytes.Length == 0)
            {
                return(bytes);
            }

            HashAlgorithm algorithm = null;

            try
            {
                if (key == null)
                {
                    switch (type)
                    {
                    case HashType.MD5:
                        algorithm = MD5.Create();
                        break;

                    case HashType.SHA1:
                        algorithm = new SHA1Managed();
                        break;

                    case HashType.SHA256:
                        algorithm = new SHA256Managed();
                        break;

                    case HashType.SHA384:
                        algorithm = new SHA384Managed();
                        break;

                    case HashType.SHA512:
                        algorithm = new SHA512Managed();
                        break;

                    default:
                        algorithm = MD5.Create();
                        break;
                    }
                }
                else
                {
                    switch (type)
                    {
                    case HashType.MD5:
                        algorithm = new HMACMD5(key);
                        break;

                    case HashType.SHA1:
                        algorithm = new HMACSHA1(key);
                        break;

                    case HashType.SHA256:
                        algorithm = new HMACSHA256(key);
                        break;

                    case HashType.SHA384:
                        algorithm = new HMACSHA384(key);
                        break;

                    case HashType.SHA512:
                        algorithm = new HMACSHA512(key);
                        break;

                    default:
                        algorithm = new HMACMD5(key);
                        break;
                    }
                }
                return(algorithm.ComputeHash(bytes));
            }
            finally
            {
                algorithm?.Dispose();
            }
        }
Ejemplo n.º 33
0
        public static string ComputeHash(string plainText, string hash, byte[] salt)
        {
            int minSaltLength = 4, maxSaltLength = 16;

            byte[] saltBytes = null;
            if (salt != null)
            {
                saltBytes = salt;
            }
            else
            {
                Random r          = new Random();
                int    SaltLength = r.Next(minSaltLength, maxSaltLength);
                saltBytes = new byte[SaltLength];
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                rng.GetNonZeroBytes(saltBytes);
                rng.Dispose();
            }

            byte[] plainData         = ASCIIEncoding.UTF8.GetBytes(plainText);
            byte[] plainDataWithSalt = new byte[plainData.Length + saltBytes.Length];

            for (int x = 0; x < plainData.Length; x++)
            {
                plainDataWithSalt[x] = plainData[x];
            }
            for (int n = 0; n < saltBytes.Length; n++)
            {
                plainDataWithSalt[plainData.Length + n] = saltBytes[n];
            }

            byte[] hashValue = null;

            switch (hash)
            {
            case "SHA256":
                SHA256Managed sha = new SHA256Managed();
                hashValue = sha.ComputeHash(plainDataWithSalt);
                sha.Dispose();
                break;

            case "SHA384":
                SHA384Managed sha1 = new SHA384Managed();
                hashValue = sha1.ComputeHash(plainDataWithSalt);
                sha1.Dispose();
                break;

            case "SHA512":
                SHA512Managed sha2 = new SHA512Managed();
                hashValue = sha2.ComputeHash(plainDataWithSalt);
                sha2.Dispose();
                break;
            }

            byte[] result = new byte[hashValue.Length + saltBytes.Length];
            for (int x = 0; x < hashValue.Length; x++)
            {
                result[x] = hashValue[x];
            }
            for (int n = 0; n < saltBytes.Length; n++)
            {
                result[hashValue.Length + n] = saltBytes[n];
            }

            return(Convert.ToBase64String(result));
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Generates a hash for the given plain text value and returns a
        /// base64-encoded result. Before the hash is computed, a random salt
        /// is generated and appended to the plain text. This salt is stored at
        /// the end of the hash value, so it can be used later for hash
        /// verification.
        /// </summary>
        /// <param name="byteData">
        /// Plaintext value to be hashed.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
        /// "SHA256", "SHA384", "SHA512", "HMACMD5", "HMACSHA1", "HMACSHA256",
        ///  "HMACSHA512" (if any other value is specified  MD5 will be used).
        ///
        /// HMAC algorithms uses Hash-based Message Authentication Code.
        /// The HMAC process mixes a secret key with the message data, hashes
        /// the result with the hash function, mixes that hash value with
        /// the secret key again, and then applies the hash function
        /// a second time. HMAC hashes are fixed lenght and generally
        /// much longer than non-HMAC hashes of the same type.
        ///
        /// https://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha256(v=vs.110).aspx
        ///
        /// This value is case-insensitive.
        /// </param>
        /// <param name="saltBytes">
        /// Optional but recommended salt bytes to apply to the hash. If not passed the
        /// raw encoding is used. If salt is nullthe raw algorithm is used (useful for
        /// file hashes etc.) HMAC versions REQUIRE that salt is passed.
        /// </param>
        /// <param name="useBinHex">if true returns the data as BinHex byte pair string. Otherwise Base64 is returned.</param>
        /// <returns>
        /// Hash value formatted as a base64-encoded or BinHex stringstring.
        /// </returns>
        public static string ComputeHash(byte[] byteData,
                                         string hashAlgorithm,
                                         byte[] saltBytes,
                                         bool useBinHex = false)
        {
            if (byteData == null)
            {
                return(null);
            }

            // Convert plain text into a byte array.
            byte[] plainTextWithSaltBytes;

            if (saltBytes != null && !hashAlgorithm.StartsWith("HMAC"))
            {
                // Allocate array, which will hold plain text and salt.
                plainTextWithSaltBytes =
                    new byte[byteData.Length + saltBytes.Length];

                // Copy plain text bytes into resulting array.
                for (int i = 0; i < byteData.Length; i++)
                {
                    plainTextWithSaltBytes[i] = byteData[i];
                }

                // Append salt bytes to the resulting array.
                for (int i = 0; i < saltBytes.Length; i++)
                {
                    plainTextWithSaltBytes[byteData.Length + i] = saltBytes[i];
                }
            }
            else
            {
                plainTextWithSaltBytes = byteData;
            }

            HashAlgorithm hash;

            // Make sure hashing algorithm name is specified.
            if (hashAlgorithm == null)
            {
                hashAlgorithm = "";
            }

            // Initialize appropriate hashing algorithm class.
            switch (hashAlgorithm.ToUpper())
            {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            case "HMACMD5":
                hash = new HMACMD5(saltBytes);
                break;

            case "HMACSHA1":
                hash = new HMACSHA1(saltBytes);
                break;

            case "HMACSHA256":
                hash = new HMACSHA256(saltBytes);
                break;

            case "HMACSHA512":
                hash = new HMACSHA512(saltBytes);
                break;

            default:
                // default to MD5
                hash = new MD5CryptoServiceProvider();
                break;
            }

            byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);


            hash.Dispose();

            if (useBinHex)
            {
                return(BinaryToBinHex(hashBytes));
            }

            return(Convert.ToBase64String(hashBytes));
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Concatenate a set of blobs - specified either via their prefix or an explicit list of blob names - to a single destination blob
        /// Source blobs must be from a single container. However because of the way the Azure Storage Block Blob works, you can call
        /// this function multiple times, specifying different sets of source blobs each time, and they will simply be "appended" to the destination blob.
        /// </summary>
        /// <param name="sourceStorageAccountName"></param>
        /// <param name="sourceStorageContainerName"></param>
        /// <param name="sourceStorageAccountKey"></param>
        /// <param name="sourceBlobPrefix"></param>
        /// <param name="sortBlobs"></param>
        /// <param name="sourceBlobNames"></param>
        /// <param name="destStorageAccountName"></param>
        /// <param name="destStorageAccountKey"></param>
        /// <param name="destStorageContainerName"></param>
        /// <param name="destBlobName"></param>
        public static bool BlobToBlob(string sourceStorageAccountName,
                                      string sourceStorageContainerName,
                                      string sourceStorageAccountKey,
                                      string sourceBlobPrefix,
                                      bool sortBlobs,
                                      List <string> sourceBlobNames,
                                      string destStorageAccountName,
                                      string destStorageAccountKey,
                                      string destStorageContainerName,
                                      string destBlobName)
        {
            // this will be used to compute a unique blockId for the source blocks
            var shaHasher = new SHA384Managed();

            GlobalOptimizations();

            // TODO remove hard-coding of core.windows.net
            string sourceAzureStorageConnStr = $"DefaultEndpointsProtocol=https;AccountName={sourceStorageAccountName};AccountKey={sourceStorageAccountKey};EndpointSuffix=core.windows.net";
            string destAzureStorageConnStr   = $"DefaultEndpointsProtocol=https;AccountName={destStorageAccountName};AccountKey={destStorageAccountKey};EndpointSuffix=core.windows.net";

            var destStorageAccount = CloudStorageAccount.Parse(destAzureStorageConnStr);
            var destBlobClient     = destStorageAccount.CreateCloudBlobClient();
            var destContainer      = destBlobClient.GetContainerReference(destStorageContainerName);
            var destBlob           = destContainer.GetBlockBlobReference(destBlobName);

            List <string> destBlockList = new List <string>();

            // check if the blob exists, in which case we need to also get the list of blocks associated with that blob
            // this will help to skip blocks which were already completed, and thereby help with resume
            // TODO Block IDs are not unique across files - this will trip up the logic
            if (destBlob.ExistsAsync().GetAwaiter().GetResult())
            {
                // only get committed blocks to be sure
                destBlockList = (from b in (destBlob.DownloadBlockListAsync(BlockListingFilter.Committed, null, null, null).GetAwaiter().GetResult()) select b.Name).ToList();
            }

            // create a place holder for the final block list (to be eventually used for put block list) and pre-populate it with the known list of blocks
            // already associated with the destination blob
            var finalBlockList = new List <string>();

            finalBlockList.AddRange(destBlockList);

            var sourceStorageAccount = CloudStorageAccount.Parse(sourceAzureStorageConnStr);
            var sourceBlobClient     = sourceStorageAccount.CreateCloudBlobClient();
            var sourceContainer      = sourceBlobClient.GetContainerReference(sourceStorageContainerName);

            var blobListing = new List <IListBlobItem>();
            BlobContinuationToken continuationToken = null;

            // check if there is a specific list of blobs given by the user, in which case the immediate 'if' code below will be skipped
            if (sourceBlobNames is null || sourceBlobNames.Count == 0)
            {
                // we have a prefix specified, so get a of blobs with a specific prefix and then add them to a list
                do
                {
                    var response = sourceContainer.ListBlobsSegmentedAsync(sourceBlobPrefix, true, BlobListingDetails.None, null, continuationToken, null, null).GetAwaiter().GetResult();
                    continuationToken = response.ContinuationToken;
                    blobListing.AddRange(response.Results);
                }while (continuationToken != null);

                // now just get the blob names, that's all we need for further processing
                sourceBlobNames = (from b in blobListing.OfType <CloudBlockBlob>() select b.Name).ToList();

                // if the user specified to sort the input blobs (only valid for the prefix case) then we will happily do that!
                // The gotcha here is that this is a string sort. So if blobs have names like blob_9, blob_13, blob_6, blob_3, blob_1
                // the sort order will result in blob_1, blob_13, blob_3, blob_6, blob_9.
                // To avoid issues like this the user must 0-prefix the numbers embedded in the filenames.
                if (sortBlobs)
                {
                    sourceBlobNames.Sort();
                }
            }

            // iterate through each source blob, one at a time.
            foreach (var sourceBlobName in sourceBlobNames)
            {
                Debug.WriteLine($"{DateTime.Now}: START {sourceBlobName}");

                var sourceBlob = sourceContainer.GetBlockBlobReference(sourceBlobName);

                // first we get the block list of the source blob. we use this to later parallelize the download / copy operation
                var sourceBlockList = sourceBlob.DownloadBlockListAsync(BlockListingFilter.Committed, null, null, null).GetAwaiter().GetResult();

                // in case the source blob is smaller then 256 MB (for latest API) then the blob is stored directly without any block list
                // so in this case the sourceBlockList is 0-length and we need to fake a BlockListItem as null, which will later be handled below
                if (sourceBlockList.Count() == 0 && sourceBlob.Properties.Length > 0)
                {
                    ListBlockItem fakeBlockItem = null;
                    sourceBlockList = sourceBlockList.Concat(new[] { fakeBlockItem });
                }

                var  blockRanges   = new List <BlockRange>();
                long currentOffset = 0;

                // iterate through the list of blocks and compute their effective offsets in the final file.
                int chunkIndex = 0;
                foreach (var blockListItem in sourceBlockList)
                {
                    // handle special case when the sourceBlob was put using PutBlob and has no blocks
                    var blockLength = blockListItem == null ? sourceBlob.Properties.Length : blockListItem.Length;

                    // compute a unique blockId based on blob account + container + blob name (includes path) + block length + block "number"
                    // TODO also include the endpoint when we generalize for all clouds
                    var hashBasis  = System.Text.Encoding.UTF8.GetBytes(string.Concat(sourceStorageAccountName, sourceStorageContainerName, sourceBlobName, blockLength, chunkIndex));
                    var newBlockId = Convert.ToBase64String(shaHasher.ComputeHash(hashBasis));

                    var newBlockRange = new BlockRange()
                    {
                        Name        = newBlockId,
                        StartOffset = currentOffset,
                        Length      = blockLength
                    };

                    // increment this here itself as we may potentially skip to the next blob
                    chunkIndex++;
                    currentOffset += blockLength;

                    // check if this block has already been copied + committed at the destination, and in that case, skip it
                    if (destBlockList.Contains(newBlockId))
                    {
                        continue;
                    }
                    else
                    {
                        blockRanges.Add(newBlockRange);
                    }
                }

                Debug.WriteLine($"Number of ranges: {blockRanges.Count}");

                // reset back to 0 to actually execute the copies
                currentOffset = 0;

                // proceed to copy blocks in parallel. to do this, we download to a local memory stream and then push that back out to the destination blob
                Parallel.ForEach <BlockRange, MD5CryptoServiceProvider>(blockRanges, new ParallelOptions()
                {
                    MaxDegreeOfParallelism = Environment.ProcessorCount * 8
                },
                                                                        () =>
                {
                    // this will be a "task-local" copy. Better than creating this within the task, as that will be slighly expensive.
                    return(new MD5CryptoServiceProvider());
                },
                                                                        (currRange, loopState, hasher) =>
                {
                    // TODO do we really need this copy?
                    var sourceBlobLocalCopy = sourceBlob; // sourceContainer.GetBlockBlobReference(sourceBlobName);

                    // TODO verify cast
                    using (var memStream = new MemoryStream((int)currRange.Length))
                    {
                        sourceBlobLocalCopy.DownloadRangeToStreamAsync(memStream, currRange.StartOffset, currRange.Length).GetAwaiter().GetResult();

                        // compute the hash, for which we need to reset the memory stream
                        memStream.Position = 0;
                        var md5Checksum    = hasher.ComputeHash(memStream);

                        // reset the memory stream again to 0 and then call Azure Storage to put this as a block with the given block ID and MD5 hash
                        memStream.Position = 0;

                        Debug.WriteLine($"Putting block {currRange.Name}");

                        destBlob.PutBlockAsync(currRange.Name, memStream, Convert.ToBase64String(md5Checksum)).GetAwaiter().GetResult();
                    }

                    return(hasher);
                },
                                                                        (hasherFinally) => { }
                                                                        );

                // keep adding the blocks we just copied, to the final block list
                finalBlockList.AddRange(from r in blockRanges select r.Name);

                // TODO review this whether we put this for each source file or at the end of all source files
                // when we are all done, execute a "commit" by using Put Block List operation
                destBlob.PutBlockListAsync(finalBlockList).GetAwaiter().GetResult();

                Debug.WriteLine($"{DateTime.Now}: END {sourceBlobName}");

                // TODO optionally allow user to specify extra character(s) to append in between files. This is typically needed when the source files do not have a trailing \n character.
            }

            // release the SHA hasher resources
            shaHasher.Dispose();

            // TODO handle failures.
            return(true);
        }
Ejemplo n.º 36
0
    /// <summary>
    /// Generates a hash for the given plain text value and returns a
    /// base64-encoded result. Before the hash is computed, a random salt
    /// is generated and appended to the plain text. This salt is stored at
    /// the end of the hash value, so it can be used later for hash
    /// verification.
    /// </summary>
    /// <param name="plainText">
    /// Plaintext value to be hashed. 
    /// </param>
    /// <param name="hashAlgorithm">
    /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
    /// "SHA256", "SHA384", and "SHA512" (if any other value is specified
    /// MD5 hashing algorithm will be used). This value is case-insensitive.
    /// </param>
    /// <param name="saltBytes">
    /// Salt bytes. This parameter can be null, in which case a random salt
    /// value will be generated.
    /// </param>
    /// <returns>
    /// Hash value formatted as a base64-encoded string.
    /// </returns>
    /// <remarks>
    /// ComputeHash code provided as an example by Obviex at
    /// http://www.obviex.com/samples/hash.aspx
    /// As noted by Obviex themselves, code is definitely not optimally efficient.
    /// Should performance requirements necessitate improvement, this should
    /// be improved.
    /// </remarks>
    public static string ComputeHash(string plainText,
                                     string hashAlgorithm,
                                     byte[] saltBytes)
    {
        if (plainText == null)
            return null;

        // If salt is not specified, generate it on the fly.
        if (saltBytes == null)
        {
            // Define min and max salt sizes.
            int minSaltSize = 4;
            int maxSaltSize = 8;

            // Generate a random number for the size of the salt.
            Random random = new Random();
            int saltSize = random.Next(minSaltSize, maxSaltSize);

            // Allocate a byte array, which will hold the salt.
            saltBytes = new byte[saltSize];

            // Initialize a random number generator.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            // Fill the salt with cryptographically strong byte values.
            rng.GetNonZeroBytes(saltBytes);
        }

        // Convert plain text into a byte array.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        // Allocate array, which will hold plain text and salt.
        byte[] plainTextWithSaltBytes =
                new byte[plainTextBytes.Length + saltBytes.Length];

        // Copy plain text bytes into resulting array.
        for (int i = 0; i < plainTextBytes.Length; i++)
            plainTextWithSaltBytes[i] = plainTextBytes[i];

        // Append salt bytes to the resulting array.
        for (int i = 0; i < saltBytes.Length; i++)
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];

        // Because we support multiple hashing algorithms, we must define
        // hash object as a common (abstract) base class. We will specify the
        // actual hashing algorithm class later during object creation.
        HashAlgorithm hash;

        // Make sure hashing algorithm name is specified.
        if (hashAlgorithm == null)
            hashAlgorithm = "";

        // Initialize appropriate hashing algorithm class.
        switch (hashAlgorithm.ToUpper())
        {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
        }

        // Compute hash value of our plain text with appended salt.
        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

        // Create array which will hold hash and original salt bytes.
        byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                            saltBytes.Length];

        // Copy hash bytes into resulting array.
        for (int i = 0; i < hashBytes.Length; i++)
            hashWithSaltBytes[i] = hashBytes[i];

        // Append salt bytes to the result.
        for (int i = 0; i < saltBytes.Length; i++)
            hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];

        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(hashWithSaltBytes);

        // Return the result.
        return hashValue;
    }
Ejemplo n.º 37
0
        public override void GenerateKey(string secretKey, AlgorithmKeyType type)
        {
            this.Key = new byte[24];
            this.IV  = new byte[8];
            byte[] bytes = Encoding.UTF8.GetBytes(secretKey);
            switch (type)
            {
            case AlgorithmKeyType.SHA1:
                using (SHA1Managed shA1Managed = new SHA1Managed())
                {
                    shA1Managed.ComputeHash(bytes);
                    byte[] hash = shA1Managed.Hash;
                    for (int index = 0; index < 20; ++index)
                    {
                        this.Key[index] = hash[index];
                    }
                    for (int index = 16; index > 8; --index)
                    {
                        this.IV[16 - index] = hash[index];
                    }
                    break;
                }

            case AlgorithmKeyType.SHA256:
                using (SHA256Managed shA256Managed = new SHA256Managed())
                {
                    shA256Managed.ComputeHash(bytes);
                    byte[] hash = shA256Managed.Hash;
                    for (int index = 0; index < 24; ++index)
                    {
                        this.Key[index] = hash[index];
                    }
                    for (int index = 31; index >= 24; --index)
                    {
                        this.IV[31 - index] = hash[index];
                    }
                    break;
                }

            case AlgorithmKeyType.SHA384:
                using (SHA384Managed shA384Managed = new SHA384Managed())
                {
                    shA384Managed.ComputeHash(bytes);
                    byte[] hash = shA384Managed.Hash;
                    for (int index = 0; index < 24; ++index)
                    {
                        this.Key[index] = hash[index];
                    }
                    for (int index = 47; index > 39; --index)
                    {
                        this.IV[47 - index] = hash[index];
                    }
                    break;
                }

            case AlgorithmKeyType.SHA512:
                using (SHA512Managed shA512Managed = new SHA512Managed())
                {
                    shA512Managed.ComputeHash(bytes);
                    byte[] hash = shA512Managed.Hash;
                    for (int index = 0; index < 24; ++index)
                    {
                        this.Key[index] = hash[index];
                    }
                    for (int index = 63; index > 55; --index)
                    {
                        this.IV[63 - index] = hash[index];
                    }
                    break;
                }

            case AlgorithmKeyType.MD5:
                using (MD5CryptoServiceProvider cryptoServiceProvider = new MD5CryptoServiceProvider())
                {
                    cryptoServiceProvider.ComputeHash(bytes);
                    byte[] hash = cryptoServiceProvider.Hash;
                    for (int index = 0; index < 16; ++index)
                    {
                        this.Key[index] = hash[index];
                    }
                    for (int index = 15; index >= 8; --index)
                    {
                        this.IV[15 - index] = hash[index];
                    }
                    break;
                }
            }
        }