Esempio n. 1
0
        private byte[] Func()
        {
            byte[] array = Utils_Int(m_block);
            m_hmac.TransformBlock(m_salt, 0, m_salt.Length, null, 0);
            m_hmac.TransformBlock(array, 0, array.Length, null, 0);
            var _EmptyArray_byte_Value = new byte[0];             // EmptyArray<byte>.Value

            m_hmac.TransformFinalBlock(_EmptyArray_byte_Value, 0, 0);
            byte[] hashValue = m_hmac.Hash;
            m_hmac.Initialize();
            byte[] array2 = hashValue;
            for (int i = 2; i <= m_iterations; i++)
            {
                m_hmac.TransformBlock(hashValue, 0, hashValue.Length, null, 0);
                m_hmac.TransformFinalBlock(_EmptyArray_byte_Value, 0, 0);
                hashValue = m_hmac.Hash;
                for (int j = 0; j < m_blockSize; j++)
                {
                    array2[j] ^= hashValue[j];
                }
                m_hmac.Initialize();
            }
            m_block++;
            return(array2);
        }
Esempio n. 2
0
        public override void Reset()
        {
            _md5HMAC.Initialize();
            _md5Ai   = _md5HMAC.ComputeHash(_seed);
            _md5Hash = new byte[0];

            _sha1HMAC.Initialize();
            _sha1Ai   = _sha1HMAC.ComputeHash(_seed);
            _sha1Hash = new byte[0];
        }
Esempio n. 3
0
        // This function is defined as follow :
        // Func (S, i) = HMAC(S || i) | HMAC2(S || i) | ... | HMAC(iterations) (S || i)
        // where i is the block number.
        byte[] Func()
        {
            var intBlock = UintToBigEndianBytes(_block);

            _hmac.TransformBlock(_salt, 0, _salt.Length, _salt, 0);
            _hmac.TransformFinalBlock(intBlock, 0, intBlock.Length);
            var temp = _hmac.Hash;

            _hmac.Initialize();

            var ret = temp;

            for (var i = 2; i <= _iterations; i++)
            {
                temp = _hmac.ComputeHash(temp);
                for (var j = 0; j < BlockSize; j++)
                {
                    ret[j] ^= temp[j];
                }
            }

            // increment the block count.
            _block++;
            return(ret);
        }
Esempio n. 4
0
        public void ValidateBytes(ContentType contentType, ulong seqNum, int frameIndex,
                                  byte[] plainBytes, byte[] mac, byte[] padding)
        {
            if (SecurityParameters.MACAlgorithm != MACAlgorithm.Null)
            {
                byte[] versionAndType  = new byte[] { (byte)contentType, m_protocolVersion[0], m_protocolVersion[1] };
                byte[] seqNumBytes     = BitConverter.GetBytes(seqNum);
                byte[] messageSize     = BitConverter.GetBytes(plainBytes.Length);
                byte[] frameIndexBytes = BitConverter.GetBytes(frameIndex);

                m_decryptionHMAC.Initialize();
                m_decryptionHMAC.TransformBlock(seqNumBytes, 0, seqNumBytes.Length, seqNumBytes, 0);
                m_decryptionHMAC.TransformBlock(versionAndType, 0, versionAndType.Length, versionAndType, 0);
                m_decryptionHMAC.TransformBlock(messageSize, 0, messageSize.Length, messageSize, 0);
                m_decryptionHMAC.TransformBlock(frameIndexBytes, 0, frameIndexBytes.Length, frameIndexBytes, 0);
                m_decryptionHMAC.TransformFinalBlock(plainBytes, 0, plainBytes.Length);

                if (!m_decryptionHMAC.Hash.SequenceEqual(mac))
                {
                    throw new NetMQSecurityException(NetMQSecurityErrorCode.MACNotMatched, "MAC not matched message");
                }

                for (int i = 0; i < padding.Length; i++)
                {
                    if (padding[i] != padding.Length - 1)
                    {
                        throw new NetMQSecurityException(NetMQSecurityErrorCode.MACNotMatched, "MAC not matched message");
                    }
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Check the given arguments and throw a <see cref="NetMQSecurityException"/> if something is amiss.
        /// </summary>
        /// <param name="contentType">This identifies the type of content: ChangeCipherSpec, Handshake, or ApplicationData.</param>
        /// <param name="seqNum"></param>
        /// <param name="frameIndex"></param>
        /// <param name="plainBytes"></param>
        /// <param name="mac"></param>
        /// <param name="padding"></param>
        /// <exception cref="NetMQSecurityException"><see cref="NetMQSecurityErrorCode.MACNotMatched"/>: MAC does not match message.</exception>
        public void ValidateBytes(ContentType contentType, ulong seqNum, byte[] plainBytes, byte[] mac, byte[] padding)
        {
            if (SecurityParameters.MACAlgorithm != MACAlgorithm.Null)
            {
                byte[] typeAndVersion = new[] { (byte)contentType, m_SubProtocolVersion[0], m_SubProtocolVersion[1] };
                byte[] seqNumBytes    = BitConverter.GetBytes(seqNum).Reverse().ToArray();
                byte[] messageSize    = BitConverter.GetBytes(plainBytes.Length).Take(2).Reverse().ToArray();
                //byte[] messageSize = plainBytes.LengthToBytes(2);
                m_decryptionHMAC.Initialize();
                m_decryptionHMAC.TransformBlock(seqNumBytes, 0, seqNumBytes.Length, seqNumBytes, 0);
                m_decryptionHMAC.TransformBlock(typeAndVersion, 0, typeAndVersion.Length, typeAndVersion, 0);
                m_decryptionHMAC.TransformBlock(messageSize, 0, messageSize.Length, messageSize, 0);
                m_decryptionHMAC.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
                //MAC(MAC_write_key, seq_num +
                //      TLSCompressed.type +
                //      TLSCompressed.version +
                //      TLSCompressed.length +
                //      TLSCompressed.fragment);
                //where "+" denotes concatenation.
                if (!m_decryptionHMAC.Hash.SequenceEqual(mac))
                {
                    throw new NetMQSecurityException(NetMQSecurityErrorCode.MACNotMatched, "MAC does not match message");
                }

                for (int i = 0; i < padding.Length; i++)
                {
                    if (padding[i] != padding.Length - 1)
                    {
                        throw new NetMQSecurityException(NetMQSecurityErrorCode.MACNotMatched, "MAC not matched message");
                    }
                }
            }
        }
Esempio n. 6
0
        private static byte[] F(string password, Salt salt, int derivationIterations)
        {
            HMAC hmacsha512 = New <HMACSHA512>().Initialize(new SymmetricKey(new UTF8Encoding(false).GetBytes(password)));

            hmacsha512.TransformBlock(salt.GetBytes(), 0, salt.Length, null, 0);
            byte[] iBytes = 1.GetBigEndianBytes();

            hmacsha512.TransformBlock(iBytes, 0, iBytes.Length, null, 0);
            hmacsha512.TransformFinalBlock(_empty, 0, 0);

            byte[] u  = hmacsha512.Hash();
            byte[] un = u;

            for (int c = 2; c <= derivationIterations; ++c)
            {
                hmacsha512.Initialize();
                hmacsha512.TransformBlock(u, 0, u.Length, null, 0);
                hmacsha512.TransformFinalBlock(_empty, 0, 0);
                u = hmacsha512.Hash();
                for (int i = 0; i < u.Length; i++)
                {
                    un[i] ^= u[i];
                }
            }

            return(un);
        }
Esempio n. 7
0
        protected void VerifyHmac(
            int testCaseId,
            string digest,
            int truncateSize = -1)
        {
            byte[] digestBytes = ByteUtils.HexToByteArray(digest);
            byte[] data        = _testData[testCaseId];
            byte[] computedDigest;

            using (HMAC hmac = Create())
            {
                Assert.True(hmac.HashSize > 0);

                byte[] key = (byte[])_testKeys[testCaseId].Clone();
                hmac.Key = key;

                // make sure the getter returns different objects each time
                Assert.NotSame(key, hmac.Key);
                Assert.NotSame(hmac.Key, hmac.Key);

                // make sure the setter didn't cache the exact object we passed in
                key[0] = (byte)(key[0] + 1);
                Assert.NotEqual <byte>(key, hmac.Key);

                computedDigest = hmac.ComputeHash(data);
            }

            if (truncateSize != -1)
            {
                byte[] tmp = new byte[truncateSize];
                Array.Copy(computedDigest, tmp, truncateSize);
                computedDigest = tmp;
            }

            Assert.Equal(digestBytes, computedDigest);

            using (HMAC hmac = Create())
            {
                byte[] key = (byte[])_testKeys[testCaseId].Clone();
                hmac.Key = key;

                hmac.TransformBlock(data, 0, data.Length, null, 0);
                hmac.Initialize();
                hmac.TransformBlock(data, 0, data.Length, null, 0);
                hmac.TransformFinalBlock(Array.Empty <byte>(), 0, 0);
                computedDigest = hmac.Hash;
            }

            if (truncateSize != -1)
            {
                byte[] tmp = new byte[truncateSize];
                Array.Copy(computedDigest, tmp, truncateSize);
                computedDigest = tmp;
            }

            Assert.Equal(digestBytes, computedDigest);
        }
Esempio n. 8
0
 public void CheckE(string testName, HMAC algo, byte[] data, byte[] result)
 {
     byte[] copy = new byte[data.Length];
     for (int i = 0; i < data.Length - 1; i++)
     {
         algo.TransformBlock(data, i, 1, copy, i);
     }
     algo.TransformFinalBlock(data, data.Length - 1, 1);
     Compare(result, algo.Hash, testName + "e");
     algo.Initialize();
 }
Esempio n. 9
0
        private byte[] EncryptBytes(ICryptoTransform encryptor, ContentType contentType, ulong seqNum,
                                    int frameIndex, byte[] plainBytes)
        {
            byte[] mac;

            if (SecurityParameters.MACAlgorithm != MACAlgorithm.Null)
            {
                byte[] versionAndType  = new byte[] { (byte)contentType, m_protocolVersion[0], m_protocolVersion[1] };
                byte[] seqNumBytes     = BitConverter.GetBytes(seqNum);
                byte[] messageSize     = BitConverter.GetBytes(plainBytes.Length);
                byte[] frameIndexBytes = BitConverter.GetBytes(frameIndex);

                m_encryptionHMAC.Initialize();
                m_encryptionHMAC.TransformBlock(seqNumBytes, 0, seqNumBytes.Length, seqNumBytes, 0);
                m_encryptionHMAC.TransformBlock(versionAndType, 0, versionAndType.Length, versionAndType, 0);
                m_encryptionHMAC.TransformBlock(messageSize, 0, messageSize.Length, messageSize, 0);
                m_encryptionHMAC.TransformBlock(frameIndexBytes, 0, frameIndexBytes.Length, frameIndexBytes, 0);
                m_encryptionHMAC.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
                mac = m_encryptionHMAC.Hash;
            }
            else
            {
                mac = new byte[0];
            }

            int  length  = plainBytes.Length + SecurityParameters.MACLength;
            byte padding = 0;

            if (SecurityParameters.BulkCipherAlgorithm != BulkCipherAlgorithm.Null)
            {
                padding = (byte)((encryptor.OutputBlockSize -
                                  (plainBytes.Length + SecurityParameters.MACLength + 1) % encryptor.OutputBlockSize) %
                                 encryptor.OutputBlockSize);

                length += padding + 1;
            }

            byte[] cipherBytes = new byte[length];

            Buffer.BlockCopy(plainBytes, 0, cipherBytes, 0, plainBytes.Length);
            Buffer.BlockCopy(mac, 0, cipherBytes, plainBytes.Length, SecurityParameters.MACLength);

            if (SecurityParameters.BulkCipherAlgorithm != BulkCipherAlgorithm.Null)
            {
                for (int i = plainBytes.Length + SecurityParameters.MACLength; i < cipherBytes.Length; i++)
                {
                    cipherBytes[i] = padding;
                }

                encryptor.TransformBlock(cipherBytes, 0, cipherBytes.Length, cipherBytes, 0);
            }

            return(cipherBytes);
        }
Esempio n. 10
0
        public static byte[] ComputeHash(this HMAC hmac, params byte[][] blobs)
        {
            hmac.Initialize();
            // TODO: generalize to allow encodings other than UTF-8.
            foreach (var blob in blobs.Take(blobs.Length - 1))
            {
                hmac.TransformBlock(blob, 0, blob.Length, null, 0);
            }
            var lastBlob = blobs[blobs.Length - 1];

            hmac.TransformFinalBlock(lastBlob, 0, lastBlob.Length);
            return(hmac.Hash);
        }
Esempio n. 11
0
        static byte[] Compute_PHash(int bytes, byte[][] seeds, HMAC hmac, int blockSize)
        {
            int blocks = (bytes / blockSize) + (bytes % blockSize == 0 ? 0 : 1);

            byte[] ret  = new byte[blockSize * blocks];
            byte[] prev = null;

            for (int i = 0; i < blocks; i++)
            {
                hmac.Initialize();
                if (prev == null)
                {
                    for (int q = 0; q < seeds.Length; q++)
                    {
                        hmac.TransformBlock(seeds[q], 0, seeds[q].Length, seeds[q], 0);
                    }
                }
                else
                {
                    hmac.TransformBlock(prev, 0, prev.Length, prev, 0);
                }
                hmac.TransformFinalBlock(Utility.EmptyByteArray, 0, 0);
                prev = hmac.Hash;
                hmac.Initialize();
                hmac.TransformBlock(prev, 0, prev.Length, prev, 0);
                for (int q = 0; q < seeds.Length; q++)
                {
                    hmac.TransformBlock(seeds[q], 0, seeds[q].Length, seeds[q], 0);
                }
                hmac.TransformFinalBlock(Utility.EmptyByteArray, 0, 0);
                for (int q = 0; q < blockSize; q++)
                {
                    ret[i * blockSize + q] = hmac.Hash[q];
                }
            }
            return(ret);
        }
Esempio n. 12
0
        protected void VerifyHmac(int testCaseId, byte[] digestBytes)
        {
            byte[] data = _testData[testCaseId];
            byte[] computedDigest;
            int    truncateSize = digestBytes.Length;

            AssertExtensions.LessThanOrEqualTo(truncateSize, MacSize);

            using (HMAC hmac = Create())
            {
                Assert.Equal(MacSize, hmac.HashSize / 8);

                byte[] key = (byte[])_testKeys[testCaseId].Clone();
                hmac.Key = key;

                // make sure the getter returns different objects each time
                Assert.NotSame(key, hmac.Key);
                Assert.NotSame(hmac.Key, hmac.Key);

                // make sure the setter didn't cache the exact object we passed in
                key[0] = (byte)(key[0] + 1);
                Assert.NotEqual <byte>(key, hmac.Key);

                computedDigest = hmac.ComputeHash(data);
            }

            computedDigest = Truncate(computedDigest, truncateSize);
            Assert.Equal(digestBytes, computedDigest);

            using (HMAC hmac = Create())
            {
                byte[] key = (byte[])_testKeys[testCaseId].Clone();
                hmac.Key = key;

                hmac.TransformBlock(data, 0, data.Length, null, 0);
                hmac.Initialize();
                hmac.TransformBlock(data, 0, data.Length, null, 0);
                hmac.TransformFinalBlock(Array.Empty <byte>(), 0, 0);
                computedDigest = hmac.Hash;
            }

            computedDigest = Truncate(computedDigest, truncateSize);
            Assert.Equal(digestBytes, computedDigest);

            // One shot - allocating and byte array inputs
            computedDigest = HashDataOneShot(_testKeys[testCaseId], data);

            computedDigest = Truncate(computedDigest, truncateSize);
            Assert.Equal(digestBytes, computedDigest);
Esempio n. 13
0
		static readonly byte[] emptyArray64 = new byte[64]; // for SHA-512

		public HKDF(Func<HMAC> hmacFactory, byte[] ikm, byte[] salt = null, byte[] context = null)
		{
			hmac = hmacFactory();
			hmac2 = hmac as HMAC2;
			hashLength = hmac.HashSize >> 3;

			// a malicious implementation of HMAC could conceivably mess up the shared static empty byte arrays, which are still writeable...
			hmac.Key = salt ?? (hashLength == 48 ? emptyArray48 : hashLength == 64 ? emptyArray64 : hashLength == 32 ? emptyArray32 : hashLength == 20 ? emptyArray20 : new byte[hashLength]);

			// re-keying hmac with PRK
			hmac.TransformBlock(ikm, 0, ikm.Length, null, 0);
			hmac.TransformFinalBlock(ikm, 0, 0);
			hmac.Key = (hmac2 != null) ? hmac2.HashInner : hmac.Hash;
			hmac.Initialize();
			this.context = context;
			Reset();
		}
Esempio n. 14
0
        /// <summary>
        /// Generates PIN code based on given Base32 secret code, interval length, and desired PIN code length
        /// </summary>
        /// <param name="secret">Base32 Secret Code</param>
        /// <returns>PIN code with desired number of digits</returns>
        public string computePin(string secret)
        {
            string strToReturn = "";

            try
            {
                byte[] keyBytes = FromBase32String(secret);
                mac = new HMACSHA1(keyBytes);
                mac.Initialize();
                strToReturn = generateResponseCode(getCurrentInterval());
            }
            catch (Exception e)
            {
                return(e.Message);
            }

            return(strToReturn);
        }
Esempio n. 15
0
        /// <summary>
        /// Creates the signature.
        /// </summary>
        /// <returns>The signature.</returns>
        /// <param name="message">Message.</param>
        public string CreateSignature(Message message)
        {
            _signatureGenerator.Initialize();

            var messages = GetMessagesToAddForDigest(message);

            // For all items update the signature
            foreach (var item in messages)
            {
                var sourceBytes = _encoder.GetBytes(item);
                _signatureGenerator.TransformBlock(sourceBytes, 0, sourceBytes.Length, null, 0);
            }

            _signatureGenerator.TransformFinalBlock(new byte[0], 0, 0);

            // Calculate the digest and remove -
            return(BitConverter.ToString(_signatureGenerator.Hash).Replace("-", "").ToLower());
        }
Esempio n. 16
0
        /// <summary>
        /// Creates the signature.
        /// </summary>
        /// <returns>The signature.</returns>
        /// <param name="message">Message.</param>
        public string CreateSignature(params string[] messages)
        {
            byte[] sourceBytes;
            _signatureGenerator.Initialize();
            // For all items update the signature
            var last = messages.Length - 1;

            for (var i = 0; i < last; i++)
            {
                sourceBytes = this._encoder.GetBytes(messages[i]);
                _signatureGenerator.TransformBlock(sourceBytes, 0, sourceBytes.Length, null, 0);
            }

            sourceBytes = _encoder.GetBytes(messages[last]);
            _signatureGenerator.TransformFinalBlock(sourceBytes, 0, sourceBytes.Length);

            // Calculate the digest and remove -
            return(BitConverter.ToString(_signatureGenerator.Hash).Replace("-", "").ToLower());
        }
 /**
  * Computes RFC 2104-compliant HMAC signature.
  */
 public static String sign(String data, String key, String signatureMethod)// throws SignatureException
 {
     try
     {
         ASCIIEncoding encoding = new ASCIIEncoding();
         HMAC          Hmac     = HMAC.Create(signatureMethod);
         Hmac.Key = encoding.GetBytes(key);
         Hmac.Initialize();
         CryptoStream cs = new CryptoStream(Stream.Null, Hmac, CryptoStreamMode.Write);
         cs.Write(encoding.GetBytes(data), 0, encoding.GetBytes(data).Length);
         cs.Close();
         byte[] rawResult = Hmac.Hash;
         String sig       = Convert.ToBase64String(rawResult, 0, rawResult.Length);
         return(sig);
     }
     catch (Exception e)
     {
         throw new AmazonFPSException("Failed to generate signature: " + e.Message);
     }
 }
Esempio n. 18
0
 private static String Sign(String data, String key, String signatureMethod)
 {
     try
     {
         var  encoding = new ASCIIEncoding();
         HMAC hmac     = HMAC.Create(signatureMethod);
         hmac.Key = encoding.GetBytes(key);
         hmac.Initialize();
         var cs    = new CryptoStream(Stream.Null, hmac, CryptoStreamMode.Write);
         var bytes = encoding.GetBytes(data);
         cs.Write(bytes, 0, bytes.Length);
         cs.Close();
         byte[] rawResult = hmac.Hash;
         String sig       = Convert.ToBase64String(rawResult, 0, rawResult.Length);
         return(sig);
     }
     catch (Exception e)
     {
         throw new Exception("Failed to generate signature: " + e.Message);
     }
 }
Esempio n. 19
0
        private void HmacDescriptionTest()
        {
            CSPPrng rng = new CSPPrng();

            byte[] data = rng.GetBytes(rng.Next(100, 400));
            byte[] key  = rng.GetBytes(64);
            HMAC   mac  = new HMAC(Digests.SHA256);

            mac.Initialize(key);
            byte[]         c1  = mac.ComputeMac(data);
            MacDescription mds = new MacDescription(64, Digests.SHA256);
            MacStream      mst = new MacStream(mds, new KeyParams(key));

            mst.Initialize(new MemoryStream(data));
            byte[] c2 = mst.ComputeMac();

            if (!Evaluate.AreEqual(c1, c2))
            {
                throw new Exception("MacStreamTest: HMAC code arrays are not equal!");
            }
        }
Esempio n. 20
0
        // iterative hash function
        private byte[] Func()
        {
            byte[] INT_block = _block.GetBigEndianBytes();

            _hmac.TransformBlock(_salt, 0, _salt.Length, _salt, 0);
            _hmac.TransformFinalBlock(INT_block, 0, INT_block.Length);
            byte[] temp = _hmac.Hash;
            _hmac.Initialize();

            byte[] ret = temp;
            for (int i = 2; i <= _iterationCount; i++)
            {
                temp = _hmac.ComputeHash(temp);
                for (int j = 0; j < _blockSize; j++)
                {
                    ret[j] ^= temp[j];
                }
            }

            _block++;
            return(ret);
        }
Esempio n. 21
0
        private Boolean ValidateSignatureV1(IDictionary <String, String> parameters)
        {
            if (awsSecretKey == null)
            {
                throw new Exception("Secret key should be set");
            }
            string signature;

            if (!String.IsNullOrEmpty(parameters[SIGNATURE_KEYNAME]))
            {
                signature = parameters[SIGNATURE_KEYNAME];
            }
            else
            {
                throw new Exception("'signature' is missing from the parameters.");
            }

            String sig;

            try
            {
                var  encoding = new ASCIIEncoding();
                HMAC hmac     = HMAC.Create("HmacSHA1");
                hmac.Key = encoding.GetBytes(awsSecretKey);
                hmac.Initialize();
                var    cs           = new CryptoStream(Stream.Null, hmac, CryptoStreamMode.Write);
                String stringToSign = CalculateStringToSignV1(parameters);
                cs.Write(encoding.GetBytes(stringToSign), 0, encoding.GetBytes(stringToSign).Length);
                cs.Close();
                byte[] rawResult = hmac.Hash;
                sig = Convert.ToBase64String(rawResult, 0, rawResult.Length);
            }
            catch (Exception e)
            {
                throw new Exception("Failed to generate HMAC : " + e.Message);
            }
            return(sig.Equals(signature));
        }
Esempio n. 22
0
        private static bool IsSignatureValid(ByteArrayPart requestUri, string password)
        {
            if (string.IsNullOrEmpty(password))
            {
                return(false);
            }

            hmac.Initialize();
            hmac.Key = Encoding.UTF8.GetBytes(password);

            var part      = requestUri;
            var signature = hmac.ComputeHash(part.Bytes, part.Offset, part.Length - 5 - 32);

            for (int i = 0; i < 16; i++)
            {
                if (HexEncoding.ParseHex2(parser.Signature, i * 2) != signature[i])
                {
                    return(false);
                }
            }

            return(true);
        }
        private byte[] ComputeBlock(int block, int size)
        {
            byte[] inputBuffer = BitConverter.GetBytes(block);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(inputBuffer, 0, 4);
            }

            _hashAlgo.TransformBlock(_salt, 0, _salt.Length, _salt, 0);
            _hashAlgo.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
            byte[] hash = _hashAlgo.Hash;
            _hashAlgo.Initialize();

            byte[] result = hash;
            for (int i = 2; i <= _iterations; i++)
            {
                hash = _hashAlgo.ComputeHash(hash);
                for (int j = 0; j < size; j++)
                {
                    result[j] = (byte)(result[j] ^ hash[j]);
                }
            }
            return(result);
        }
Esempio n. 24
0
        private static bool ValidateSignatureV1(NameValueCollection parameters)
        {
            String stringToSign = CalculateSignV1(parameters);
            String signature    = parameters[SIGNATURE_KEYNAME];
            String sig;

            try
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                HMAC          Hmac     = HMAC.Create("HmacSHA1");
                Hmac.Key = encoding.GetBytes(SimplePaySettings.SecretKey);
                Hmac.Initialize();
                CryptoStream cs = new CryptoStream(Stream.Null, Hmac, CryptoStreamMode.Write);
                cs.Write(encoding.GetBytes(stringToSign), 0, encoding.GetBytes(stringToSign).Length);
                cs.Close();
                byte[] rawResult = Hmac.Hash;
                sig = Convert.ToBase64String(rawResult, 0, rawResult.Length);
            }
            catch (Exception e)
            {
                throw new Exception("Failed to generate HMAC : " + e.Message);
            }
            return(sig.Equals(signature));
        }
Esempio n. 25
0
        /// <summary>
        /// Test the MacStream class implementation
        /// <para>Throws an Exception on failure</</para>
        /// </summary>
        public static void StreamMacTest()
        {
            byte[]       data;
            byte[]       key;
            MemoryStream instrm;
            MemoryStream outstrm = new MemoryStream();

            using (KeyGenerator kg = new KeyGenerator())
            {
                data = kg.GetBytes(512);
                key  = kg.GetBytes(64);
            }

            // data to digest
            instrm = new MemoryStream(data);
            byte[] code1;
            byte[] code2;

            using (MacStream sm = new MacStream(new HMAC(new SHA512(), key)))
            {
                sm.Initialize(instrm);
                code1 = sm.ComputeMac();
            }

            using (HMAC hm = new HMAC(new SHA512()))
            {
                hm.Initialize(key);
                code2 = hm.ComputeMac(data);
            }

            // compare the hash codes
            if (!Evaluate.AreEqual(code1, code2))
            {
                throw new Exception();
            }
        }
Esempio n. 26
0
        private void HMACTest(IDigest Digest, String[] Expected, byte[] TruncExpected)
        {
            HMAC mac = new HMAC(Digest);

            byte[] macV2 = new byte[mac.MacSize];

            for (int i = 0; i != _macKeys.Length; i++)
            {
                mac.Initialize(_macKeys[i]);

                byte[] mData = HexConverter.Decode(_macData[i]);
                byte[] macV  = new byte[mac.MacSize];

                mac.BlockUpdate(mData, 0, mData.Length);
                mac.DoFinal(macV, 0);

                if (Evaluate.AreEqual(HexConverter.Decode(Expected[i]), macV) == false)
                {
                    throw new Exception("Keccak HMAC: Expected hash is not equal! Expected: " + Expected[i] + " Received: " + HexConverter.ToString(macV));
                }
            }

            // test truncated keys
            mac = new HMAC(Digest);
            mac.Initialize(_truncKey);
            mac.BlockUpdate(_truncData, 0, _truncData.Length);
            mac.DoFinal(macV2, 0);

            for (int i = 0; i != TruncExpected.Length; i++)
            {
                if (macV2[i] != TruncExpected[i])
                {
                    throw new Exception("Keccak HMAC: Expected hash is not equal!");
                }
            }
        }
Esempio n. 27
0
        private byte[] EncryptBytes(ICryptoTransform encryptor, ContentType contentType, ulong seqNum, byte[] plainBytes)
        {
            byte[] mac;
            //记录有效负载保护
            //加密和 MAC 功能将 TLS 压缩结构转换为 TLSCipher 文本。 解密功能反转该过程。
            //记录的 MAC 还包括一个序列号,以便可检测到缺失、额外或重复的消息。
            //  struct {
            //       ContentType type;
            //        ProtocolVersion version;
            //        uint16 length;
            //        opaque fragment[TLSPlaintext.length];
            //    }
            //    TLSPlaintext;
            if (SecurityParameters.MACAlgorithm != MACAlgorithm.Null)
            {
                byte[] versionAndType = new[] { (byte)contentType, m_SubProtocolVersion[0], m_SubProtocolVersion[1] };
                byte[] seqNumBytes    = BitConverter.GetBytes(seqNum).Reverse().ToArray();                            //大端
                byte[] messageSize    = BitConverter.GetBytes((ushort)plainBytes.Length).Take(2).Reverse().ToArray(); //长度2字节

                m_encryptionHMAC.Initialize();
                m_encryptionHMAC.TransformBlock(seqNumBytes, 0, seqNumBytes.Length, seqNumBytes, 0);
                m_encryptionHMAC.TransformBlock(versionAndType, 0, versionAndType.Length, versionAndType, 0);
                m_encryptionHMAC.TransformBlock(messageSize, 0, messageSize.Length, messageSize, 0);
                m_encryptionHMAC.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
                mac = m_encryptionHMAC.Hash;
            }
            else
            {
                mac = EmptyArray <byte> .Instance;
            }

            int  length  = plainBytes.Length + SecurityParameters.MACLength;
            byte padding = 0;

            if (SecurityParameters.BulkCipherAlgorithm != BulkCipherAlgorithm.Null)
            {
                padding = (byte)((encryptor.OutputBlockSize -
                                  (plainBytes.Length + SecurityParameters.MACLength + 1) % encryptor.OutputBlockSize) %
                                 encryptor.OutputBlockSize);

                length += padding + 1;
            }

            byte[] cipherBytes = new byte[length];

            Buffer.BlockCopy(plainBytes, 0, cipherBytes, 0, plainBytes.Length);
            Buffer.BlockCopy(mac, 0, cipherBytes, plainBytes.Length, SecurityParameters.MACLength);
#if DEBUG
            Debug.WriteLine("[TLSPlaintext]:" + BitConverter.ToString(cipherBytes));
            Debug.WriteLine("[TLSPlaintext.data]:" + BitConverter.ToString(plainBytes));
            Debug.WriteLine("[TLSPlaintext.mac]:" + BitConverter.ToString(mac));
            Debug.WriteLine("[TLSPlaintext.padding]:" + padding);
#endif
            if (SecurityParameters.BulkCipherAlgorithm != BulkCipherAlgorithm.Null)
            {
                for (int i = plainBytes.Length + SecurityParameters.MACLength; i < cipherBytes.Length; i++)
                {
                    cipherBytes[i] = padding;
                }

                encryptor.TransformBlock(cipherBytes, 0, cipherBytes.Length, cipherBytes, 0);
            }
            return(cipherBytes);
        }
Esempio n. 28
0
 public void CheckD(string testName, HMAC algo, byte[] data, byte[] result)
 {
     algo.TransformFinalBlock(data, 0, data.Length);
     Compare(result, algo.Hash, testName + "d");
     algo.Initialize();
 }
    void DecryptStream(Stream encryptedStream, Stream output)
    {
        using (BinaryReader reader = new BinaryReader(encryptedStream))
            using (BinaryWriter writer = new BinaryWriter(output))
            {
                //Read file header
                byte[] headerNonce;
                byte[] ciphertextPayload;
                byte[] mac;
                byte[] contentKey;
                byte[] cleartextPayload;

                headerNonce       = reader.ReadBytes(16);
                ciphertextPayload = reader.ReadBytes(40);
                mac = reader.ReadBytes(32);

                HMAC headerHmac = new HMAC(macKey);
                headerHmac.Update(headerNonce);
                headerHmac.DoFinal(ciphertextPayload);
                if (!headerHmac.Hash.SequenceEqual(mac))
                {
                    throw new IOException("Encrypted file fails integrity check.");
                }

                cleartextPayload = AesCtr(ciphertextPayload, masterKey, headerNonce);
                contentKey       = Slice(cleartextPayload, 8, 32);

                HMAC chunkHmac = new HMAC(macKey);

                //Process all chunks
                for (int blocknum = 0; ; ++blocknum)
                {
                    //read file content payload
                    byte[] chunk;
                    chunk = reader.ReadBytes(32768 + 48);
                    if (chunk.Length == 0)
                    {
                        break;
                    }

                    var chunkNonce   = Slice(chunk, 0, 16);
                    var chunkpayload = Slice(chunk, chunkNonce.Length, chunk.Length - 48);
                    var chunkmac     = Slice(chunk, chunkNonce.Length + chunkpayload.Length, 32);


                    byte[] beBlockNum = BitConverter.GetBytes((long)blocknum);
                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(beBlockNum);
                    }

                    chunkHmac.Initialize();
                    chunkHmac.Update(headerNonce);
                    chunkHmac.Update(beBlockNum);
                    chunkHmac.Update(chunkNonce);
                    chunkHmac.DoFinal(chunkpayload);
                    if (!chunkHmac.Hash.SequenceEqual(chunkmac))
                    {
                        throw new IOException("Encrypted file fails integrity check.");
                    }

                    var decryptedContent = AesCtr(chunkpayload, contentKey, chunkNonce);
                    writer.Write(decryptedContent);
                }
            }
    }
Esempio n. 30
0
 private static byte[] hmacSha(byte[] data, HMAC hmac)
 {
     hmac.Initialize();
     return(hmac.ComputeHash(data));
 }