Inheritance: HashAlgorithm
Exemplo n.º 1
0
        /// <summary>
        /// Open file and get it's SHA1 hash
        /// </summary>
        /// <param name="file_name">File name (full path)</param>
        /// <returns>String representation of the SHA1 hash</returns>
        public static string GetSHAHashFromFile(string file_name, SHAType shaType)
        {
            System.IO.FileStream file = new System.IO.FileStream(file_name, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            byte[] retVal             = null;
            switch (shaType)
            {
            case SHAType.SHA1:
                System.Security.Cryptography.SHA1 sha1obj = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                retVal = sha1obj.ComputeHash(file);
                break;

            case SHAType.SHA256:
                System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create();
                retVal = sha256.ComputeHash(file);
                break;

            case SHAType.SHA384:
                System.Security.Cryptography.SHA384 sha384 = System.Security.Cryptography.SHA384.Create();
                retVal = sha384.ComputeHash(file);
                break;

            case SHAType.SHA512:
                System.Security.Cryptography.SHA512 sha512 = System.Security.Cryptography.SHA512.Create();
                retVal = sha512.ComputeHash(file);
                break;
            }
            file.Close();
            return(BitConverter.ToString(retVal).Replace("-", "").ToLower());
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initialize the encryptor
        /// </summary>
        public AESEncryptor()
        {
            aesProvider = new AesCryptoServiceProvider();
            aesProvider.KeySize = AESKeySize;

            sha384 = SHA384.Create();
        }
Exemplo n.º 3
0
 public static string Hash(string input)
 {
     System.Security.Cryptography.SHA384 sha384 = System.Security.Cryptography.SHA384.Create();
     // convert string to byte array
     byte[] input_bytes = ASCIIEncoding.ASCII.GetBytes(input);
     byte[] output      = sha384.ComputeHash(input_bytes);
     return(Base64.Encode(output));
 }
Exemplo n.º 4
0
 /// <summary>
 /// CheckSum384 method implementation
 /// </summary>
 public static byte[] CheckSum384(string value)
 {
     byte[] hash = null;
     using (System.Security.Cryptography.SHA384 sha384 = System.Security.Cryptography.SHA384Managed.Create())
     {
         hash = sha384.ComputeHash(Encoding.UTF8.GetBytes(value));
     }
     return(hash);
 }
Exemplo n.º 5
0
 /// <summary>
 /// CheckSum384 method implementation
 /// </summary>
 public static byte[] CheckSum384(byte[] value)
 {
     byte[] hash = null;
     using (System.Security.Cryptography.SHA384 sha384 = System.Security.Cryptography.SHA384Cng.Create())
     {
         hash = sha384.ComputeHash(value);
     }
     return(hash);
 }
Exemplo n.º 6
0
        public override string StringHashAlgorithm(string value)
        {
            System.Security.Cryptography.SHA384 sha = System.Security.Cryptography.SHA384.Create();
            byte[]        bytes = sha.ComputeHash(System.Text.ASCIIEncoding.UTF8.GetBytes(value));
            StringBuilder sb    = new StringBuilder();

            foreach (var b in bytes)
            {
                sb.Append(b.ToString("x2"));
            }
            return(sb.ToString());
        }
Exemplo n.º 7
0
        // sha384 below
        public static string GetSHA384Hash(string str)
        {
            System.Security.Cryptography.SHA384 sha384 = System.Security.Cryptography.SHA384.Create();
            byte[] bytes   = Encoding.Default.GetBytes(str);
            byte[] encoded = sha384.ComputeHash(bytes);

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < encoded.Length; i++)
            {
                sb.Append(encoded[i].ToString("x2"));
            }

            return(sb.ToString());
        }
Exemplo n.º 8
0
        /// <summary>
        /// Return SHA-384 (SHA-2) for a string.
        /// </summary>
        /// <param name="text">Source text to calculate hash from</param>
        /// <param name="encoding">Text encoding</param>
        /// <returns>SHA1 hash in hex format</returns>
        public static string SHA384(string text, Encoding encoding)
        {
            if (text == null)
            {
                return(null);
            }
#if !NETCF
            using (System.Security.Cryptography.SHA384 cipher = System.Security.Cryptography.SHA384.Create())
            {
                byte[] array = cipher.ComputeHash(encoding.GetBytes(text));
                return(Energy.Base.Hex.ArrayToHex(array).ToLower());
            }
#endif
#if NETCF
            return(null);
#endif
        }
        /// <summary>
        ///  验证面md5值是否先等
        /// </summary>
        /// <param name="md5Hash"></param>
        /// <param name="input"></param>
        /// <param name="hash"></param>
        /// <returns></returns>
        private static bool VerifySHA384Hash(SHA384 SHA1Hash, string input, string hash)
        {
            // Hash the input.
            string hashOfInput = GetSHA384Hash(SHA1Hash, input);

            // Create a StringComparer an compare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
Exemplo n.º 10
0
	public void FIPS186_Test1 (SHA384 hash) 
	{
		string className = hash.ToString ();
		byte[] result = { 0xcb, 0x00, 0x75, 0x3f, 0x45, 0xa3, 0x5e, 0x8b,
				  0xb5, 0xa0, 0x3d, 0x69, 0x9a, 0xc6, 0x50, 0x07,
				  0x27, 0x2c, 0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63,
				  0x1a, 0x8b, 0x60, 0x5a, 0x43, 0xff, 0x5b, 0xed,
				  0x80, 0x86, 0x07, 0x2b, 0xa1, 0xe7, 0xcc, 0x23,
				  0x58, 0xba, 0xec, 0xa1, 0x34, 0xc8, 0x25, 0xa7 };
		byte[] input = Encoding.Default.GetBytes (input1);
	
		string testName = className + " 1";
		FIPS186_a (testName, hash, input, result);
		FIPS186_b (testName, hash, input, result);
		FIPS186_c (testName, hash, input, result);
		FIPS186_d (testName, hash, input, result);
		FIPS186_e (testName, hash, input, result);
	}
Exemplo n.º 11
0
	public void FIPS186_Test2 (SHA384 hash) 
	{
		string className = hash.ToString ();
		byte[] result = { 0x09, 0x33, 0x0c, 0x33, 0xf7, 0x11, 0x47, 0xe8,
				  0x3d, 0x19, 0x2f, 0xc7, 0x82, 0xcd, 0x1b, 0x47,
				  0x53, 0x11, 0x1b, 0x17, 0x3b, 0x3b, 0x05, 0xd2,
				  0x2f, 0xa0, 0x80, 0x86, 0xe3, 0xb0, 0xf7, 0x12,
				  0xfc, 0xc7, 0xc7, 0x1a, 0x55, 0x7e, 0x2d, 0xb9,
				  0x66, 0xc3, 0xe9, 0xfa, 0x91, 0x74, 0x60, 0x39 };
		byte[] input = Encoding.Default.GetBytes (input2);
	
		string testName = className + " 2";
		FIPS186_a (testName, hash, input, result);
		FIPS186_b (testName, hash, input, result);
		FIPS186_c (testName, hash, input, result);
		FIPS186_d (testName, hash, input, result);
		FIPS186_e (testName, hash, input, result);
	}
        /// <summary>
        /// 获取md5值
        /// </summary>
        /// <param name="md5Hash"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        private static string GetSHA384Hash(SHA384 hash, string input)
        {

            // Convert the input string to a byte array and compute the hash.
            byte[] data = hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }
Exemplo n.º 13
0
	public void FIPS186_Test3 (SHA384 hash) 
	{
		string className = hash.ToString ();
		byte[] result = { 0x9d, 0x0e, 0x18, 0x09, 0x71, 0x64, 0x74, 0xcb,
				  0x08, 0x6e, 0x83, 0x4e, 0x31, 0x0a, 0x4a, 0x1c,
				  0xed, 0x14, 0x9e, 0x9c, 0x00, 0xf2, 0x48, 0x52,
				  0x79, 0x72, 0xce, 0xc5, 0x70, 0x4c, 0x2a, 0x5b,
				  0x07, 0xb8, 0xb3, 0xdc, 0x38, 0xec, 0xc4, 0xeb,
				  0xae, 0x97, 0xdd, 0xd8, 0x7f, 0x3d, 0x89, 0x85 };
		byte[] input = new byte [1000000];
		for (int i = 0; i < 1000000; i++)
			input[i] = 0x61; // a
	
		string testName = className + " 3";
		FIPS186_a (testName, hash, input, result);
		FIPS186_b (testName, hash, input, result);
		FIPS186_c (testName, hash, input, result);
		FIPS186_d (testName, hash, input, result);
		FIPS186_e (testName, hash, input, result);
	}
Exemplo n.º 14
0
        /// <summary>
        /// Get SHA1 hash from buffer of bytes
        /// </summary>
        /// <param name="input_buffer">Input buffer</param>
        /// <returns>16-byte array of hash</returns>
        public static byte[] GetSHAHash(byte[] input_buffer, SHAType shaType)
        {
            switch (shaType)
            {
            case SHAType.SHA1:
                SHA1 sha1 = new SHA1CryptoServiceProvider();
                return(sha1.ComputeHash(input_buffer));

            case SHAType.SHA256:
                System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create();
                return(sha256.ComputeHash(input_buffer));

            case SHAType.SHA384:
                System.Security.Cryptography.SHA384 sha384 = System.Security.Cryptography.SHA384.Create();
                return(sha384.ComputeHash(input_buffer));

            case SHAType.SHA512:
                System.Security.Cryptography.SHA512 sha512 = System.Security.Cryptography.SHA512.Create();
                return(sha512.ComputeHash(input_buffer));
            }
            return(null);
        }
Exemplo n.º 15
0
 public override byte[] ByteHashAlgorithm(string value)
 {
     System.Security.Cryptography.SHA384 sha = System.Security.Cryptography.SHA384.Create();
     byte[] bytes = sha.ComputeHash(System.Text.ASCIIEncoding.UTF8.GetBytes(value));
     return(bytes);
 }
Exemplo n.º 16
0
        private static unsafe void FillKeyDerivation(
            ReadOnlySpan <byte> password,
            ReadOnlySpan <byte> salt,
            int iterations,
            string hashAlgorithmName,
            Span <byte> destination)
        {
            SafeBCryptKeyHandle keyHandle;
            int hashBlockSizeBytes = GetHashBlockSize(hashAlgorithmName);

            // stackalloc 0 to let compiler know this cannot escape.
            Span <byte>         clearSpan            = stackalloc byte[0];
            ReadOnlySpan <byte> symmetricKeyMaterial = stackalloc byte[0];
            int symmetricKeyMaterialLength;

            if (password.IsEmpty)
            {
                // CNG won't accept a null pointer for the password.
                symmetricKeyMaterial       = stackalloc byte[1];
                symmetricKeyMaterialLength = 0;
                clearSpan = default;
            }
            else if (password.Length <= hashBlockSizeBytes)
            {
                // Password is small enough to use as-is.
                symmetricKeyMaterial       = password;
                symmetricKeyMaterialLength = password.Length;
                clearSpan = default;
            }
            else
            {
                // RFC 2104: "The key for HMAC can be of any length (keys longer than B bytes are
                //     first hashed using H).
                //     We denote by B the byte-length of such
                //     blocks (B=64 for all the above mentioned examples of hash functions)
                //
                // Windows' PBKDF2 will do this up to a point. To ensure we accept arbitrary inputs for
                // PBKDF2, we do the hashing ourselves.
                Span <byte> hashBuffer = stackalloc byte[512 / 8]; // 64 bytes is SHA512, the largest digest handled.
                int         hashBufferSize;

                switch (hashAlgorithmName)
                {
                case HashAlgorithmNames.SHA1:
                    hashBufferSize = SHA1.HashData(password, hashBuffer);
                    break;

                case HashAlgorithmNames.SHA256:
                    hashBufferSize = SHA256.HashData(password, hashBuffer);
                    break;

                case HashAlgorithmNames.SHA384:
                    hashBufferSize = SHA384.HashData(password, hashBuffer);
                    break;

                case HashAlgorithmNames.SHA512:
                    hashBufferSize = SHA512.HashData(password, hashBuffer);
                    break;

                default:
                    Debug.Fail($"Unexpected hash algorithm '{hashAlgorithmName}'");
                    throw new CryptographicException();
                }

                clearSpan                  = hashBuffer.Slice(0, hashBufferSize);
                symmetricKeyMaterial       = clearSpan;
                symmetricKeyMaterialLength = hashBufferSize;
            }

            Debug.Assert(symmetricKeyMaterial.Length > 0);

            NTSTATUS generateKeyStatus;

            if (Interop.BCrypt.PseudoHandlesSupported)
            {
                fixed(byte *pSymmetricKeyMaterial = symmetricKeyMaterial)
                {
                    generateKeyStatus = Interop.BCrypt.BCryptGenerateSymmetricKey(
                        (nuint)BCryptAlgPseudoHandle.BCRYPT_PBKDF2_ALG_HANDLE,
                        out keyHandle,
                        pbKeyObject: IntPtr.Zero,
                        cbKeyObject: 0,
                        pSymmetricKeyMaterial,
                        symmetricKeyMaterialLength,
                        dwFlags: 0);
                }
            }
            else
            {
                if (s_pbkdf2AlgorithmHandle is null)
                {
                    NTSTATUS openStatus = Interop.BCrypt.BCryptOpenAlgorithmProvider(
                        out SafeBCryptAlgorithmHandle pbkdf2AlgorithmHandle,
                        Internal.NativeCrypto.BCryptNative.AlgorithmName.Pbkdf2,
                        null,
                        BCryptOpenAlgorithmProviderFlags.None);

                    if (openStatus != NTSTATUS.STATUS_SUCCESS)
                    {
                        pbkdf2AlgorithmHandle.Dispose();
                        CryptographicOperations.ZeroMemory(clearSpan);
                        throw Interop.BCrypt.CreateCryptographicException(openStatus);
                    }

                    // This might race, and that's okay. Worst case the algorithm is opened
                    // more than once, and the ones that lost will get cleaned up during collection.
                    Interlocked.CompareExchange(ref s_pbkdf2AlgorithmHandle, pbkdf2AlgorithmHandle, null);
                }

                fixed(byte *pSymmetricKeyMaterial = symmetricKeyMaterial)
                {
                    generateKeyStatus = Interop.BCrypt.BCryptGenerateSymmetricKey(
                        s_pbkdf2AlgorithmHandle,
                        out keyHandle,
                        pbKeyObject: IntPtr.Zero,
                        cbKeyObject: 0,
                        pSymmetricKeyMaterial,
                        symmetricKeyMaterialLength,
                        dwFlags: 0);
                }
            }

            CryptographicOperations.ZeroMemory(clearSpan);

            if (generateKeyStatus != NTSTATUS.STATUS_SUCCESS)
            {
                keyHandle.Dispose();
                throw Interop.BCrypt.CreateCryptographicException(generateKeyStatus);
            }

            Debug.Assert(!keyHandle.IsInvalid);

            ulong kdfIterations = (ulong)iterations; // Previously asserted to be positive.

            using (keyHandle)
                fixed(char *pHashAlgorithmName = hashAlgorithmName)
                fixed(byte *pSalt        = salt)
                fixed(byte *pDestination = destination)
                {
                    Span <BCryptBuffer> buffers = stackalloc BCryptBuffer[3];

                    buffers[0].BufferType = CngBufferDescriptors.KDF_ITERATION_COUNT;
                    buffers[0].pvBuffer   = (IntPtr)(&kdfIterations);
                    buffers[0].cbBuffer   = sizeof(ulong);

                    buffers[1].BufferType = CngBufferDescriptors.KDF_SALT;
                    buffers[1].pvBuffer   = (IntPtr)pSalt;
                    buffers[1].cbBuffer   = salt.Length;

                    buffers[2].BufferType = CngBufferDescriptors.KDF_HASH_ALGORITHM;
                    buffers[2].pvBuffer   = (IntPtr)pHashAlgorithmName;

                    // C# spec: "A char* value produced by fixing a string instance always points to a null-terminated string"
                    buffers[2].cbBuffer = checked ((hashAlgorithmName.Length + 1) * sizeof(char)); // Add null terminator.

                    fixed(BCryptBuffer *pBuffers = buffers)
                    {
                        Interop.BCrypt.BCryptBufferDesc bufferDesc;
                        bufferDesc.ulVersion = Interop.BCrypt.BCRYPTBUFFER_VERSION;
                        bufferDesc.cBuffers  = buffers.Length;
                        bufferDesc.pBuffers  = (IntPtr)pBuffers;

                        NTSTATUS deriveStatus = Interop.BCrypt.BCryptKeyDerivation(
                            keyHandle,
                            &bufferDesc,
                            pDestination,
                            destination.Length,
                            out uint resultLength,
                            dwFlags: 0);

                        if (deriveStatus != NTSTATUS.STATUS_SUCCESS)
                        {
                            throw Interop.BCrypt.CreateCryptographicException(deriveStatus);
                        }

                        if (destination.Length != resultLength)
                        {
                            Debug.Fail("PBKDF2 resultLength != destination.Length");
                            throw new CryptographicException();
                        }
                    }
                }
        }
Exemplo n.º 17
0
 /// <summary>Creates an instance of the default implementation of <see cref="T:System.Security.Cryptography.SHA384" />.</summary>
 /// <returns>A new instance of <see cref="T:System.Security.Cryptography.SHA384" />.</returns>
 /// <exception cref="T:System.Reflection.TargetInvocationException">The algorithm was used with Federal Information Processing Standards (FIPS) mode enabled, but is not FIPS compatible.</exception>
 /// <PermissionSet>
 ///   <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode" />
 /// </PermissionSet>
 public new static SHA384 Create()
 {
     return(SHA384.Create("System.Security.Cryptography.SHA384"));
 }
Exemplo n.º 18
0
	public void FIPS186_e (string testName, SHA384 hash, byte[] input, byte[] result) 
	{
		byte[] copy = new byte [input.Length];
		for (int i=0; i < input.Length - 1; i++)
			hash.TransformBlock (input, i, 1, copy, i);
		byte[] output = hash.TransformFinalBlock (input, input.Length - 1, 1);
		// LAMESPEC or FIXME: TransformFinalBlock doesn't return HashValue !
		// AssertEquals (testName + ".e.1", result, output);
		Assert.IsNotNull (output, testName + ".e.1");
		Assert.AreEqual (result, hash.Hash, testName + ".e.2");
		// required or next operation will still return old hash
		hash.Initialize ();
	}
Exemplo n.º 19
0
	public void FIPS186_d (string testName, SHA384 hash, byte[] input, byte[] result) 
	{
		byte[] output = hash.TransformFinalBlock (input, 0, input.Length);
		// LAMESPEC or FIXME: TransformFinalBlock doesn't return HashValue !
		// AssertEquals( testName + ".d.1", result, output );
		Assert.IsNotNull (output, testName + ".d.1");
		Assert.AreEqual (result, hash.Hash, testName + ".d.2");
		// required or next operation will still return old hash
		hash.Initialize ();
	}
Exemplo n.º 20
0
	public void FIPS186_c (string testName, SHA384 hash, byte[] input, byte[] result) 
	{
		MemoryStream ms = new MemoryStream (input);
		byte[] output = hash.ComputeHash (ms); 
		Assert.AreEqual (result, output, testName + ".c.1");
		Assert.AreEqual (result, hash.Hash, testName + ".c.2");
		// required or next operation will still return old hash
		hash.Initialize ();
	}
Exemplo n.º 21
0
	public void FIPS186_b (string testName, SHA384 hash, byte[] input, byte[] result) 
	{
		byte[] output = hash.ComputeHash (input, 0, input.Length); 
		Assert.AreEqual (result, output, testName + ".b.1");
		Assert.AreEqual (result, hash.Hash, testName + ".b.2");
		// required or next operation will still return old hash
		hash.Initialize ();
	}
Exemplo n.º 22
0
 private static SHA384 GetHasher384() {
     if (_hasher384 == null) {
         _hasher384 = SHA384Managed.Create();
     }
     return _hasher384;
 }
Exemplo n.º 23
0
	public void FIPS186_a (string testName, SHA384 hash, byte[] input, byte[] result) 
	{
		byte[] output = hash.ComputeHash (input); 
		AssertEquals (testName + ".a.1", result, output);
		AssertEquals (testName + ".a.2", result, hash.Hash);
		// required or next operation will still return old hash
		hash.Initialize ();
	}