Esempio n. 1
0
        public void TestReusability(HashAlgorithm hashAlgorithm)
        {
            using (hashAlgorithm)
            {
                byte[] input = { 8, 6, 7, 5, 3, 0, 9, };
                byte[] hash1 = hashAlgorithm.ComputeHash(input);
                byte[] hash2 = hashAlgorithm.ComputeHash(input);

                Assert.Equal(hash1, hash2);
            }
        }
Esempio n. 2
0
    static void Test(HashAlgorithm digest)
    {
        byte[] result1, result2, result3;

        if (digest is SHA1) {
            Console.WriteLine ("Testing results wrt FIPS 180-1 test vectors");
            result1 = new byte [] { 0xa9, 0x99, 0x3e, 0x36, 0x47, 0x06, 0x81, 0x6a, 0xba, 0x3e,
                0x25, 0x71, 0x78, 0x50, 0xc2, 0x6c, 0x9c, 0xd0, 0xd8, 0x9d };
            result2 = new byte [] { 0x84, 0x98, 0x3e, 0x44, 0x1c, 0x3b, 0xd2, 0x6e, 0xba, 0xae,
                0x4a, 0xa1, 0xf9, 0x51, 0x29, 0xe5, 0xe5, 0x46, 0x70, 0xf1 };
            result3 = new byte [] { 0x34, 0xaa, 0x97, 0x3c, 0xd4, 0xc4, 0xda, 0xa4, 0xf6, 0x1e,
                0xeb, 0x2b, 0xdb, 0xad, 0x27, 0x31, 0x65, 0x34, 0x01, 0x6f };
        } else if (digest is SHA256) {
            Console.WriteLine ("Testing results wrt FIPS 180-2 test vectors");
            result1 = new byte [] { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,
                0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,
                0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
                0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad };
            result2 = new byte [] { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,
                0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,
                0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,
                0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 };
            result3 = new byte [] { 0xcd, 0xc7, 0x6e, 0x5c, 0x99, 0x14, 0xfb, 0x92,
                0x81, 0xa1, 0xc7, 0xe2, 0x84, 0xd7, 0x3e, 0x67,
                0xf1, 0x80, 0x9a, 0x48, 0xa4, 0x97, 0x20, 0x0e,
                0x04, 0x6d, 0x39, 0xcc, 0xc7, 0x11, 0x2c, 0xd0 };
        } else {
            Console.WriteLine ("No test vectors were found.");
            return;
        }
        string input1 = "abc";
        string input2 = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";

        byte[] input = Encoding.Default.GetBytes (input1);
        byte[] output = digest.ComputeHash (input);
        Console.WriteLine ("FIPS 180 Test 1: {0}",
            BitConverter.ToString (result1) != BitConverter.ToString (output) ?
            "FAIL" : "PASS");

        input = Encoding.Default.GetBytes (input2);
        output = digest.ComputeHash (input);
        Console.WriteLine ("FIPS 180 Test 2: {0}",
            BitConverter.ToString (result2) != BitConverter.ToString (output) ?
            "FAIL" : "PASS");

        input = new byte [1000000];
        for (int i = 0; i < 1000000; i++)
            input[i] = 0x61; // a
        output = digest.ComputeHash (input);
        Console.WriteLine ("FIPS 180 Test 3: {0}",
            BitConverter.ToString (result3) != BitConverter.ToString (output) ?
            "FAIL" : "PASS");
    }
Esempio n. 3
0
        private static void VerifyIncrementalResult(HashAlgorithm referenceAlgorithm, IncrementalHash incrementalHash)
        {
            byte[] referenceHash = referenceAlgorithm.ComputeHash(s_inputBytes);
            const int StepA = 13;
            const int StepB = 7;

            int position = 0;

            while (position < s_inputBytes.Length - StepA)
            {
                incrementalHash.AppendData(s_inputBytes, position, StepA);
                position += StepA;
            }

            incrementalHash.AppendData(s_inputBytes, position, s_inputBytes.Length - position);

            byte[] incrementalA = incrementalHash.GetHashAndReset();
            Assert.Equal(referenceHash, incrementalA);

            // Now try again, verifying both immune to step size behaviors, and that GetHashAndReset resets.
            position = 0;

            while (position < s_inputBytes.Length - StepB)
            {
                incrementalHash.AppendData(s_inputBytes, position, StepA);
                position += StepA;
            }

            incrementalHash.AppendData(s_inputBytes, position, s_inputBytes.Length - position);

            byte[] incrementalB = incrementalHash.GetHashAndReset();
            Assert.Equal(referenceHash, incrementalB);
        }
Esempio n. 4
0
        /// <summary>
        /// 从文件流获取Hash描述表
        /// </summary>
        /// <param name="objFile">源文件</param>
        /// <returns>Hash描述表</returns>
        public static string GetHashString(this FileStream objFile)
        {
            //从文件中取得Hash描述
            HashAlgorithm md5      = HashAlgorithm.Create("MD5");
            var           hashData = md5?.ComputeHash(objFile);

            return(Convert.ToBase64String(hashData));
        }
Esempio n. 5
0
        //获取Hash描述表
        /// <summary>
        /// 获取Hash描述表
        /// </summary>
        /// <param name="mStrSource">源数据</param>
        /// <returns>Hash描述表</returns>
        public static byte[] GetHashBytes(this string mStrSource)
        {
            //从字符串中取得Hash描述
            HashAlgorithm md5    = HashAlgorithm.Create("MD5");
            var           buffer = Encoding.UTF8.GetBytes(mStrSource);

            return(md5?.ComputeHash(buffer));
        }
Esempio n. 6
0
 //获取Hash描述表
 /// <summary>
 /// 从文件流获取Hash描述表
 /// </summary>
 /// <param name="objFile">源文件</param>
 /// <returns>Hash描述表</returns>
 public static byte[] GetHashBytes(this FileStream objFile)
 {
     //从文件中取得Hash描述
     using (objFile)
     {
         HashAlgorithm md5 = HashAlgorithm.Create("MD5");
         return(md5?.ComputeHash(objFile));
     }
 }
Esempio n. 7
0
 // prints the hash of a specified input to the console
 public static void PrintHash(string name, HashAlgorithm algo, byte[] data)
 {
     // compute the hash of the input data..
     byte[] hash = algo.ComputeHash(data);
     // ..and write the hash to the console
     Console.WriteLine(name + BytesToHex(hash));
     // dispose of the hash algorithm; we do not need to hash more data with it
     algo.Clear();
 }
Esempio n. 8
0
        //获取Hash描述表
        /// <summary>
        /// 获取Hash描述表
        /// </summary>
        /// <param name="mStrSource">源数据</param>
        /// <returns>Hash描述表</returns>
        public static string GetHashString(this string mStrSource)
        {
            //从字符串中取得Hash描述
            HashAlgorithm md5      = HashAlgorithm.Create("MD5");
            var           buffer   = Encoding.UTF8.GetBytes(mStrSource);
            var           hashData = md5?.ComputeHash(buffer);

            return(Convert.ToBase64String(hashData));
        }
        protected static void VerifySignature(AsymmetricSignatureFormatter formatter, AsymmetricSignatureDeformatter deformatter, HashAlgorithm hashAlgorithm, string hashAlgorithmName)
        {
            formatter.SetHashAlgorithm(hashAlgorithmName);
            deformatter.SetHashAlgorithm(hashAlgorithmName);

            byte[] hash = hashAlgorithm.ComputeHash(HelloBytes);

            VerifySignatureWithHashBytes(formatter, deformatter, hash);
            VerifySignatureWithHashAlgorithm(formatter, deformatter, hashAlgorithm);
        }
Esempio n. 10
0
    public static string GetHash(string input, HashAlgorithm hash)
    {
        byte[] data = hash.ComputeHash(Encoding.UTF8.GetBytes(input));

        StringBuilder sBuilder = new StringBuilder();
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }
        return sBuilder.ToString();
    }
Esempio n. 11
0
        public ARC4Crypt(HashAlgorithm hash, bool isServer)
        {
            Contract.Requires(hash != null);

            var encKey = isServer ? _serverEncClientDec : _serverDecClientEnc;
            var decKey = isServer ? _serverDecClientEnc : _serverEncClientDec;

            _encrypt = new ARC4Managed();
            _decrypt = new ARC4Managed();

            _encrypt.Key = hash.ComputeHash(encKey);
            _decrypt.Key = hash.ComputeHash(decKey);

            var buffer = new byte[DropN];
            var length = buffer.Length;

            // Drop the first N bytes in the stream, to prevent the FMS attack.
            _encrypt.TransformFinalBlock(buffer, 0, length);
            _decrypt.TransformFinalBlock(buffer, 0, length);
        }
Esempio n. 12
0
		private static byte[] GetEmptyHash (HashAlgorithm hash) 
		{
			if (hash is SHA1)
				return emptySHA1;
			else if (hash is SHA256)
				return emptySHA256;
			else if (hash is SHA384)
				return emptySHA384;
			else if (hash is SHA512)
				return emptySHA512;
			else
				return hash.ComputeHash ((byte[])null);
		}
Esempio n. 13
0
    public static string ComputeHash(string input, HashAlgorithm algorithm)
    {
        byte[] salt = Convert.FromBase64String(DEFAULT_SALT);
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);

        // Combine salt and input bytes
        byte[] saltedInput = new Byte[salt.Length + inputBytes.Length];
        salt.CopyTo(saltedInput, 0);
        inputBytes.CopyTo(saltedInput, salt.Length);

        byte[] hashedBytes = algorithm.ComputeHash(saltedInput);
        return Convert.ToBase64String(hashedBytes);
    }
Esempio n. 14
0
        private static byte[] ComputeHash(this HashAlgorithmEnum hashHashAlgo, byte[] input)
        {
            HashAlgorithm hashAlgorithm = null;

            switch (hashHashAlgo)
            {
            case HashAlgorithmEnum.Md5: hashAlgorithm = MD5.Create(); break;

            case HashAlgorithmEnum.Sha1: hashAlgorithm = SHA1.Create(); break;

            case HashAlgorithmEnum.Sha2256: hashAlgorithm = SHA256.Create(); break;

            case HashAlgorithmEnum.Sha2384: hashAlgorithm = SHA384.Create(); break;

            case HashAlgorithmEnum.Sha2512: hashAlgorithm = SHA512.Create(); break;
            }

            return(hashAlgorithm?.ComputeHash(input));
        }
Esempio n. 15
0
 /// <summary>
 /// 各哈希算法下的消息摘要算法
 /// </summary>
 /// <param name="text">原串</param>
 /// <param name="hash">哈希算法</param>
 /// <returns></returns>
 private static string Hash(string text, HashAlgorithm hash)
 {
     byte[] vs = hash.ComputeHash(Encoding.UTF8.GetBytes(text));
     return(BitConverter.ToString(vs).Replace("-", ""));
 }
Esempio n. 16
0
 private byte[] ComputeHash(byte[] data)
 {
     return(_hasher.ComputeHash(data));
 }
Esempio n. 17
0
 public string ComputeHash(string input, HashAlgorithm algorithm)
 {
     Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
     Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
     return BitConverter.ToString(hashedBytes);
 }
Esempio n. 18
0
        private bool CheckSignature(string fileName)
        {
            filename = fileName;
            Open(filename);
            entry = GetSecurityEntry();
            if (entry == null)
            {
                // no signature is present
                reason = 1;
                Close();
                return(false);
            }

            PKCS7.ContentInfo ci = new PKCS7.ContentInfo(entry);
            if (ci.ContentType != PKCS7.Oid.signedData)
            {
                Close();
                return(false);
            }

            PKCS7.SignedData sd = new PKCS7.SignedData(ci.Content);
            if (sd.ContentInfo.ContentType != spcIndirectDataContext)
            {
                Close();
                return(false);
            }

            coll = sd.Certificates;

            ASN1 spc = sd.ContentInfo.Content;

            signedHash = spc [0][1][1];

            HashAlgorithm ha = null;

            switch (signedHash.Length)
            {
            case 16:
                ha   = HashAlgorithm.Create("MD5");
                hash = GetHash(ha);
                break;

            case 20:
                ha   = HashAlgorithm.Create("SHA1");
                hash = GetHash(ha);
                break;

            default:
                reason = 5;
                Close();
                return(false);
            }
            Close();

            if (!signedHash.CompareValue(hash))
            {
                reason = 2;
            }

            // messageDigest is a hash of spcIndirectDataContext (which includes the file hash)
            byte[] spcIDC = spc [0].Value;
            ha.Initialize();              // re-using hash instance
            byte[] messageDigest = ha.ComputeHash(spcIDC);

            bool sign = VerifySignature(sd, messageDigest, ha);

            return(sign && (reason == 0));
        }
Esempio n. 19
0
        /// <summary>
        /// Decrypts data using the provided RSA key(s) to decrypt an AES key, which decrypts the cookie.
        /// </summary>
        /// <param name="encoded">The encoded data</param>
        /// <returns>The decoded data</returns>
        /// <exception cref="ArgumentNullException">The argument 'encoded' is null.</exception>
        /// <exception cref="ArgumentException">The argument 'encoded' contains zero bytes.</exception>
        /// <exception cref="NotSupportedException">The platform does not support the requested algorithm.</exception>
        /// <exception cref="InvalidOperationException">There are no decryption keys or none of the keys match.</exception>
        public override byte[] Decode(byte[] encoded)
        {
            if (null == encoded)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoded");
            }

            if (0 == encoded.Length)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("encoded", SR.GetString(SR.ID6045));
            }

            ReadOnlyCollection <RSA> decryptionKeys = DecryptionKeys;

            if (0 == decryptionKeys.Count)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID6039));
            }

            byte[] encryptedKeyAndIV;
            byte[] encryptedData;
            byte[] rsaHash;
            RSA    rsaDecryptionKey = null;

            using (HashAlgorithm hash = CryptoHelper.CreateHashAlgorithm(_hashName))
            {
                int hashSizeInBytes = hash.HashSize / 8;
                using (BinaryReader br = new BinaryReader(new MemoryStream(encoded)))
                {
                    rsaHash = br.ReadBytes(hashSizeInBytes);
                    int encryptedKeyAndIVSize = br.ReadInt32();
                    if (encryptedKeyAndIVSize < 0)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.ID1006, encryptedKeyAndIVSize)));
                    }
                    //
                    // Enforce upper limit on key size to prevent large buffer allocation in br.ReadBytes()
                    //

                    if (encryptedKeyAndIVSize > encoded.Length)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.ID1007)));
                    }
                    encryptedKeyAndIV = br.ReadBytes(encryptedKeyAndIVSize);

                    int encryptedDataSize = br.ReadInt32();
                    if (encryptedDataSize < 0)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.ID1008, encryptedDataSize)));
                    }
                    //
                    // Enforce upper limit on data size to prevent large buffer allocation in br.ReadBytes()
                    //
                    if (encryptedDataSize > encoded.Length)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.ID1009)));
                    }

                    encryptedData = br.ReadBytes(encryptedDataSize);
                }

                //
                // Find the decryption key matching the one in XML
                //
                foreach (RSA key in decryptionKeys)
                {
                    byte[] hashedKey = hash.ComputeHash(Encoding.UTF8.GetBytes(key.ToXmlString(false)));
                    if (CryptoHelper.IsEqual(hashedKey, rsaHash))
                    {
                        rsaDecryptionKey = key;
                        break;
                    }
                }
            }

            if (rsaDecryptionKey == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID6040));
            }

            byte[] decryptedKeyAndIV = CngLightup.OaepSha1Decrypt(rsaDecryptionKey, encryptedKeyAndIV);

            using (SymmetricAlgorithm symmetricAlgorithm = CryptoHelper.NewDefaultEncryption())
            {
                byte[] decryptionKey = new byte[symmetricAlgorithm.KeySize / 8];

                //
                // Ensure there is sufficient length in the descrypted key and IV buffer for an IV.
                //
                if (decryptedKeyAndIV.Length < decryptionKey.Length)
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID6047, decryptedKeyAndIV.Length, decryptionKey.Length));
                }

                byte[] decryptionIV = new byte[decryptedKeyAndIV.Length - decryptionKey.Length];

                //
                // Copy key into its own buffer.
                // The remaining bytes are the IV copy those into a buffer as well.
                //
                Array.Copy(decryptedKeyAndIV, decryptionKey, decryptionKey.Length);
                Array.Copy(decryptedKeyAndIV, decryptionKey.Length, decryptionIV, 0, decryptionIV.Length);

                using (ICryptoTransform decryptor = symmetricAlgorithm.CreateDecryptor(decryptionKey, decryptionIV))
                {
                    return(decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length));
                }
            }
        }
Esempio n. 20
0
        private static byte[] GetHash(string inputString)
        {
            HashAlgorithm algorithm = SHA256.Create();

            return(algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString)));
        }
Esempio n. 21
0
            internal override ImmutableArray<byte> ComputeHash(HashAlgorithm algorithm)
            {
                try
                {
                    using (var stream = _resource.DataProvider())
                    {
                        if (stream == null)
                        {
                            throw new InvalidOperationException(CodeAnalysisResources.ResourceDataProviderShouldReturnNonNullStream);
                        }

                        return ImmutableArray.CreateRange(algorithm.ComputeHash(stream));
                    }
                }
                catch (Exception ex)
                {
                    throw new ResourceException(_resource.FileName, ex);
                }
            }
Esempio n. 22
0
 public static string GetChecksum(string path)
 {
     using (FileStream fs = File.OpenRead(path))
         return(ChecksumHasher.ComputeHash(fs).ToHexadecimalString());
 }
Esempio n. 23
0
 public virtual byte[] GetDigestedOutput(HashAlgorithm hash) {
     return hash.ComputeHash((Stream) GetOutput(typeof(Stream)));
 }
        private void ProtocolV4(Stream stream, CertificateStore serverCredentials, Certificate[] trustedRootCertificates, ISecureChannelSecurityManager manager, string preSharedKey, SecureChannelCryptoOptionFlags supportedOptions)
        {
            #region 1. hello handshake

            //read client hello
            SecureChannelPacket.Hello clientHello = (new SecureChannelPacket(stream)).GetHello();

            //select crypto option
            _selectedCryptoOption = supportedOptions & clientHello.CryptoOptions;

            if (_selectedCryptoOption == SecureChannelCryptoOptionFlags.None)
            {
                throw new SecureChannelException(SecureChannelCode.NoMatchingCryptoAvailable, _remotePeerEP, _remotePeerCert);
            }
            else if ((_selectedCryptoOption & SecureChannelCryptoOptionFlags.ECDHE256_RSA_WITH_AES256_CBC_HMAC_SHA256) > 0)
            {
                _selectedCryptoOption = SecureChannelCryptoOptionFlags.ECDHE256_RSA_WITH_AES256_CBC_HMAC_SHA256;
            }
            else if ((_selectedCryptoOption & SecureChannelCryptoOptionFlags.DHE2048_RSA_WITH_AES256_CBC_HMAC_SHA256) > 0)
            {
                _selectedCryptoOption = SecureChannelCryptoOptionFlags.DHE2048_RSA_WITH_AES256_CBC_HMAC_SHA256;
            }
            else
            {
                throw new SecureChannelException(SecureChannelCode.NoMatchingCryptoAvailable, _remotePeerEP, _remotePeerCert);
            }

            //send server hello
            SecureChannelPacket.Hello serverHello = new SecureChannelPacket.Hello(BinaryID.GenerateRandomID256(), _selectedCryptoOption);
            SecureChannelPacket.WritePacket(stream, serverHello);

            #endregion

            #region 2. key exchange

            SymmetricEncryptionAlgorithm encAlgo;
            string       hashAlgo;
            KeyAgreement keyAgreement;

            switch (_selectedCryptoOption)
            {
            case SecureChannelCryptoOptionFlags.DHE2048_RSA_WITH_AES256_CBC_HMAC_SHA256:
                encAlgo      = SymmetricEncryptionAlgorithm.Rijndael;
                hashAlgo     = "SHA256";
                keyAgreement = new DiffieHellman(DiffieHellmanGroupType.RFC3526, 2048, KeyAgreementKeyDerivationFunction.Hmac, KeyAgreementKeyDerivationHashAlgorithm.SHA256);
                break;

            case SecureChannelCryptoOptionFlags.ECDHE256_RSA_WITH_AES256_CBC_HMAC_SHA256:
                encAlgo      = SymmetricEncryptionAlgorithm.Rijndael;
                hashAlgo     = "SHA256";
                keyAgreement = new TechnitiumLibrary.Security.Cryptography.ECDiffieHellman(256, KeyAgreementKeyDerivationFunction.Hmac, KeyAgreementKeyDerivationHashAlgorithm.SHA256);
                break;

            default:
                throw new SecureChannelException(SecureChannelCode.NoMatchingCryptoAvailable, _remotePeerEP, _remotePeerCert);
            }

            //send server key exchange data
            SecureChannelPacket.KeyExchange serverKeyExchange = new SecureChannelPacket.KeyExchange(keyAgreement.GetPublicKeyXML(), serverCredentials.PrivateKey, hashAlgo);
            SecureChannelPacket.WritePacket(stream, serverKeyExchange);

            //read client key exchange data
            SecureChannelPacket.KeyExchange clientKeyExchange = (new SecureChannelPacket(stream)).GetKeyExchange();

            //generate master key
            byte[] masterKey = GenerateMasterKey(clientHello, serverHello, _preSharedKey, keyAgreement, clientKeyExchange.PublicKeyXML);

            //verify master key using HMAC authentication
            {
                SecureChannelPacket.Authentication clientAuthentication = (new SecureChannelPacket(stream)).GetAuthentication();
                if (!clientAuthentication.IsValid(serverHello, masterKey))
                {
                    throw new SecureChannelException(SecureChannelCode.ProtocolAuthenticationFailed, _remotePeerEP, _remotePeerCert);
                }

                SecureChannelPacket.Authentication serverAuthentication = new SecureChannelPacket.Authentication(clientHello, masterKey);
                SecureChannelPacket.WritePacket(stream, serverAuthentication);
            }

            //enable channel encryption
            switch (encAlgo)
            {
            case SymmetricEncryptionAlgorithm.Rijndael:
                //using MD5 for generating AES IV of 128bit block size
                HashAlgorithm md5Hash = HashAlgorithm.Create("MD5");
                byte[]        eIV     = md5Hash.ComputeHash(serverHello.Nonce.ID);
                byte[]        dIV     = md5Hash.ComputeHash(clientHello.Nonce.ID);

                //create encryption and decryption objects
                SymmetricCryptoKey encryptionKey = new SymmetricCryptoKey(SymmetricEncryptionAlgorithm.Rijndael, masterKey, eIV, PaddingMode.None);
                SymmetricCryptoKey decryptionKey = new SymmetricCryptoKey(SymmetricEncryptionAlgorithm.Rijndael, masterKey, dIV, PaddingMode.None);

                //enable encryption
                EnableEncryption(stream, encryptionKey, decryptionKey, new HMACSHA256(masterKey), new HMACSHA256(masterKey));
                break;

            default:
                throw new SecureChannelException(SecureChannelCode.NoMatchingCryptoAvailable, _remotePeerEP, _remotePeerCert);
            }

            //channel encryption is ON!

            #endregion

            #region 3. exchange & verify certificates & signatures

            if (!_reNegotiating)
            {
                //read client certificate
                _remotePeerCert = (new SecureChannelPacket(this)).GetCertificate();

                //verify client certificate
                try
                {
                    _remotePeerCert.Verify(trustedRootCertificates);
                }
                catch (Exception ex)
                {
                    throw new SecureChannelException(SecureChannelCode.InvalidRemoteCertificate, _remotePeerEP, _remotePeerCert, "Invalid remote certificate.", ex);
                }
            }

            //verify key exchange signature
            switch (_selectedCryptoOption)
            {
            case SecureChannelCryptoOptionFlags.DHE2048_RSA_WITH_AES256_CBC_HMAC_SHA256:
            case SecureChannelCryptoOptionFlags.ECDHE256_RSA_WITH_AES256_CBC_HMAC_SHA256:
                if (_remotePeerCert.PublicKeyEncryptionAlgorithm != AsymmetricEncryptionAlgorithm.RSA)
                {
                    throw new SecureChannelException(SecureChannelCode.InvalidRemoteCertificateAlgorithm, _remotePeerEP, _remotePeerCert);
                }

                if (!clientKeyExchange.IsSignatureValid(_remotePeerCert, "SHA256"))
                {
                    throw new SecureChannelException(SecureChannelCode.InvalidRemoteKeyExchangeSignature, _remotePeerEP, _remotePeerCert);
                }

                break;

            default:
                throw new SecureChannelException(SecureChannelCode.NoMatchingCryptoAvailable, _remotePeerEP, _remotePeerCert);
            }

            if ((manager != null) && !manager.ProceedConnection(_remotePeerCert))
            {
                throw new SecureChannelException(SecureChannelCode.SecurityManagerDeclinedAccess, _remotePeerEP, _remotePeerCert, "Security manager declined access.");
            }

            //send server certificate
            if (!_reNegotiating)
            {
                SecureChannelPacket.WritePacket(this, serverCredentials.Certificate);
            }

            #endregion
        }
Esempio n. 25
0
        /// <summary>
        /// Unix-like Crypt-MD5 function
        /// </summary>
        /// <param name="password">The user password</param>
        /// <param name="salt">The salt or the pepper of the password</param>
        /// <returns>a human readable string</returns>
        public static String crypt(String password, String salt)
        {
            int saltEnd;
            int len;
            int value;
            int i;

            byte[] final;
            byte[] passwordBytes;
            byte[] saltBytes;
            byte[] ctx;

            StringBuilder result;
            HashAlgorithm x_hash_alg = HashAlgorithm.Create("MD5");

            // Skip magic if it exists
            if (salt.StartsWith(magic))
            {
                salt = salt.Substring(magic.Length);
            }

            // Remove password hash if present
            if ((saltEnd = salt.LastIndexOf('$')) != -1)
            {
                salt = salt.Substring(0, saltEnd);
            }

            // Shorten salt to 8 characters if it is longer
            if (salt.Length > 8)
            {
                salt = salt.Substring(0, 8);
            }

            ctx   = Encoding.ASCII.GetBytes(password + magic + salt);
            final = x_hash_alg.ComputeHash(Encoding.ASCII.GetBytes(password + salt + password));

            // Add as many characters of ctx1 to ctx
            for (len = password.Length; len > 0; len -= 16)
            {
                if (len > 16)
                {
                    ctx = Concat(ctx, final);
                }
                else
                {
                    ctx = Concat(ctx, final, len);
                }
            }

            // Then something really weird...
            passwordBytes = Encoding.ASCII.GetBytes(password);

            for (i = password.Length; i > 0; i >>= 1)
            {
                if ((i & 1) == 1)
                {
                    ctx = Concat(ctx, new byte[] { 0 });
                }
                else
                {
                    ctx = Concat(ctx, new byte[] { passwordBytes[0] });
                }
            }

            final = x_hash_alg.ComputeHash(ctx);

            // Do additional mutations
            saltBytes = Encoding.ASCII.GetBytes(salt);
            for (i = 0; i < 1000; i++)
            {
                var ctx1 = new byte[] { };
                if ((i & 1) == 1)
                {
                    ctx1 = Concat(ctx1, passwordBytes);
                }
                else
                {
                    ctx1 = Concat(ctx1, final);
                }
                if (i % 3 != 0)
                {
                    ctx1 = Concat(ctx1, saltBytes);
                }
                if (i % 7 != 0)
                {
                    ctx1 = Concat(ctx1, passwordBytes);
                }
                if ((i & 1) != 0)
                {
                    ctx1 = Concat(ctx1, final);
                }
                else
                {
                    ctx1 = Concat(ctx1, passwordBytes);
                }
                final = x_hash_alg.ComputeHash(ctx1);
            }

            result = new StringBuilder();
            // Add the password hash to the result string
            value = ((final[0] & 0xff) << 16) | ((final[6] & 0xff) << 8)
                    | (final[12] & 0xff);
            result.Append(to64(value, 4));
            value = ((final[1] & 0xff) << 16) | ((final[7] & 0xff) << 8)
                    | (final[13] & 0xff);
            result.Append(to64(value, 4));
            value = ((final[2] & 0xff) << 16) | ((final[8] & 0xff) << 8)
                    | (final[14] & 0xff);
            result.Append(to64(value, 4));
            value = ((final[3] & 0xff) << 16) | ((final[9] & 0xff) << 8)
                    | (final[15] & 0xff);
            result.Append(to64(value, 4));
            value = ((final[4] & 0xff) << 16) | ((final[10] & 0xff) << 8)
                    | (final[5] & 0xff);
            result.Append(to64(value, 4));
            value = final[11] & 0xff;
            result.Append(to64(value, 2));

            // Return result string
            return(magic + salt + "$" + result);
        }
Esempio n. 26
0
        private string CalculateVer(DiscoNode n)
        {
            if (m_hash == null)
                return null;

            // 1. Initialize an empty string S.
            StringBuilder S = new StringBuilder();

            // 2. Sort the service discovery identities [16] by category and then by type
            // (if it exists) and then by xml:lang (if it exists), formatted as
            // CATEGORY '/' [TYPE] '/' [LANG] '/' [NAME]. Note that each slash is
            // included even if the TYPE, LANG, or NAME is not included.
            Ident[] ids = n.GetIdentities();
            Array.Sort(ids);

            // 3. For each identity, append the 'category/type/lang/name' to S, followed by
            // the '<' character.
            foreach (Ident id in ids)
            {
                S.Append(id.Key);
                S.Append(SEP);
            }

            // 4. Sort the supported service discovery features.
            string[] features = n.FeatureNames;
            Array.Sort(features);

            // 5. For each feature, append the feature to S, followed by the '<' character.
            foreach (string feature in features)
            {
                S.Append(feature);
                S.Append(SEP);
            }

            // 6. If the service discovery information response includes XEP-0128 data forms, 
            // sort the forms by the FORM_TYPE (i.e., by the XML character 
            // data of the <value/> element).
            Data[] ext = n.Extensions;
            if (ext != null)
            {
                Array.Sort(ext, new FormTypeComparer());
                foreach (Data x in ext)  
                {
                    // For each extended service discovery information form:

                    // 1. Append the XML character data of the FORM_TYPE field's <value/> 
                    // element, followed by the '<' character.
                    S.Append(x.FormType);
                    S.Append(SEP);

                    // 2. Sort the fields by the value of the "var" attribute.
                    bedrock.collections.Tree fields = new bedrock.collections.Tree();
                    foreach (Field f in x.GetFields())
                        fields[f.Var] = f;

                    // 3. For each field:
                    foreach (System.Collections.DictionaryEntry entry in fields)
                    {
                        Field f = (Field)entry.Value;
                        if (f.Var == "FORM_TYPE")
                            continue;

                        // 1. Append the value of the "var" attribute, followed by the '<' character.
                        S.Append(f.Var);
                        S.Append(SEP);

                        // 2. Sort values by the XML character data of the <value/> element.
                        string[] values = f.Vals;
                        Array.Sort(values);
                        foreach (string v in values)
                        {
                            // 3. For each <value/> element, append the XML character data, followed by the '<' character.
                            S.Append(v);
                            S.Append(SEP);
                        }
                    }
                }
            }

            // Ensure that S is encoded according to the UTF-8 encoding (RFC 3269 [16]).
            byte[] input = Encoding.UTF8.GetBytes(S.ToString());

            // Compute the verification string by hashing S using the algorithm specified
            // in the 'hash' attribute (e.g., SHA-1 as defined in RFC 3174 [17]). The hashed
            // data MUST be generated with binary output and encoded using Base64 as specified
            // in Section 4 of RFC 4648 [18] (note: the Base64 output MUST NOT include
            // whitespace and MUST set padding bits to zero). [19]
            HashAlgorithm hasher = GetHasher(m_hash);
            byte[] hash = hasher.ComputeHash(input, 0, input.Length);
            return Convert.ToBase64String(hash);
        }
Esempio n. 27
0
        private bool VerifyCounterSignature(PKCS7.SignerInfo cs, byte[] signature)
        {
            // SEQUENCE {
            //   INTEGER 1
            if (cs.Version != 1)
            {
                return(false);
            }
            //   SEQUENCE {
            //      SEQUENCE {

            string contentType   = null;
            ASN1   messageDigest = null;

            for (int i = 0; i < cs.AuthenticatedAttributes.Count; i++)
            {
                // SEQUENCE {
                //   OBJECT IDENTIFIER
                ASN1   attr = (ASN1)cs.AuthenticatedAttributes [i];
                string oid  = ASN1Convert.ToOid(attr[0]);
                switch (oid)
                {
                case "1.2.840.113549.1.9.3":
                    // contentType
                    contentType = ASN1Convert.ToOid(attr[1][0]);
                    break;

                case "1.2.840.113549.1.9.4":
                    // messageDigest
                    messageDigest = attr[1][0];
                    break;

                case "1.2.840.113549.1.9.5":
                    // SEQUENCE {
                    //   OBJECT IDENTIFIER
                    //     signingTime (1 2 840 113549 1 9 5)
                    //   SET {
                    //     UTCTime '030124013651Z'
                    //   }
                    // }
                    timestamp = ASN1Convert.ToDateTime(attr[1][0]);
                    break;

                default:
                    break;
                }
            }

            if (contentType != PKCS7.Oid.data)
            {
                return(false);
            }

            // verify message digest
            if (messageDigest == null)
            {
                return(false);
            }
            // TODO: must be read from the ASN.1 structure
            string hashName = null;

            switch (messageDigest.Length)
            {
            case 16:
                hashName = "MD5";
                break;

            case 20:
                hashName = "SHA1";
                break;
            }
            HashAlgorithm ha = HashAlgorithm.Create(hashName);

            if (!messageDigest.CompareValue(ha.ComputeHash(signature)))
            {
                return(false);
            }

            // verify signature
            byte[] counterSignature = cs.Signature;

            // change to SET OF (not [0]) as per PKCS #7 1.5
            ASN1 aa = new ASN1(0x31);

            foreach (ASN1 a in cs.AuthenticatedAttributes)
            {
                aa.Add(a);
            }
            byte[] p7hash = ha.ComputeHash(aa.GetBytes());

            // we need to try all certificates
            string issuer = cs.IssuerName;

            byte[] serial = cs.SerialNumber;
            foreach (X509Certificate x509 in coll)
            {
                if (CompareIssuerSerial(issuer, serial, x509))
                {
                    if (x509.PublicKey.Length > counterSignature.Length)
                    {
                        RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.RSA;
                        // we need to HACK around bad (PKCS#1 1.5) signatures made by Verisign Timestamp Service
                        // and this means copying stuff into our own RSAManaged to get the required flexibility
                        RSAManaged rsam = new RSAManaged();
                        rsam.ImportParameters(rsa.ExportParameters(false));
                        if (PKCS1.Verify_v15(rsam, ha, p7hash, counterSignature, true))
                        {
                            timestampChain.LoadCertificates(coll);
                            return(timestampChain.Build(x509));
                        }
                    }
                }
            }
            // no certificate can verify this signature!
            return(false);
        }
Esempio n. 28
0
        //private bool VerifySignature (ASN1 cs, byte[] calculatedMessageDigest, string hashName)
        private bool VerifySignature(PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha)
        {
            string contentType   = null;
            ASN1   messageDigest = null;

//			string spcStatementType = null;
//			string spcSpOpusInfo = null;

            for (int i = 0; i < sd.SignerInfo.AuthenticatedAttributes.Count; i++)
            {
                ASN1   attr = (ASN1)sd.SignerInfo.AuthenticatedAttributes [i];
                string oid  = ASN1Convert.ToOid(attr[0]);
                switch (oid)
                {
                case "1.2.840.113549.1.9.3":
                    // contentType
                    contentType = ASN1Convert.ToOid(attr[1][0]);
                    break;

                case "1.2.840.113549.1.9.4":
                    // messageDigest
                    messageDigest = attr[1][0];
                    break;

                case "1.3.6.1.4.1.311.2.1.11":
                    // spcStatementType (Microsoft code signing)
                    // possible values
                    // - individualCodeSigning (1 3 6 1 4 1 311 2 1 21)
                    // - commercialCodeSigning (1 3 6 1 4 1 311 2 1 22)
//						spcStatementType = ASN1Convert.ToOid (attr[1][0][0]);
                    break;

                case "1.3.6.1.4.1.311.2.1.12":
                    // spcSpOpusInfo (Microsoft code signing)

/*						try {
 *                                                      spcSpOpusInfo = System.Text.Encoding.UTF8.GetString (attr[1][0][0][0].Value);
 *                                              }
 *                                              catch (NullReferenceException) {
 *                                                      spcSpOpusInfo = null;
 *                                              }*/
                    break;

                default:
                    break;
                }
            }
            if (contentType != spcIndirectDataContext)
            {
                return(false);
            }

            // verify message digest
            if (messageDigest == null)
            {
                return(false);
            }
            if (!messageDigest.CompareValue(calculatedMessageDigest))
            {
                return(false);
            }

            // verify signature
            string hashOID = CryptoConfig.MapNameToOID(ha.ToString());

            // change to SET OF (not [0]) as per PKCS #7 1.5
            ASN1 aa = new ASN1(0x31);

            foreach (ASN1 a in sd.SignerInfo.AuthenticatedAttributes)
            {
                aa.Add(a);
            }
            ha.Initialize();
            byte[] p7hash = ha.ComputeHash(aa.GetBytes());

            byte[] signature = sd.SignerInfo.Signature;
            // we need to find the specified certificate
            string issuer = sd.SignerInfo.IssuerName;

            byte[] serial = sd.SignerInfo.SerialNumber;
            foreach (X509Certificate x509 in coll)
            {
                if (CompareIssuerSerial(issuer, serial, x509))
                {
                    // don't verify is key size don't match
                    if (x509.PublicKey.Length > (signature.Length >> 3))
                    {
                        // return the signing certificate even if the signature isn't correct
                        // (required behaviour for 2.0 support)
                        signingCertificate = x509;
                        RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.RSA;
                        if (rsa.VerifyHash(p7hash, hashOID, signature))
                        {
                            signerChain.LoadCertificates(coll);
                            trustedRoot = signerChain.Build(x509);
                            break;
                        }
                    }
                }
            }

            // timestamp signature is optional
            if (sd.SignerInfo.UnauthenticatedAttributes.Count == 0)
            {
                trustedTimestampRoot = true;
            }
            else
            {
                for (int i = 0; i < sd.SignerInfo.UnauthenticatedAttributes.Count; i++)
                {
                    ASN1   attr = (ASN1)sd.SignerInfo.UnauthenticatedAttributes[i];
                    string oid  = ASN1Convert.ToOid(attr[0]);
                    switch (oid)
                    {
                    case PKCS7.Oid.countersignature:
                        // SEQUENCE {
                        //   OBJECT IDENTIFIER
                        //     countersignature (1 2 840 113549 1 9 6)
                        //   SET {
                        PKCS7.SignerInfo cs = new PKCS7.SignerInfo(attr[1]);
                        trustedTimestampRoot = VerifyCounterSignature(cs, signature);
                        break;

                    default:
                        // we don't support other unauthenticated attributes
                        break;
                    }
                }
            }

            return(trustedRoot && trustedTimestampRoot);
        }
Esempio n. 29
0
 public static byte[] ComputeHash(this byte[] data)
 {
     return(hashProvider.ComputeHash(data));
 }
Esempio n. 30
0
 /// <summary>
 /// 加密方法
 /// </summary>
 /// <param name="Source">待加密的串</param>
 /// <returns>经过加密的串</returns>
 public string Encrypto(string Source)
 {
     byte[] bytIn  = UTF8Encoding.UTF8.GetBytes(Source);
     byte[] bytOut = HashCryptoService.ComputeHash(bytIn);
     return(Convert.ToBase64String(bytOut));
 }
Esempio n. 31
0
 public static string StringToHash(this string data, string salt, HashAlgorithm algorithm)
 {
     byte[] saltedBytes = Encoding.UTF8.GetBytes(data + salt);     // Combine the data with the salt
     byte[] hashedBytes = algorithm.ComputeHash(saltedBytes);      // Compute the hash value of our input
     return(BitConverter.ToString(hashedBytes));
 }
Esempio n. 32
0
	public static bool ExerciseHash(HashAlgorithm hash, int size)
	{
		// Exercise the properties
		//
		if (hash.CanReuseTransform != true)
		{
			Console.WriteLine("CanReuseTransform != true");
			return false;
		}

		if (hash.CanTransformMultipleBlocks != true)
		{
			Console.WriteLine("CanTransformMultipleBlocks != true");
			return false;
		}

		if (hash.HashSize != size)
		{
			Console.WriteLine("HashSize, expected={0} actual={1}", size, hash.HashSize);
			return false;
		}

		if (hash.InputBlockSize != 1)
		{
			Console.WriteLine("InputBlockSize != 1");
			return false;
		}

		if (hash.OutputBlockSize != 1)
		{
			Console.WriteLine("OutputBlockSize != 1");
			return false;
		}

		// Exercise the Initialize method.  Test proper behavior both when it is and is not called.
		//
		byte[] bytesHalf1 = {0x00, 0x01, 0x02, 0x03};
		byte[] bytesHalf2 = {0xfc, 0xfd, 0xfe, 0xff};
		byte[] bytesFull  = {0x00, 0x01, 0x02, 0x03, 0xfc, 0xfd, 0xfe, 0xff};
		byte[] bytesExpected;
		byte[] bytesActual;

		// Initialize is called between partial hashes
		//
		hash.Initialize();
		bytesExpected = hash.ComputeHash(bytesHalf1);
		
		hash.Initialize();
		hash.TransformBlock(bytesHalf2, 0, bytesHalf2.Length, bytesHalf2, 0);
		hash.Initialize();
		hash.TransformFinalBlock(bytesHalf1, 0, bytesHalf1.Length);
		bytesActual = hash.Hash;

		if (!CompareBytes(bytesExpected, bytesActual))
		{
			Console.WriteLine("\nInitialize test failed");
			return false;
		}

		// Initialize is not called between partial hashes
		//
		hash.Initialize();
		bytesExpected = hash.ComputeHash(bytesFull);

		hash.Initialize();
		hash.TransformBlock(bytesHalf1, 0, bytesHalf1.Length, bytesHalf1, 0);
		hash.TransformFinalBlock(bytesHalf2, 0, bytesHalf2.Length);
		bytesActual = hash.Hash;
		
		if (!CompareBytes(bytesExpected, bytesActual))
		{
			Console.WriteLine("\nNo Initialize test failed");
			return false;
		}

		// Exercise the Clear method -- ensure object disposed
		//
		hash.Initialize();
		hash.Clear();

		try
		{
			hash.ComputeHash(bytesFull);
			Console.WriteLine("Clear test failed -- no exception thrown");
			return false;
		}
		catch (ObjectDisposedException)
		{
		}
		
		return true;
	}
Esempio n. 33
0
 private static string Hash(HashAlgorithm alg, string input) =>
 BitConverter.ToString(alg.ComputeHash(Encoding.UTF8.GetBytes(input))).ToLower().Replace("-", "");
Esempio n. 34
0
        /// <summary>
        /// Encode the data.  The data is encrypted using the default encryption algorithm (AES-256),
        /// then the AES key is encrypted using RSA and the RSA public key is appended.
        /// </summary>
        /// <param name="value">The data to encode</param>
        /// <exception cref="ArgumentNullException">The argument 'value' is null.</exception>
        /// <exception cref="ArgumentException">The argument 'value' contains zero bytes.</exception>
        /// <exception cref="InvalidOperationException">The EncryptionKey is null.</exception>
        /// <returns>Encoded data</returns>
        public override byte[] Encode(byte[] value)
        {
            if (null == value)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
            }

            if (0 == value.Length)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.ID6044));
            }

            RSA encryptionKey = EncryptionKey;

            if (null == encryptionKey)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID6043));
            }

            byte[] rsaHash;
            byte[] encryptedKeyAndIV;
            byte[] encryptedData;

            using (HashAlgorithm hash = CryptoHelper.CreateHashAlgorithm(_hashName))
            {
                rsaHash = hash.ComputeHash(Encoding.UTF8.GetBytes(encryptionKey.ToXmlString(false)));
            }

            using (SymmetricAlgorithm encryptionAlgorithm = CryptoHelper.NewDefaultEncryption())
            {
                encryptionAlgorithm.GenerateIV();
                encryptionAlgorithm.GenerateKey();

                using (ICryptoTransform encryptor = encryptionAlgorithm.CreateEncryptor())
                {
                    encryptedData = encryptor.TransformFinalBlock(value, 0, value.Length);
                }

                RSACryptoServiceProvider provider = encryptionKey as RSACryptoServiceProvider;

                if (provider == null)
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID6041));
                }

                //
                // Concatenate the Key and IV in an attempt to avoid two minimum block lengths in the cookie
                //
                byte[] keyAndIV = new byte[encryptionAlgorithm.Key.Length + encryptionAlgorithm.IV.Length];
                Array.Copy(encryptionAlgorithm.Key, keyAndIV, encryptionAlgorithm.Key.Length);
                Array.Copy(encryptionAlgorithm.IV, 0, keyAndIV, encryptionAlgorithm.Key.Length, encryptionAlgorithm.IV.Length);

                encryptedKeyAndIV = CngLightup.OaepSha1Encrypt(encryptionKey, keyAndIV);
            }

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write(rsaHash);
                    bw.Write(encryptedKeyAndIV.Length);
                    bw.Write(encryptedKeyAndIV);
                    bw.Write(encryptedData.Length);
                    bw.Write(encryptedData);
                    bw.Flush();
                }

                return(ms.ToArray());
            }
        }
Esempio n. 35
0
		public byte[] method_10(byte[] byte_2, HashAlgorithm hashAlgorithm_0)
		{
			Class1.Class13.Enum1 enum1_ = this.method_16(hashAlgorithm_0);
			byte[] byte_3 = hashAlgorithm_0.ComputeHash(byte_2);
			return this.method_7(byte_3, enum1_);
		}
Esempio n. 36
0
 public static byte[] GetHash(this string inputString)
 {
     using (HashAlgorithm algorithm = SHA256.Create())
         return(algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString)));
 }
Esempio n. 37
0
		public virtual byte[] GetDigestedOutput (HashAlgorithm hash)
		{
			// no null check, MS throws a NullReferenceException here
			return hash.ComputeHash ((Stream) GetOutput (typeof (Stream)));
		}
Esempio n. 38
0
        public static void VerifyEmptyHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm)
        {
            using (referenceAlgorithm)
            using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm))
            {
                for (int i = 0; i < 10; i++)
                {
                    incrementalHash.AppendData(Array.Empty<byte>());
                }

                byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>());
                byte[] incrementalResult = incrementalHash.GetHashAndReset();

                Assert.Equal(referenceHash, incrementalResult);
            }
        }
Esempio n. 39
0
		// PKCS #1 v.2.1, Section B.2.1
		public static byte[] MGF1 (HashAlgorithm hash, byte[] mgfSeed, int maskLen) 
		{
			// 1. If maskLen > 2^32 hLen, output "mask too long" and stop.
			// easy - this is impossible by using a int (31bits) as parameter ;-)
			// BUT with a signed int we do have to check for negative values!
			if (maskLen < 0)
				throw new OverflowException();
	
			int mgfSeedLength = mgfSeed.Length;
			int hLen = (hash.HashSize >> 3); // from bits to bytes
			int iterations = (maskLen / hLen);
			if (maskLen % hLen != 0)
				iterations++;
			// 2. Let T be the empty octet string.
			byte[] T = new byte [iterations * hLen];
	
			byte[] toBeHashed = new byte [mgfSeedLength + 4];
			int pos = 0;
			// 3. For counter from 0 to \ceil (maskLen / hLen) - 1, do the following:
			for (int counter = 0; counter < iterations; counter++) {
				// a.	Convert counter to an octet string C of length 4 octets
				byte[] C = I2OSP (counter, 4); 
	
				// b.	Concatenate the hash of the seed mgfSeed and C to the octet string T:
				//	T = T || Hash (mgfSeed || C)
				Buffer.BlockCopy (mgfSeed, 0, toBeHashed, 0, mgfSeedLength);
				Buffer.BlockCopy (C, 0, toBeHashed, mgfSeedLength, 4);
				byte[] output = hash.ComputeHash (toBeHashed);
				Buffer.BlockCopy (output, 0, T, pos, hLen);
				pos += hLen;
			}
			
			// 4. Output the leading maskLen octets of T as the octet string mask.
			byte[] mask = new byte [maskLen];
			Buffer.BlockCopy (T, 0, mask, 0, maskLen);
			return mask;
		}
	// Run a hash algorithm test.
	protected void RunHash(HashAlgorithm alg, String value, byte[] expected)
			{
				// Make sure that the hash size is what we expect.
				AssertEquals("hash size is incorrect",
							 alg.HashSize, expected.Length * 8);

				// Convert the string form of the input into a byte array.
				byte[] input = Encoding.ASCII.GetBytes(value);

				// Get the hash value over the input.
				byte[] hash = alg.ComputeHash(input);

				// Compare the hash with the expected value.
				AssertNotNull("returned hash was null", hash);
				AssertEquals("hash length is wrong", hash.Length,
							 expected.Length);
				if(!IdenticalBlock(hash, 0, expected, 0, expected.Length))
				{
					Fail("incorrect hash value produced");
				}

				// Get the hash value over the input in a sub-buffer.
				byte[] input2 = new byte [input.Length + 20];
				Array.Copy(input, 0, input2, 10, input.Length);
				hash = alg.ComputeHash(input2, 10, input.Length);

				// Compare the hash with the expected value.
				AssertNotNull("returned hash was null", hash);
				AssertEquals("hash length is wrong", hash.Length,
							 expected.Length);
				if(!IdenticalBlock(hash, 0, expected, 0, expected.Length))
				{
					Fail("incorrect hash value produced");
				}

				// Get the hash value over the input via a stream.
				MemoryStream stream = new MemoryStream(input, false);
				hash = alg.ComputeHash(stream);

				// Compare the hash with the expected value.
				AssertNotNull("returned hash was null", hash);
				AssertEquals("hash length is wrong", hash.Length,
							 expected.Length);
				if(!IdenticalBlock(hash, 0, expected, 0, expected.Length))
				{
					Fail("incorrect hash value produced");
				}
			}
Esempio n. 41
0
 /// <summary>
 /// Compute the hash of the full key string using the given hash algorithm
 /// </summary>
 /// <param name="fullKeyString">The full key return by call FullKeyAsString</param>
 /// <param name="hashAlgorithm">The hash algorithm used to hash the key</param>
 /// <returns>The hashed key as a string</returns>
 private static string ComputeHash(string fullKeyString, HashAlgorithm hashAlgorithm)
 {
     byte[] bytes        = Encoding.ASCII.GetBytes(fullKeyString);
     byte[] computedHash = hashAlgorithm.ComputeHash(bytes);
     return(Convert.ToBase64String(computedHash));
 }
Esempio n. 42
0
		private static byte[] GetEmptyHash (HashAlgorithm hash) 
		{
			if (hash is SHA1)
				return emptySHA1;
			else if (hash is SHA256)
				return emptySHA256;
#if !NET_2_1 || MONOTOUCH
			else if (hash is SHA384)
				return emptySHA384;
			else if (hash is SHA512)
				return emptySHA512;
#endif
			else
				return hash.ComputeHash ((byte[])null);
		}
        /// <summary>
        /// Construct the strong assembly name from metadata
        /// </summary>
        internal static string GetAssemblyStrongName(MetadataReader metadataReader)
        {
            AssemblyDefinition assemblyDefinition = metadataReader.GetAssemblyDefinition();
            string             asmName            = metadataReader.GetString(assemblyDefinition.Name);
            string             asmVersion         = assemblyDefinition.Version.ToString();
            string             asmCulture         = metadataReader.GetString(assemblyDefinition.Culture);

            asmCulture = (asmCulture == string.Empty) ? "neutral" : asmCulture;

            AssemblyHashAlgorithm hashAlgorithm = assemblyDefinition.HashAlgorithm;
            BlobHandle            blobHandle    = assemblyDefinition.PublicKey;
            BlobReader            blobReader    = metadataReader.GetBlobReader(blobHandle);

            string publicKeyTokenString = "null";

            // Extract public key token only if PublicKey exists in the metadata
            if (blobReader.Length > 0)
            {
                byte[] publickey = blobReader.ReadBytes(blobReader.Length);

                HashAlgorithm hashImpl = null;
                switch (hashAlgorithm)
                {
                case AssemblyHashAlgorithm.Sha1:
                    hashImpl = SHA1.Create();
                    break;

                case AssemblyHashAlgorithm.MD5:
                    hashImpl = MD5.Create();
                    break;

                case AssemblyHashAlgorithm.Sha256:
                    hashImpl = SHA256.Create();
                    break;

                case AssemblyHashAlgorithm.Sha384:
                    hashImpl = SHA384.Create();
                    break;

                case AssemblyHashAlgorithm.Sha512:
                    hashImpl = SHA512.Create();
                    break;

                default:
                    throw new NotSupportedException();
                }

                byte[] publicKeyHash       = hashImpl.ComputeHash(publickey);
                byte[] publicKeyTokenBytes = new byte[8];
                // Note that, the low 8 bytes of the hash of public key in reverse order is the public key tokens.
                for (int i = 1; i <= 8; i++)
                {
                    publicKeyTokenBytes[i - 1] = publicKeyHash[publicKeyHash.Length - i];
                }

                // Convert bytes to hex format strings in lower case.
                publicKeyTokenString = BitConverter.ToString(publicKeyTokenBytes).Replace("-", string.Empty).ToLowerInvariant();
            }

            string strongAssemblyName = string.Format(CultureInfo.InvariantCulture,
                                                      "{0}, Version={1}, Culture={2}, PublicKeyToken={3}",
                                                      asmName, asmVersion, asmCulture, publicKeyTokenString);

            return(strongAssemblyName);
        }
Esempio n. 44
0
        internal StrongNameSignature StrongHash(Stream stream, StrongNameOptions options)
        {
            StrongNameSignature signature = new StrongNameSignature();
            HashAlgorithm       transform = HashAlgorithm.Create(this.TokenAlgorithm);
            CryptoStream        stream2   = new CryptoStream(Stream.Null, transform, CryptoStreamMode.Write);

            byte[] buffer = new byte[0x80];
            stream.Read(buffer, 0, 0x80);
            if (BitConverterLE.ToUInt16(buffer, 0) != 0x5a4d)
            {
                return(null);
            }
            uint num = BitConverterLE.ToUInt32(buffer, 60);

            stream2.Write(buffer, 0, 0x80);
            if (num != 0x80)
            {
                byte[] buffer2 = new byte[num - 0x80];
                stream.Read(buffer2, 0, buffer2.Length);
                stream2.Write(buffer2, 0, buffer2.Length);
            }
            byte[] buffer3 = new byte[0xf8];
            stream.Read(buffer3, 0, 0xf8);
            if (BitConverterLE.ToUInt32(buffer3, 0) != 0x4550)
            {
                return(null);
            }
            if (BitConverterLE.ToUInt16(buffer3, 4) != 0x14c)
            {
                return(null);
            }
            byte[] src = new byte[8];
            Buffer.BlockCopy(src, 0, buffer3, 0x58, 4);
            Buffer.BlockCopy(src, 0, buffer3, 0x98, 8);
            stream2.Write(buffer3, 0, 0xf8);
            ushort sections = BitConverterLE.ToUInt16(buffer3, 6);
            int    count    = sections * 40;

            byte[] buffer5 = new byte[count];
            stream.Read(buffer5, 0, count);
            stream2.Write(buffer5, 0, count);
            uint r    = BitConverterLE.ToUInt32(buffer3, 0xe8);
            uint num5 = this.RVAtoPosition(r, sections, buffer5);
            int  num6 = (int)BitConverterLE.ToUInt32(buffer3, 0xec);

            byte[] buffer6 = new byte[num6];
            stream.Position = num5;
            stream.Read(buffer6, 0, num6);
            uint num7 = BitConverterLE.ToUInt32(buffer6, 0x20);

            signature.SignaturePosition = this.RVAtoPosition(num7, sections, buffer5);
            signature.SignatureLength   = BitConverterLE.ToUInt32(buffer6, 0x24);
            uint num8 = BitConverterLE.ToUInt32(buffer6, 8);

            signature.MetadataPosition = this.RVAtoPosition(num8, sections, buffer5);
            signature.MetadataLength   = BitConverterLE.ToUInt32(buffer6, 12);
            if (options == StrongNameOptions.Metadata)
            {
                stream2.Close();
                transform.Initialize();
                byte[] buffer7 = new byte[signature.MetadataLength];
                stream.Position = signature.MetadataPosition;
                stream.Read(buffer7, 0, buffer7.Length);
                signature.Hash = transform.ComputeHash(buffer7);
                return(signature);
            }
            for (int i = 0; i < sections; i++)
            {
                uint   num10   = BitConverterLE.ToUInt32(buffer5, (i * 40) + 20);
                int    num11   = (int)BitConverterLE.ToUInt32(buffer5, (i * 40) + 0x10);
                byte[] buffer8 = new byte[num11];
                stream.Position = num10;
                stream.Read(buffer8, 0, num11);
                if ((num10 <= signature.SignaturePosition) && (signature.SignaturePosition < (num10 + num11)))
                {
                    int num12 = (int)(signature.SignaturePosition - num10);
                    if (num12 > 0)
                    {
                        stream2.Write(buffer8, 0, num12);
                    }
                    signature.Signature = new byte[signature.SignatureLength];
                    Buffer.BlockCopy(buffer8, num12, signature.Signature, 0, (int)signature.SignatureLength);
                    Array.Reverse(signature.Signature);
                    int offset = num12 + ((int)signature.SignatureLength);
                    int num14  = num11 - offset;
                    if (num14 > 0)
                    {
                        stream2.Write(buffer8, offset, num14);
                    }
                }
                else
                {
                    stream2.Write(buffer8, 0, num11);
                }
            }
            stream2.Close();
            signature.Hash = transform.Hash;
            return(signature);
        }
Esempio n. 45
0
		public bool method_11(byte[] byte_2, HashAlgorithm hashAlgorithm_0, byte[] byte_3)
		{
			Class1.Class13.Enum1 enum1_ = this.method_16(hashAlgorithm_0);
			byte[] byte_4 = hashAlgorithm_0.ComputeHash(byte_2);
			return this.method_9(byte_4, byte_3, enum1_);
		}
Esempio n. 46
0
        ///***************************************************/

        private static byte[] SHA256_byte(byte[] inputObj)
        {
            HashAlgorithm algorithm = System.Security.Cryptography.SHA256.Create();

            return(algorithm.ComputeHash(inputObj));
        }
Esempio n. 47
0
        public static void VerifyTrivialHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm)
        {
            using (referenceAlgorithm)
            using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm))
            {
                byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>());
                byte[] incrementalResult = incrementalHash.GetHashAndReset();

                Assert.Equal(referenceHash, incrementalResult);
            }
        }
Esempio n. 48
0
        public static byte[] GetHash(string inputString)
        {
            HashAlgorithm algorithm = MD5.Create();  //or use SHA1.Create();

            return(algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString)));
        }
		//private bool VerifySignature (ASN1 cs, byte[] calculatedMessageDigest, string hashName) 
		private bool VerifySignature (PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha) 
		{
			string contentType = null;
			ASN1 messageDigest = null;
//			string spcStatementType = null;
//			string spcSpOpusInfo = null;

			for (int i=0; i < sd.SignerInfo.AuthenticatedAttributes.Count; i++) {
				ASN1 attr = (ASN1) sd.SignerInfo.AuthenticatedAttributes [i];
				string oid = ASN1Convert.ToOid (attr[0]);
				switch (oid) {
					case "1.2.840.113549.1.9.3":
						// contentType
						contentType = ASN1Convert.ToOid (attr[1][0]);
						break;
					case "1.2.840.113549.1.9.4":
						// messageDigest
						messageDigest = attr[1][0];
						break;
					case "1.3.6.1.4.1.311.2.1.11":
						// spcStatementType (Microsoft code signing)
						// possible values
						// - individualCodeSigning (1 3 6 1 4 1 311 2 1 21)
						// - commercialCodeSigning (1 3 6 1 4 1 311 2 1 22)
//						spcStatementType = ASN1Convert.ToOid (attr[1][0][0]);
						break;
					case "1.3.6.1.4.1.311.2.1.12":
						// spcSpOpusInfo (Microsoft code signing)
/*						try {
							spcSpOpusInfo = System.Text.Encoding.UTF8.GetString (attr[1][0][0][0].Value);
						}
						catch (NullReferenceException) {
							spcSpOpusInfo = null;
						}*/
						break;
					default:
						break;
				}
			}
			if (contentType != spcIndirectDataContext)
				return false;

			// verify message digest
			if (messageDigest == null)
				return false;
			if (!messageDigest.CompareValue (calculatedMessageDigest))
				return false;

			// verify signature
			string hashOID = CryptoConfig.MapNameToOID (ha.ToString ());
			
			// change to SET OF (not [0]) as per PKCS #7 1.5
			ASN1 aa = new ASN1 (0x31);
			foreach (ASN1 a in sd.SignerInfo.AuthenticatedAttributes)
				aa.Add (a);
			ha.Initialize ();
			byte[] p7hash = ha.ComputeHash (aa.GetBytes ());

			byte[] signature = sd.SignerInfo.Signature;
			// we need to find the specified certificate
			string issuer = sd.SignerInfo.IssuerName;
			byte[] serial = sd.SignerInfo.SerialNumber;
			foreach (X509Certificate x509 in coll) {
				if (CompareIssuerSerial (issuer, serial, x509)) {
					// don't verify is key size don't match
					if (x509.PublicKey.Length > (signature.Length >> 3)) {
						// return the signing certificate even if the signature isn't correct
						// (required behaviour for 2.0 support)
						signingCertificate = x509;
						RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA;
						if (rsa.VerifyHash (p7hash, hashOID, signature)) {
							signerChain.LoadCertificates (coll);
							trustedRoot = signerChain.Build (x509);
							break; 
						}
					}
				}
			}

			// timestamp signature is optional
			if (sd.SignerInfo.UnauthenticatedAttributes.Count == 0) {
				trustedTimestampRoot = true;
			}  else {
				for (int i = 0; i < sd.SignerInfo.UnauthenticatedAttributes.Count; i++) {
					ASN1 attr = (ASN1) sd.SignerInfo.UnauthenticatedAttributes[i];
					string oid = ASN1Convert.ToOid (attr[0]);
					switch (oid) {
					case PKCS7.Oid.countersignature:
						// SEQUENCE {
						//   OBJECT IDENTIFIER
						//     countersignature (1 2 840 113549 1 9 6)
						//   SET {
						PKCS7.SignerInfo cs = new PKCS7.SignerInfo (attr[1]);
						trustedTimestampRoot = VerifyCounterSignature (cs, signature);
						break;
					default:
						// we don't support other unauthenticated attributes
						break;
					}
				}
			}

			return (trustedRoot && trustedTimestampRoot);
		}
Esempio n. 50
0
 /// <summary>
 /// HashAlgorithm 加密统一方法
 /// </summary>
 private static string HashAlgorithmBase(HashAlgorithm hashAlgorithmObj, string source, Encoding encoding)
 {
     byte[] btStr   = encoding.GetBytes(source);
     byte[] hashStr = hashAlgorithmObj.ComputeHash(btStr);
     return(hashStr.Bytes2Str());
 }
		public override byte[] GetDigestedOutput (HashAlgorithm hash)
		{
			// no null check, MS throws a NullReferenceException here
			return hash.ComputeHash ((Stream) GetOutput ());
		}
Esempio n. 52
0
 protected static string ComputeHash(string input, HashAlgorithm algorithm)
 {
     Byte[] inputBytes  = Encoding.UTF8.GetBytes(input);
     Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
     return(BitConverter.ToString(hashedBytes).Replace("-", ""));
 }
		public override byte[] GetDigestedOutput (HashAlgorithm hash)
		{
			return hash.ComputeHash ((Stream) GetOutput ());
		}
Esempio n. 54
0
        /// <summary>
        /// Returns a pseudo-random key from a password, salt and iteration count.
        /// </summary>
        /// <param name="cb">The number of pseudo-random key bytes to generate.</param>
        /// <returns>A byte array filled with pseudo-random key bytes.</returns>
        public override byte[] GetBytes(int cb)
        {
            if (cb <= 0)
            {
                throw new ArgumentOutOfRangeException("cb", cb, "cb is out of range. Positive number required.");
            }

            if (_currentHash == null)
            {
                _hashList          = new List <byte>();
                _currentHash       = new byte[0];
                _hashListReadIndex = 0;

                int preHashLength = _data.Length + ((_salt != null) ? _salt.Length : 0);

                var preHash = new byte[preHashLength];

                Buffer.BlockCopy(_data, 0, preHash, 0, _data.Length);
                if (_salt != null)
                {
                    Buffer.BlockCopy(_salt, 0, preHash, _data.Length, _salt.Length);
                }

                _currentHash = _hash.ComputeHash(preHash);

                for (int i = 1; i < _iterations; i++)
                {
                    _currentHash = _hash.ComputeHash(_currentHash);
                }

                _hashList.AddRange(_currentHash);
            }

            while (_hashList.Count < (cb + _hashListReadIndex))
            {
                int preHashLength = _currentHash.Length + _data.Length + ((_salt != null) ? _salt.Length : 0);
                var preHash       = new byte[preHashLength];

                Buffer.BlockCopy(_currentHash, 0, preHash, 0, _currentHash.Length);
                Buffer.BlockCopy(_data, 0, preHash, _currentHash.Length, _data.Length);
                if (_salt != null)
                {
                    Buffer.BlockCopy(_salt, 0, preHash, _currentHash.Length + _data.Length, _salt.Length);
                }

                _currentHash = _hash.ComputeHash(preHash);

                for (int i = 1; i < _iterations; i++)
                {
                    _currentHash = _hash.ComputeHash(_currentHash);
                }

                _hashList.AddRange(_currentHash);
            }

            byte[] dst = new byte[cb];
            _hashList.CopyTo(_hashListReadIndex, dst, 0, cb);
            _hashListReadIndex += cb;

            return(dst);
        }
Esempio n. 55
0
		public HMAC(string hashName, byte[] rgbKey)
		{
			// Create the hash
			if (hashName == null || hashName.Length == 0)
			{
				hashName = "MD5";
			}
			hash = HashAlgorithm.Create(hashName);
			// Set HashSizeValue
			HashSizeValue = hash.HashSize;

			/* if key is longer than 64 bytes reset it to rgbKey = Hash(rgbKey) */
			if (rgbKey.Length > 64)
			{
				KeyValue = hash.ComputeHash(rgbKey);
			}
			else
			{
				KeyValue = (byte[])rgbKey.Clone();
			}

			this.Initialize();
		}
Esempio n. 56
0
		public HMAC (HashAlgorithm ha, byte[] rgbKey)
		{
			hash = ha;
			// Set HashSizeValue
			HashSizeValue = hash.HashSize;

			/* if key is longer than 64 bytes reset it to rgbKey = Hash(rgbKey) */
			if (rgbKey.Length > 64)
			{
				KeyValue = hash.ComputeHash(rgbKey);
			}
			else
			{
				KeyValue = (byte[])rgbKey.Clone();
			}

			this.Initialize();
		}