예제 #1
0
파일: Hash.cs 프로젝트: REMSLogic/REMSLogic
        public static string GetHash(string text, string type, Encoding enc, string outputType = null)
        {
            type = type.ToLower();

            byte[] message = enc.GetBytes( text );
            HashAlgorithm algo = null;

            switch (type)
            {
            case "md5":
                algo = new MD5CryptoServiceProvider();
                break;
            case "sha1":
                algo = new SHA1Managed();
                break;
            case "sha256":
                algo = new SHA256Managed();
                break;
            case "sha384":
                algo = new SHA384Managed();
                break;
            case "sha512":
                algo = new SHA512Managed();
                break;
            default:
                throw new ArgumentException("Type must be one of ['md5', 'sha1', 'sha256', 'sha384', 'sha512'].", "type");
            }

            return GetOutput( algo.ComputeHash( message ), outputType );
        }
예제 #2
0
        /// <summary>
        /// Encrypts the specified password using the specified hash algoritm
        /// </summary>
        /// <param name="passWord"></param>
        /// <param name="salt"></param>
        /// <param name="hashAlgoritm"></param>
        /// <returns></returns>
        public static string EncryptPassWord(string passWord, string salt, HashAlgoritm hashAlgoritm)
        {
            UTF8Encoding textConverter = new UTF8Encoding();
            HashAlgorithm hash;

            switch (hashAlgoritm)
            {
                case HashAlgoritm.SHA1:
                    hash = new SHA1Managed();
                    break;
                case HashAlgoritm.SHA256:
                    hash = new SHA256Managed();
                    break;
                case HashAlgoritm.SHA384:
                    hash = new SHA384Managed();
                    break;
                case HashAlgoritm.SHA512:
                    hash = new SHA512Managed();
                    break;
                default:
                    hash = new MD5CryptoServiceProvider();
                    break;
            }

            string tmpPassword = string.Format("{0}_{1}", passWord, salt);
            byte[] passBytes = textConverter.GetBytes(tmpPassword);

            return Convert.ToBase64String(hash.ComputeHash(passBytes));
        }
예제 #3
0
 /// <summary>
 /// Every time is created new instance of class to guarantee thread safety
 /// </summary>
 /// <param name="function"></param>
 /// <returns></returns>
 private HashAlgorithm GetAlgorithmByFunctionName(string function)
 {
     HashAlgorithm a;
     switch (Util.Convertion.EnumNameToValue<HashFunction>(function))
     {
         case HashFunction.MD5:
             a = new MD5CryptoServiceProvider();
             break;
         case HashFunction.SHA1:
             a = new SHA1Managed();
             break;
         case HashFunction.SHA256:
             a = new SHA256Managed();
             break;
         case HashFunction.SHA384:
             a = new SHA384Managed();
             break;
         case HashFunction.SHA512:
             a = new SHA512Managed();
             break;
         default:
             throw new ArgumentException("Unknown function", "function");
     }
     return a;
 }
예제 #4
0
파일: Crypto.cs 프로젝트: Ranentil/diamonds
 public static string sha384encrypt(string phrase)
 {
     UTF8Encoding encoder = new UTF8Encoding();
     SHA384Managed sha384hasher = new SHA384Managed();
     byte[] hashedDataBytes = sha384hasher.ComputeHash(encoder.GetBytes(phrase));
     return byteArrayToString(hashedDataBytes);
 }
예제 #5
0
파일: Encryption.cs 프로젝트: lamemmv/apex
        private static HashAlgorithm GetHashProvider(HashProvider hashAlgorithm)
        {
            HashAlgorithm hash;
            switch (hashAlgorithm)
            {
                case HashProvider.SHA1:
                    hash = new SHA1Managed();
                    break;

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

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

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

                case HashProvider.MD5:
                default:
                    hash = new MD5CryptoServiceProvider();
                    break;
            }

            return hash;
        }
예제 #6
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>
        /// <returns>
        /// Hash value formatted as a base64-encoded string.
        /// </returns>
        public static string ComputeHash(string plainText,
                                         HashType hashType)
        {
            // Convert plain text into a byte array.
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // Allocate array, which will hold plain text.
            var plainTextWithSaltBytes =
                new byte[plainTextBytes.Length];

            // Copy plain text bytes into resulting array.
            for (int i = 0; i < plainTextBytes.Length; i++)
                plainTextWithSaltBytes[i] = plainTextBytes[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 (hashType.ToString())
            {
                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.
            var hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

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

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

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

            // Return the result.
            return hashValue;
        }
예제 #7
0
 /// <summary>
 /// SHA384加密,不可逆转
 /// </summary>
 /// <param name="str">string str:被加密的字符串</param>
 /// <returns>返回加密后的字符串</returns>
 public string SHA384Encrypt(string str)
 {
     System.Security.Cryptography.SHA384 s384 = new System.Security.Cryptography.SHA384Managed();
     byte[] byte1;
     byte1 = s384.ComputeHash(Encoding.UTF8.GetBytes(str));
     s384.Clear();
     return Convert.ToBase64String(byte1);
 }
예제 #8
0
 private void SetKeyButton_Click(object sender, EventArgs e)
 {
     var passwordBytes = Encoding.ASCII.GetBytes(PasswordBox.Text);
     SHA384 sha = new SHA384Managed();
     _cryptor.Key = sha.ComputeHash(passwordBytes);
     EncryptButton.Enabled = true;
     DecryptButton.Enabled = false;
 }
예제 #9
0
 /// <summary>
         /// SHA384加密,不可逆转
         /// </summary>
         /// <param name="str">string str:被加密的字符串</param>
         /// <returns>返回加密后的字符串</returns>
 private static string SHA384Encrypt(string str)
 {
     System.Security.Cryptography.SHA384 s384 = new System.Security.Cryptography.SHA384Managed();
     byte[] byte1;
     byte1 = s384.ComputeHash(Encoding.Default.GetBytes(str));
     s384.Clear();
     return(Convert.ToBase64String(byte1));
 }
예제 #10
0
 public static string SHA384(string data)
 {
     byte[] hash;
     using (SHA384 shaM = new SHA384Managed())
     {
         hash = shaM.ComputeHash(data.GetBytes());
     }
     return AESProvider.HexString(hash);
 }
예제 #11
0
        public static byte[] SHA384Compute(byte[] data)
        {
            if (data == null)
                throw new ArgumentNullException("data");

            SHA384Managed SHA384 = new SHA384Managed();
            byte[] hash = SHA384.ComputeHash(data);
            SHA384.Clear();
            return hash;
        }
예제 #12
0
        public static string ComputeHash(string plainText, HashAlgorithm hashAlgorithm, string salt)
        {
            System.Security.Cryptography.HashAlgorithm hash;

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

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

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

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

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

            byte[] saltBytes = Encoding.UTF8.GetBytes(salt);

            byte[] plainTextWithSalt = Encoding.UTF8.GetBytes(plainText + salt);
            byte[] hashBytes = hash.ComputeHash(plainTextWithSalt);
            string hashValue = System.Convert.ToBase64String(hashBytes);

            ////// 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 hashValue;
        }
예제 #13
0
        public static 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;
        }
예제 #14
0
        public static string Sha384(string msg)
        {
            if (msg == null)
                return null;

            var encoder = new UTF8Encoding();
            var sha384Hasher = new SHA384Managed();
            var hashedDataBytes = sha384Hasher.ComputeHash(encoder.GetBytes(msg));

            return ByteArrayToString(hashedDataBytes);
        }
예제 #15
0
 public static string SHA384Hash(string Paragraph)
 {
     SHA384 sha = new SHA384Managed();
     byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(Paragraph));
     StringBuilder sb = new StringBuilder();
     foreach (byte bt in hash)
     {
         sb.AppendFormat("{0:x2}", bt);
     }
     return sb.ToString();
 }
예제 #16
0
        /// <summary>
        /// Encrypts a string using the SHA384(Secure Hash Algorithm) algorithm.
        /// This works in the same manner as MD5, providing 384bit encryption.
        /// </summary>
        /// <param name="Data">A string containing the data to encrypt.</param>
        /// <returns>A string containing the string, encrypted with the SHA384 algorithm.</returns>
        public static string SHA384Hash(string Data)
        {
            SHA384 sha = new SHA384Managed();
            byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(Data));

            StringBuilder stringBuilder = new StringBuilder();
            foreach (byte b in hash)
            {
                stringBuilder.AppendFormat("{0:x2}", b);
            }
            return stringBuilder.ToString();
        }
예제 #17
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;
 }
예제 #18
0
        public RijndaelEncryptor()
        {
            m_key = new byte[32];
            m_vector = new byte[16];

            using (var sha = new SHA384Managed())
            {
                byte[] hashArray = sha.ComputeHash(hashBuffer);

                Array.Copy(hashArray, 0, m_key, 0, 32);
                Array.Copy(hashArray, 32, m_vector, 0, 16);
            }
        }
예제 #19
0
        public static String GetSHA384(String strPlain)
        {
            UnicodeEncoding UE = new UnicodeEncoding();
            Byte[] HashValue, MessageBytes = UE.GetBytes(strPlain);
            SHA384Managed SHhash = new SHA384Managed();
            String strHex = String.Empty;

            HashValue = SHhash.ComputeHash(MessageBytes);
            foreach (Byte b in HashValue)
            {
                strHex += String.Format("{0:x2}", b);
            }
            return strHex;
        }
예제 #20
0
 public static string ComputeHash(string plainText, HashAlgorithmType hashAlgorithm, bool outputHexFormat)
 {
     HashAlgorithm algorithm;
     plainText = (SALTHash + plainText);
     byte[] bytes = Encoding.UTF8.GetBytes(plainText);
     switch (hashAlgorithm)
     {
         case HashAlgorithmType.SHA1:
             algorithm = new SHA1Managed();
             break;
         case HashAlgorithmType.SHA256:
             algorithm = new SHA256Managed();
             break;
         case HashAlgorithmType.SHA384:
             algorithm = new SHA384Managed();
             break;
         case HashAlgorithmType.SHA512:
             algorithm = new SHA512Managed();
             break;
         default:
             algorithm = new MD5CryptoServiceProvider();
             break;
     }
     byte[] inArray = algorithm.ComputeHash(bytes);
     if (outputHexFormat)
     {
         var builder = new StringBuilder();
         int num2 = (inArray.Length - 1);
         int i = 0;
         while ((i <= num2))
         {
             if ((Conversion.Hex(inArray[i]).Length == 1))
             {
                 builder.Append(("0" + Conversion.Hex(inArray[i])));
             }
             else
             {
                 builder.Append(Conversion.Hex(inArray[i]));
             }
             if ((((i + 1)%2) == 0))
             {
                 builder.Append(" ");
             }
             i++;
         }
         return builder.ToString().Trim().Replace(" ", "-");
     }
     return Convert.ToBase64String(inArray);
 }
예제 #21
0
        public static string GetFileHash(string filePath, HashType type)
        {
            if (!File.Exists(filePath))
                return string.Empty;

            System.Security.Cryptography.HashAlgorithm hasher;
            switch(type)
            {
                case HashType.SHA1:
                default:
                    hasher = new SHA1CryptoServiceProvider();
                    break;
                case HashType.SHA256:
                    hasher = new SHA256Managed();
                    break;
                case HashType.SHA384:
                    hasher = new SHA384Managed();
                    break;
                case HashType.SHA512:
                    hasher = new SHA512Managed();
                    break;
                case HashType.MD5:
                    hasher = new MD5CryptoServiceProvider();
                    break;
                case HashType.RIPEMD160:
                    hasher = new RIPEMD160Managed();
                    break;
            }
            StringBuilder buff = new StringBuilder();
            try
            {
                using (FileStream f = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192))
                {
                    hasher.ComputeHash(f);
                    Byte[] hash = hasher.Hash;
                    foreach (Byte hashByte in hash)
                    {
                        buff.Append(string.Format("{0:x2}", hashByte));
                    }
                }
            }
            catch
            {
                return "Error reading file." + new System.Random(DateTime.Now.Second * DateTime.Now.Millisecond).Next().ToString();
            }
            return buff.ToString();
        }
예제 #22
0
        /// <summary>
        /// Make hash with salt (stored at the end)
        /// </summary>
        /// <param name="text">
        /// Original text
        /// </param>
        /// <param name="hashAlgorithm">
        /// Hash algorithm: MD5, SHA1, SHA256, SHA384, SHA512 (default MD5)
        /// </param>
        /// <param name="useSalt">
        /// Use salt for generate hash
        /// </param>
        /// <param name="saltBytes">
        /// Salt bytes (if missing, use random salt)
        /// </param>
        /// <returns>
        /// Hash value formatted as a base64-encoded string.
        /// </returns>
        public static string ComputeHash(string text, HashAlgorithmEnum hashAlgorithm = HashAlgorithmEnum.MD5, bool useSalt = true, byte[] saltBytes = null)
        {
            if (text != String.Empty)
            {
                string hashValue = "";
                HashAlgorithm hash;
                switch (hashAlgorithm)
                {
                    case HashAlgorithmEnum.SHA1: hash = new SHA1Managed(); break;
                    case HashAlgorithmEnum.SHA256: hash = new SHA256Managed(); break;
                    case HashAlgorithmEnum.SHA384: hash = new SHA384Managed(); break;
                    case HashAlgorithmEnum.SHA512: hash = new SHA512Managed(); break;
                    default: hash = new MD5CryptoServiceProvider(); break;
                }
                if (useSalt)
                {
                    if (saltBytes == null)
                    {
                        int minSaltSize = 4;
                        int maxSaltSize = 8;
                        saltBytes = new byte[(new System.Random()).Next(minSaltSize, maxSaltSize)];
                        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                        rng.GetNonZeroBytes(saltBytes);
                    }
                    byte[] plainTextBytes = Encoding.UTF8.GetBytes(text);
                    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];

                    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];
                    hashValue = Convert.ToBase64String(hashWithSaltBytes);
                }
                else
                {
                    hashValue = Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(text)));
                }
                return hashValue;
            }
            else
                return null;
        }
예제 #23
0
        /// <summary>
        /// Encrypts the specified value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="includeTag">if set to <c>true</c> include the module Tag.</param>
        /// <returns>
        /// The encrypted hash.
        /// </returns>
        /// <exception cref="Haxxor.Framework.Core.Exceptions.HaxxorException">Value cannot be null when encrypting.</exception>
        public override string Encrypt(string value, bool includeTag = true)
        {
            if (value == null)
            {
                throw new HaxxorException("Value cannot be null when encrypting.");
            }

            var bytes = CryptoHelper.GetBytes(value);

            using (var sha = new SHA384Managed())
            {
                var hash = sha.ComputeHash(bytes);
                var hash64 = Convert.ToBase64String(hash);

                return includeTag
                    ? CryptoHelper.FormatTagHash(Tag, hash64)
                    : hash64;
            }
        }
예제 #24
0
        public static byte[] HashData(TpmAlgId algId, byte[] dataToHash)
        {
#if TSS_USE_BCRYPT
            string algName = Native.BCryptHashAlgName(algId);
            if (string.IsNullOrEmpty(algName))
            {
                Globs.Throw<ArgumentException>("HashData(): Unsupported hash algorithm " + algId);
                return null;
            }

            var alg = new BCryptAlgorithm(algName);
            var digest = alg.HashData(dataToHash);
            alg.Close();
            return digest;
#else
            HashAlgorithm hashAlg = null;
            switch (algId)
            {
                case TpmAlgId.Sha1:
                    hashAlg = new SHA1Managed();
                    break;
                case TpmAlgId.Sha256:
                    hashAlg = new SHA256Managed();
                    break;
                case TpmAlgId.Sha384:
                    hashAlg = new SHA384Managed();
                    break;
                case TpmAlgId.Sha512:
                    hashAlg = new SHA512Managed();
                    break;
                default:
                    Globs.Throw<ArgumentException>("AlgId is not a supported hash algorithm");
                    return null;
            }
            return hashAlg.ComputeHash(dataToHash);
#endif
        }
예제 #25
0
        /// <summary>
        /// Generates a hash based on the source text.
        /// </summary>
        /// <param name="SourceText">The text to hash.</param>
        /// <returns>The hashed text as a Base64 string.</returns>
        public static string GenerateHash(string sourceText, string salt, HashType hashType)
        {
            sourceText = sourceText + salt;

            System.Security.Cryptography.HashAlgorithm hasher;
            switch (hashType) {
                case HashType.SHA1:
                default:
                    hasher = new SHA1CryptoServiceProvider();
                    break;
                case HashType.SHA256:
                    hasher = new SHA256Managed();
                    break;
                case HashType.SHA384:
                    hasher = new SHA384Managed();
                    break;
                case HashType.SHA512:
                    hasher = new SHA512Managed();
                    break;
                case HashType.MD5:
                    hasher = new MD5CryptoServiceProvider();
                    break;
                case HashType.RIPEMD160:
                    hasher = new RIPEMD160Managed();
                    break;
            }

            StringBuilder buffer = new StringBuilder();
            UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
            //Retrieve a byte array based on the source text
            byte[] byteSourceText = unicodeEncoding.GetBytes(sourceText);
            hasher.ComputeHash(byteSourceText);
            foreach (Byte hashByte in hasher.Hash) {
                buffer.Append(string.Format("{0:x2}", hashByte));
            }
            return buffer.ToString();
        }
예제 #26
0
        /// <summary>
        /// <c>ComputeHashWithoutSalt</c> member function
        /// this function calls <c>ComputeHash</c> member function to calculate hash value of provided  data
        /// </summary>
        /// <param name="plainText"></param>
        /// <param name="hashAlgorithm"></param>
        /// <returns></returns>
        public static string ComputeHashWithoutSalt(string plainText, string hashAlgorithm)
        {
            string result = "";
            try
            {
                // Convert plain text into a byte array.
                byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
                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(plainTextBytes);
                result = Convert.ToBase64String(hashBytes);
            }
            catch (Exception)
            {

            }

            ListWebClass.Log("Calculated Hash 10:" + result, false);
            while (result.IndexOf('/') != -1)
            {
                try
                {
                    result = result.Remove(result.IndexOf('/'), 1);
                }
                catch (Exception)
                {

                }
            }
            ListWebClass.Log("Updated Hash 10:" + result, false);
            return result;
        }
예제 #27
0
		public string ComputeHash(string plainText, string hashAlgorithm)
		{
			// Convert plain text into a byte array.
			byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

			// 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(plainTextBytes);

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

			// Return the result.
			return hashValue;
		}
	protected override void SetUp () 
	{
		hash = new SHA384Managed ();
	}
예제 #29
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)
            {
                // 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);
        }
 // Token: 0x0600237A RID: 9082 RVA: 0x00081538 File Offset: 0x0007F738
 private static ulong Sigma_1(ulong x)
 {
     return(SHA384Managed.RotateRight(x, 14) ^ SHA384Managed.RotateRight(x, 18) ^ SHA384Managed.RotateRight(x, 41));
 }
 // Token: 0x0600237B RID: 9083 RVA: 0x00081554 File Offset: 0x0007F754
 private static ulong sigma_0(ulong x)
 {
     return(SHA384Managed.RotateRight(x, 1) ^ SHA384Managed.RotateRight(x, 8) ^ x >> 7);
 }
 // Token: 0x0600237C RID: 9084 RVA: 0x00081569 File Offset: 0x0007F769
 private static ulong sigma_1(ulong x)
 {
     return(SHA384Managed.RotateRight(x, 19) ^ SHA384Managed.RotateRight(x, 61) ^ x >> 6);
 }
예제 #33
0
        /// <summary>
        /// <c>ComputeHash</c> member function
        /// calculates hash value
        /// </summary>
        /// <param name="plainText"></param>
        /// <param name="hashAlgorithm"></param>
        /// <param name="saltBytes"></param>
        /// <returns></returns>
        public static string ComputeHash(string plainText, string 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;

            // 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;
        }
예제 #34
0
        private string step_3(string filename) //Core validation
        {
            string[] SUPPORTED_TRANSFORMS =
            {
                "http://www.w3.org/TR/2001/REC-xml-c14n-20010315",
                "http://www.w3.org/2000/09/xmldsig#base64",
            };
            string[] SUPPORTED_DIGEST_METHOD =
            {
                "http://www.w3.org/2001/04/xmlenc#sha512 ",
                "http://www.w3.org/2001/04/xmldsig-more#sha384",
                "http://www.w3.org/2001/04/xmlenc#sha256",
                "http://www.w3.org/2001/04/xmldsig-more#sha224",
                "http://www.w3.org/2000/09/xmldsig#sha1",
            };

            XmlDocument xades = new XmlDocument();

            xades.Load(filename);
            var namespaceId = new XmlNamespaceManager(xades.NameTable);

            namespaceId.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
            namespaceId.AddNamespace("xades", "http://uri.etsi.org/01903/v1.3.2#");



            //check ds:SignedInfo and ds:Manifest
            XmlNode     signedInfoN       = xades.SelectSingleNode(@"//ds:SignedInfo", namespaceId);
            XmlNodeList referenceElements = signedInfoN.SelectNodes(@"//ds:Reference", namespaceId);

            //Reference in SignedInfo
            foreach (XmlNode reference in referenceElements)
            {
                String ReferenceURI = reference.Attributes.GetNamedItem("URI").Value;
                ReferenceURI = ReferenceURI.Substring(1);
                XmlNode digestMethod          = reference.SelectSingleNode("ds:DigestMethod", namespaceId);
                String  digestMethodAlgorithm = digestMethod.Attributes.GetNamedItem("Algorithm").Value;
                string  dsDigestValue         = reference.SelectSingleNode("ds:DigestValue", namespaceId).InnerText;

                if (ReferenceURI.StartsWith("ManifestObject"))
                {
                    //get Manifest XML and check DigestValue
                    string               manifestXML = xades.SelectSingleNode("//ds:Manifest[@Id='" + ReferenceURI + "']", namespaceId).OuterXml;
                    MemoryStream         sManifest   = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(manifestXML));
                    XmlDsigC14NTransform t           = new XmlDsigC14NTransform();
                    t.LoadInput(sManifest);
                    HashAlgorithm hash = null;

                    switch (digestMethodAlgorithm)
                    {
                    case "http://www.w3.org/2000/09/xmldsig#sha1":
                        hash = new System.Security.Cryptography.SHA1Managed();
                        break;

                    case "http://www.w3.org/2001/04/xmlenc#sha256":
                        hash = new System.Security.Cryptography.SHA256Managed();
                        break;

                    case "http://www.w3.org/2001/04/xmldsig-more#sha384":
                        hash = new System.Security.Cryptography.SHA384Managed();
                        break;

                    case "http://www.w3.org/2001/04/xmlenc#sha512":
                        hash = new System.Security.Cryptography.SHA512Managed();
                        break;
                    }

                    if (hash == null)
                    {
                        return("nesprávny hashovací algoritmus " + digestMethodAlgorithm);
                    }

                    byte[] digest = t.GetDigestedOutput(hash);
                    string result = Convert.ToBase64String(digest);

                    Console.WriteLine("-");
                    Console.WriteLine("Overenie hodnoty podpisu");
                    Console.WriteLine(result);
                    Console.WriteLine(dsDigestValue);
                    Console.WriteLine("-");

                    if (!result.Equals(dsDigestValue))
                    {
                        return("hodnoty DigestValue s výpočtom Manifest sa nezhodujú");
                    }
                }
            }

            //signed info kanonikalizovat

            XmlNode checkData = xades.SelectSingleNode(@"//ds:KeyInfo/ds:X509Data/ds:X509Certificate", namespaceId);

            if (checkData == null)
            {
                return("neobsahuje element ds:X509Data");
            }

            byte[]  signatureCertificate   = Convert.FromBase64String(xades.SelectSingleNode(@"//ds:KeyInfo/ds:X509Data/ds:X509Certificate", namespaceId).InnerText);
            byte[]  signature              = Convert.FromBase64String(xades.SelectSingleNode(@"//ds:SignatureValue", namespaceId).InnerText);
            XmlNode signedInfoNnn          = xades.SelectSingleNode(@"//ds:SignedInfo", namespaceId);
            string  signedInfoTransformAlg = xades.SelectSingleNode(@"//ds:SignedInfo/ds:CanonicalizationMethod", namespaceId).Attributes.GetNamedItem("Algorithm").Value;
            string  signedInfoSignatureAlg = xades.SelectSingleNode(@"//ds:SignedInfo/ds:SignatureMethod", namespaceId).Attributes.GetNamedItem("Algorithm").Value;

            XmlDsigC14NTransform t1  = new XmlDsigC14NTransform(false);
            XmlDocument          pom = new XmlDocument();

            pom.LoadXml(signedInfoNnn.OuterXml);
            t1.LoadInput(pom);
            byte[] data = ((MemoryStream)t1.GetOutput()).ToArray();

            string errMsg = "";
            bool   res    = this.verifySign(signatureCertificate, signature, data, signedInfoSignatureAlg, out errMsg);

            if (!res)
            {
                Console.WriteLine("Error " + errMsg);
                return(errMsg);
            }


            //check Id in ds:Signature
            XmlNode dsSignatureId = xades.SelectSingleNode("//ds:Signature", namespaceId).Attributes["Id"];

            if (dsSignatureId == null)
            {
                return("ds:Signature nemá atribút Id");
            }
            //check namespace in ds:Signature
            XmlNode dsSignatureXmlns = xades.SelectSingleNode("//ds:Signature", namespaceId).Attributes["xmlns:ds"];

            if (dsSignatureXmlns == null)
            {
                return("ds:Signature nemá špecifikovaný namespace xmlns:ds");
            }



            //check SignatureValue Id
            XmlNode dsSignatureValueId = xades.SelectSingleNode("//ds:SignatureValue", namespaceId).Attributes["Id"];

            if (dsSignatureValueId == null)
            {
                return("ds:SignatureValue nemá atribút Id");
            }



            //check reference in ds:SignedInfo
            XmlNode     signedInfo  = xades.SelectSingleNode("//ds:SignedInfo", namespaceId);
            XmlNodeList dsKeyInfoId = signedInfo.SelectNodes("//ds:Reference", namespaceId);

            if (dsKeyInfoId.Count < 1)
            {
                return("ds:SignedInfo neobsahuje ds:Reference");
            }
            String        KeyInfo             = "";
            String        SignatureProperties = "";
            String        SignedProperties    = "";
            List <string> Manifest            = new List <string>();

            //get URI
            foreach (XmlNode ReferenceList in dsKeyInfoId)
            {
                if (ReferenceList.Attributes["Id"] == null)
                {
                    continue;
                }
                else if (ReferenceList.Attributes["Id"] != null)
                {
                    if (ReferenceList.Attributes["Type"].Value.Contains("Object"))
                    {
                        KeyInfo = ReferenceList.Attributes["URI"].Value;
                        KeyInfo = KeyInfo.Substring(1);
                    }
                    else if (ReferenceList.Attributes["Type"].Value.Contains("SignatureProperties"))
                    {
                        SignatureProperties = ReferenceList.Attributes["URI"].Value;
                        SignatureProperties = SignatureProperties.Substring(1);
                    }
                    else if (ReferenceList.Attributes["Type"].Value.Contains("SignedProperties"))
                    {
                        SignedProperties = ReferenceList.Attributes["URI"].Value;
                        SignedProperties = SignedProperties.Substring(1);
                    }
                    else if (ReferenceList.Attributes["Type"].Value.Contains("Manifest"))
                    {
                        String tmp = ReferenceList.Attributes["URI"].Value;
                        tmp = tmp.Substring(1);
                        Manifest.Add(tmp);
                    }
                }
            }
            //check if exist ds:KeyInfo, ds:SignatureProperties, xades:SignedProperties
            XmlNode ElementKeyInfo             = xades.SelectSingleNode("//ds:KeyInfo", namespaceId);
            XmlNode ElementSignatureProperties = xades.SelectSingleNode("//ds:SignatureProperties", namespaceId);
            XmlNode ElementSignedProperties    = xades.SelectSingleNode("//xades:SignedProperties", namespaceId);

            if (ElementKeyInfo.Attributes["Id"] == null)
            {
                return("ds:Keyinfo nemá atribút Id");
            }
            if (!ElementKeyInfo.Attributes["Id"].Value.Equals(KeyInfo))
            {
                return("ds:Keyinfo, nezhoduje sa Id s URI");
            }

            if (ElementSignatureProperties.Attributes["Id"] == null)
            {
                return("ds:SignatureProperties nemá atribút Id");
            }
            if (!ElementSignatureProperties.Attributes["Id"].Value.Equals(SignatureProperties))
            {
                return("ds:SignatureProperties, nezhoduje sa Id s URI");
            }

            if (ElementSignedProperties.Attributes["Id"] == null)
            {
                return("xades:SignedProperties nemá atribút Id");
            }
            if (!ElementSignedProperties.Attributes["Id"].Value.Equals(SignedProperties))
            {
                return("xades:SignedProperties, nezhoduje sa Id s URI");
            }

            //check if exist ds:Manifest
            XmlNodeList ElementManifest = xades.SelectNodes("//ds:Manifest", namespaceId);
            bool        flag            = false;

            foreach (XmlNode OneManifest in ElementManifest)
            {
                foreach (String ManifestURI in Manifest)
                {
                    if (OneManifest.Attributes["Id"] == null || !OneManifest.Attributes["Id"].Value.Equals(ManifestURI))
                    {
                        flag = true;
                    }
                }
            }
            if (!flag)
            {
                return("ds:Manifest nemá atribút Id alebo sa nezhoduje Id s URI");
            }



            //check ds:KeyInfo Id
            if (ElementKeyInfo.Attributes["Id"] == null)
            {
                return("element ds:KeyInfo nemá atribút Id");
            }
            //check ds:KeyInfo elements
            XmlNode X509Data = ElementKeyInfo.SelectSingleNode("//ds:X509Data", namespaceId);

            if (X509Data == null)
            {
                return("ds:KeyInfo neobsahuje element ds:X509Data");
            }
            if (X509Data.ChildNodes.Count < 3)
            {
                return(" chýbajú podelementy pre ds:X509Data");
            }
            //check ds:KeyInfo values
            XmlNodeList elemList = X509Data.ChildNodes;

            byte[] bytes;
            var    cert = new X509Certificate2();
            String IssuerSerialFirst  = "";
            String IssuerSerialSecond = "";
            String SubjectName        = "";

            for (int i = 0; i < elemList.Count; i++)
            {
                switch (elemList[i].Name)
                {
                case "ds:X509Certificate":
                    bytes = Convert.FromBase64String(elemList[i].InnerText);
                    cert  = new X509Certificate2(bytes);
                    break;

                case "ds:X509IssuerSerial":
                    if (elemList[i].HasChildNodes)
                    {
                        IssuerSerialFirst  = elemList[i].FirstChild.InnerText;
                        IssuerSerialSecond = elemList[i].LastChild.InnerText;
                    }
                    break;

                case "ds:X509SubjectName":
                    SubjectName = elemList[i].InnerText;
                    break;
                }
            }
            BigInteger hex = BigInteger.Parse(cert.SerialNumber, NumberStyles.AllowHexSpecifier);

            if (!cert.Subject.Equals(SubjectName))
            {
                return("hodnota ds:X509SubjectName sa nezhoduje s príslušnou hodnotou v certifikáte");
            }
            if (!cert.Issuer.Equals(IssuerSerialFirst))
            {
                return("hodnota ds:X509IssuerName sa nezhoduje s príslušnou hodnotou v certifikáte");
            }
            if (!hex.ToString().Equals(IssuerSerialSecond))
            {
                return("hodnota ds:X509SerialNumber sa nezhoduje s príslušnou hodnotou v certifikáte");
            }



            //check ds:SignatureProperties Id
            if (ElementSignatureProperties.Attributes["Id"] == null)
            {
                return("element ds:SignatureProperties nema atribut Id");
            }
            //check ds:SignatureProperties numbers of elements
            XmlNodeList elemListSignatureProperties = ElementSignatureProperties.ChildNodes;

            if (elemListSignatureProperties.Count < 2)
            {
                return("ds:SignatureProperties neobsahuje dva elementy");
            }
            //check ds:SignatureProperties elements
            for (int i = 0; i < elemListSignatureProperties.Count; i++)
            {
                if (elemListSignatureProperties[i].FirstChild.Name.Equals("xzep:SignatureVersion") ||
                    elemListSignatureProperties[i].FirstChild.Name.Equals("xzep:ProductInfos"))
                {
                    String tmpTargetValue = elemListSignatureProperties[i].Attributes["Target"].Value;
                    tmpTargetValue = tmpTargetValue.Substring(1);
                    if (!tmpTargetValue.Equals(dsSignatureId.Value))
                    {
                        return("atribút Target v elemente ds:SignatureProperty nie je nastavený na element ds:Signature");
                    }
                }
            }



            //check Manifest and Manifest references
            String ManifestReferenceUri  = "";
            String algorithmDigestMethod = "";
            String algorithmTransforms   = "";
            String digestValue           = "";
            bool   flag1 = false;



            for (int i = 0; i < ElementManifest.Count; i++)
            {
                //check ds:Manifest Id
                if (ElementManifest[i].Attributes["Id"] == null)
                {
                    return("jeden z elementov ds:Manifest nemá atribút Id");
                }
                //check number of reference, ds:Object
                XmlNodeList ManifestChildNodes = ElementManifest[i].ChildNodes;
                if (ManifestChildNodes.Count > 1 || ManifestChildNodes.Count < 1)
                {
                    return("ds:Manifest neobsahuje práve jedenu referenciu");
                }
                if (!ManifestChildNodes[0].Attributes["Type"].Value.Contains("Object"))
                {
                    return("nezhoduje sa Type v ds:Manifest");
                }
                //check value attribute Type
                if (ManifestChildNodes[0].Attributes["Type"].Value.Equals("http://www.w3.org/2000/09/xmldsig#Object"))
                {
                    //check supported ds:Transforms and ds:DigestMethod
                    XmlNodeList ReferenceElementsChild = ManifestChildNodes[0].ChildNodes;
                    for (int l = 0; l < ReferenceElementsChild.Count; l++)
                    {
                        if (ReferenceElementsChild[l].Name.Equals("ds:Transforms"))
                        {
                            algorithmTransforms = ReferenceElementsChild[l].FirstChild.Attributes["Algorithm"].Value;
                            if (!SUPPORTED_TRANSFORMS.Contains(algorithmTransforms))
                            {
                                return("ds:Transforms neobsahuje podporovaný algoritmus pre daný element podľa profilu XAdES_ZEP");
                            }
                        }
                        if (ReferenceElementsChild[l].Name.Equals("ds:DigestMethod"))
                        {
                            algorithmDigestMethod = ReferenceElementsChild[l].Attributes["Algorithm"].Value;
                            if (!SUPPORTED_DIGEST_METHOD.Contains(algorithmDigestMethod))
                            {
                                return("ds:DigestMethod neobsahuje podporovaný algoritmus pre daný element podľa profilu XAdES_ZEP");
                            }
                        }
                        if (ReferenceElementsChild[l].Name.Equals("ds:DigestValue"))
                        {
                            digestValue = ReferenceElementsChild[l].InnerText;
                        }
                    }
                    ManifestReferenceUri = ManifestChildNodes[0].Attributes["URI"].Value;
                    ManifestReferenceUri = ManifestReferenceUri.Substring(1);

                    //check values ds:Manifest and ds:Object
                    XmlNodeList ObjectElement = xades.SelectNodes("//ds:Object", namespaceId);
                    for (int j = 0; j < ObjectElement.Count; j++)
                    {
                        if (ObjectElement[j].Attributes["Id"] == null)
                        {
                            continue;
                        }
                        if (ObjectElement[j].Attributes["Id"].Value.Equals(ManifestReferenceUri))
                        {
                            flag1 = true;

                            XmlDsigC14NTransform t     = new XmlDsigC14NTransform();
                            XmlDocument          myDoc = new XmlDocument();
                            myDoc.LoadXml(ObjectElement[i].OuterXml);
                            t.LoadInput(myDoc);
                            Stream s = (Stream)t.GetOutput(typeof(Stream));
                            byte[] hash;
                            string base64String = "";
                            switch (algorithmDigestMethod)
                            {
                            case "http://www.w3.org/2001/04/xmldsig#sha1":
                                SHA1 sha1 = SHA1.Create();
                                hash         = sha1.ComputeHash(s);
                                base64String = Convert.ToBase64String(hash);
                                break;

                            case "http://www.w3.org/2001/04/xmlenc#sha256":
                                SHA256 sha256 = SHA256.Create();
                                hash         = sha256.ComputeHash(s);
                                base64String = Convert.ToBase64String(hash);
                                break;

                            case "http://www.w3.org/2001/04/xmldsig-more#sha384":
                                SHA384 sha384 = SHA384.Create();
                                hash         = sha384.ComputeHash(s);
                                base64String = Convert.ToBase64String(hash);
                                break;

                            case "http://www.w3.org/2001/04/xmlenc#sha512":
                                SHA512 sha512 = SHA512.Create();
                                hash         = sha512.ComputeHash(s);
                                base64String = Convert.ToBase64String(hash);
                                break;
                            }
                            Console.WriteLine("-");
                            Console.WriteLine("Overenie hodnoty ds:DigestValue");
                            Console.WriteLine("First " + base64String);
                            Console.WriteLine("Second " + digestValue);
                            Console.WriteLine("-");
                        }
                    }
                    if (!flag1)
                    {
                        return("odkaz z ds:Manifest na ds:Object sa nezhoduje");
                    }
                    flag1 = false;
                }
                else
                {
                    return("ds:Reference, hodnota atribútu Type sa neoverila voči profilu XADES_ZEP");
                }
            }


            return("OK");
        }
 // Token: 0x06002379 RID: 9081 RVA: 0x0008151C File Offset: 0x0007F71C
 private static ulong Sigma_0(ulong x)
 {
     return(SHA384Managed.RotateRight(x, 28) ^ SHA384Managed.RotateRight(x, 34) ^ SHA384Managed.RotateRight(x, 39));
 }
예제 #36
0
 public static string Sha384(string str)
 {
     byte[] sha384Data = Encoding.UTF8.GetBytes(str);
     SHA384Managed sha384 = new SHA384Managed();
     byte[] result = sha384.ComputeHash(sha384Data);
     return Convert.ToBase64String(result); //返回长度为64字节的字符串
 }
예제 #37
0
        private static unsafe void SHATransform(ulong *expandedBuffer, ulong *state, byte *block)
        {
            ulong num1 = *state;
            ulong num2 = (ulong)*(long *)((IntPtr)state + 8);
            ulong num3 = state[2];
            ulong num4 = state[3];
            ulong num5 = state[4];
            ulong num6 = state[5];
            ulong num7 = state[6];
            ulong num8 = state[7];

            Utils.QuadWordFromBigEndian(expandedBuffer, 16, block);
            SHA384Managed.SHA384Expand(expandedBuffer);
            int index1;

            for (int index2 = 0; index2 < 80; index2 = index1 + 1)
            {
                ulong num9   = num8 + SHA384Managed.Sigma_1(num5) + SHA384Managed.Ch(num5, num6, num7) + SHA384Managed._K[index2] + expandedBuffer[index2];
                ulong num10  = num4 + num9;
                ulong num11  = num9 + SHA384Managed.Sigma_0(num1) + SHA384Managed.Maj(num1, num2, num3);
                int   index3 = index2 + 1;
                ulong num12  = num7 + SHA384Managed.Sigma_1(num10) + SHA384Managed.Ch(num10, num5, num6) + SHA384Managed._K[index3] + expandedBuffer[index3];
                ulong num13  = num3 + num12;
                ulong num14  = num12 + SHA384Managed.Sigma_0(num11) + SHA384Managed.Maj(num11, num1, num2);
                int   index4 = index3 + 1;
                ulong num15  = num6 + SHA384Managed.Sigma_1(num13) + SHA384Managed.Ch(num13, num10, num5) + SHA384Managed._K[index4] + expandedBuffer[index4];
                ulong num16  = num2 + num15;
                ulong num17  = num15 + SHA384Managed.Sigma_0(num14) + SHA384Managed.Maj(num14, num11, num1);
                int   index5 = index4 + 1;
                ulong num18  = num5 + SHA384Managed.Sigma_1(num16) + SHA384Managed.Ch(num16, num13, num10) + SHA384Managed._K[index5] + expandedBuffer[index5];
                ulong num19  = num1 + num18;
                ulong num20  = num18 + SHA384Managed.Sigma_0(num17) + SHA384Managed.Maj(num17, num14, num11);
                int   index6 = index5 + 1;
                ulong num21  = num10 + SHA384Managed.Sigma_1(num19) + SHA384Managed.Ch(num19, num16, num13) + SHA384Managed._K[index6] + expandedBuffer[index6];
                num8 = num11 + num21;
                num4 = num21 + SHA384Managed.Sigma_0(num20) + SHA384Managed.Maj(num20, num17, num14);
                int   index7 = index6 + 1;
                ulong num22  = num13 + SHA384Managed.Sigma_1(num8) + SHA384Managed.Ch(num8, num19, num16) + SHA384Managed._K[index7] + expandedBuffer[index7];
                num7 = num14 + num22;
                num3 = num22 + SHA384Managed.Sigma_0(num4) + SHA384Managed.Maj(num4, num20, num17);
                int   index8 = index7 + 1;
                ulong num23  = num16 + SHA384Managed.Sigma_1(num7) + SHA384Managed.Ch(num7, num8, num19) + SHA384Managed._K[index8] + expandedBuffer[index8];
                num6   = num17 + num23;
                num2   = num23 + SHA384Managed.Sigma_0(num3) + SHA384Managed.Maj(num3, num4, num20);
                index1 = index8 + 1;
                ulong num24 = num19 + SHA384Managed.Sigma_1(num6) + SHA384Managed.Ch(num6, num7, num8) + SHA384Managed._K[index1] + expandedBuffer[index1];
                num5 = num20 + num24;
                num1 = num24 + SHA384Managed.Sigma_0(num2) + SHA384Managed.Maj(num2, num3, num4);
            }
            ulong *numPtr = state;
            long   num25  = (long)*numPtr + (long)num1;

            *      numPtr = (ulong)num25;
            IntPtr num26  = (IntPtr)state + 8;
            long   num27  = *(long *)num26 + (long)num2;

            *(long *)num26 = num27;
            IntPtr num28 = (IntPtr)(state + 2);
            long   num29 = *(long *)num28 + (long)num3;

            *(long *)num28 = num29;
            IntPtr num30 = (IntPtr)(state + 3);
            long   num31 = *(long *)num30 + (long)num4;

            *(long *)num30 = num31;
            IntPtr num32 = (IntPtr)(state + 4);
            long   num33 = *(long *)num32 + (long)num5;

            *(long *)num32 = num33;
            IntPtr num34 = (IntPtr)(state + 5);
            long   num35 = *(long *)num34 + (long)num6;

            *(long *)num34 = num35;
            IntPtr num36 = (IntPtr)(state + 6);
            long   num37 = *(long *)num36 + (long)num7;

            *(long *)num36 = num37;
            IntPtr num38 = (IntPtr)(state + 7);
            long   num39 = *(long *)num38 + (long)num8;

            *(long *)num38 = num39;
        }