static void EncodeFile(byte[] key, String sourceFile, string destFile)
        {
            // initialize keyed hash object
            HMACSHA1 hms = new HMACSHA1(key);

            // open filestreams to read in original file and write out coded file
            using(FileStream inStream = new FileStream(sourceFile,FileMode.Open))
            using (FileStream outStream = new FileStream(destFile, FileMode.Create))
            {
                // array to hold keyed hash value of original file
                byte[] hashValue = hms.ComputeHash(inStream);

                // reset instream ready to read original file contents from start
                inStream.Position = 0;

                // write keyed hash value to coded file
                outStream.Write(hashValue, 0, hashValue.Length);

                // copy data from original file to output file, 1K at a time
                int bytesRead;
                byte[] buffer = new byte[1024];
                do
                {
                    bytesRead = inStream.Read(buffer, 0, 1024);
                    outStream.Write(buffer, 0, bytesRead);
                } while (bytesRead > 0);
                hms.Clear();

                inStream.Close();
                outStream.Close();
            }
        }
 public static byte[] ComputeCombinedKey(byte[] requestorEntropy, byte[] issuerEntropy, int keySizeInBits)
 {
     if (requestorEntropy == null)
     {
         throw new ArgumentNullException("requestorEntropy");
     }
     if (issuerEntropy == null)
     {
         throw new ArgumentNullException("issuerEntropy");
     }
     int num = ValidateKeySizeInBytes(keySizeInBits);
     byte[] array = new byte[num];
     
     using (KeyedHashAlgorithm algorithm = new HMACSHA1())
     {
         algorithm.Key = requestorEntropy;
         byte[] buffer = issuerEntropy;
         byte[] buffer3 = new byte[(algorithm.HashSize / 8) + buffer.Length];
         byte[] buffer4 = null;
         try
         {
             try
             {
                 int num2 = 0;
                 while (num2 < num)
                 {
                     algorithm.Initialize();
                     buffer = algorithm.ComputeHash(buffer);
                     buffer.CopyTo(buffer3, 0);
                     issuerEntropy.CopyTo(buffer3, buffer.Length);
                     algorithm.Initialize();
                     buffer4 = algorithm.ComputeHash(buffer3);
                     for (int i = 0; i < buffer4.Length; i++)
                     {
                         if (num2 >= num)
                         {
                             continue;
                         }
                         array[num2++] = buffer4[i];
                     }
                 }
             }
             catch
             {
                 Array.Clear(array, 0, array.Length);
                 throw;
             }
             return array;
         }
         finally
         {
             if (buffer4 != null)
             {
                 Array.Clear(buffer4, 0, buffer4.Length);
             }
             Array.Clear(buffer3, 0, buffer3.Length);
             algorithm.Clear();
         }
     }
 }
Пример #3
0
 protected override void Dispose(bool disposing)
 {
     Array.Clear(_buffer, 0, _buffer.Length);
     Array.Clear(_salt, 0, _salt.Length);
     _hmac.Clear();
     base.Dispose(disposing);
 }
Пример #4
0
 public string ComputeSignature(string signatureBase, string consumerSecret, string tokenSecret)
 {
     using (HMACSHA1 crypto = new HMACSHA1()) {
         string key = Rfc3986.Encode(consumerSecret) + "&" + Rfc3986.Encode(tokenSecret);
         crypto.Key = Encoding.ASCII.GetBytes(key);
         string hash = Convert.ToBase64String(crypto.ComputeHash(Encoding.ASCII.GetBytes(signatureBase)));
         crypto.Clear();
         return hash;
     }
 }
Пример #5
0
        private string GetHashString(string sPassword, string salt)
        {
            HashAlgorithm hash = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(salt));

            byte[] hashBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(sPassword));

            hash.Clear();

            return(BitConverter.ToString(hashBytes).Replace("-", string.Empty).ToLower());
        }
Пример #6
0
        public byte[] doFinal()
        {
            //return mac.doFinal();
            cs.Close();
            byte[] result = mentalis_mac.Hash;
            byte[] key    = mentalis_mac.Key;
            mentalis_mac.Clear();
            init(key);

            return(result);
        }
Пример #7
0
        public byte[] doFinal()
        {
            //Console.WriteLine("Sha1");
            //return mac.doFinal();
            cs.Close();
            byte[] result = mentalis_mac.Hash;
            byte[] key    = mentalis_mac.Key;
            mentalis_mac.Clear();
            init(key);

            return(result);
        }
Пример #8
0
 public static byte[] Encriptar(string strTexto, byte[] objKey)
 {
     HMACSHA1 _objHMACSHA = new HMACSHA1(objKey);
     try
     {
         return _objHMACSHA.ComputeHash(Encoding.UTF8.GetBytes(strTexto));
     }
     finally
     {
         _objHMACSHA.Clear();
     }
 }
Пример #9
0
        public new void Dispose()
        {
            if (!m_Disposed)
            {
                m_Disposed = true;
                m_md5.Clear();
                m_sha1.Clear();

                Array.Clear(m_s1, 0, m_s1.Length);
                Array.Clear(m_s2, 0, m_s2.Length);
                Array.Clear(m_ls, 0, m_ls.Length);
            }
        }
Пример #10
0
        private bool Verify(int version, string privateMac, string privateHash,
                            string passphrase, string keyTypeName, string encryptionName, string comment, byte[] publicBlob, byte[] privateBlob)
        {
            byte[] macData;
            using (MemoryStream macDataBuff = new MemoryStream())
            {
                if (version == 1)
                {
                    WriteMacData(macDataBuff, privateBlob);
                }
                else
                {
                    WriteMacData(macDataBuff, keyTypeName);
                    WriteMacData(macDataBuff, encryptionName);
                    WriteMacData(macDataBuff, comment);
                    WriteMacData(macDataBuff, publicBlob);
                    WriteMacData(macDataBuff, privateBlob);
                }
                macDataBuff.Close();
                macData = macDataBuff.ToArray();
            }

            if (privateMac != null)
            {
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                byte[] a = Encoding.ASCII.GetBytes("putty-private-key-file-mac-key");
                sha1.TransformBlock(a, 0, a.Length, null, 0);
                byte[] b = Encoding.UTF8.GetBytes(passphrase);
                sha1.TransformFinalBlock(b, 0, b.Length);
                byte[] key = sha1.Hash;
                sha1.Clear();

                System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(key);
                byte[] hash = hmacsha1.ComputeHash(macData);
                hmacsha1.Clear();
                string mac = BinToHex(hash);
                return(mac == privateMac);
            }
            else if (privateHash != null)
            {
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                byte[] hash = sha1.ComputeHash(macData);
                sha1.Clear();
                string mac = BinToHex(hash);
                return(mac == privateHash);
            }
            else
            {
                return(true);
            }
        }
Пример #11
0
 public static string GetExpiringHMAC(string message, DateTime expiryDate)
 {
     HMAC alg = new HMACSHA1(Key);
     try
     {
         string input = expiryDate.Ticks + message;
         byte[] hashBytes = alg.ComputeHash(Encoding.UTF8.GetBytes(input));
         byte[] result = new byte[8 + hashBytes.Length];
         hashBytes.CopyTo(result, 8);
         BitConverter.GetBytes(expiryDate.Ticks).CopyTo(result, 0);
         return Swap(Convert.ToBase64String(result), "+=/", "-_,");
     }
     finally { alg.Clear(); }
 }
Пример #12
0
        /// <summary>
        /// Get the Cart Signature used in the &quot;signature&quot;
        /// form field that is posted to Google Checkout.
        /// </summary>
        /// <param name="cart">The Cart Xml returned from the
        /// <see cref="GCheckout.Checkout.CheckoutShoppingCartRequest.GetXml"/>
        /// method.</param>
        /// <param name="merchantKey">Your Google Merchant Key</param>
        /// <returns>A Base64 encoded string of the cart signature</returns>
        public static string GetCartSignature(byte[] cart, string merchantKey)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] key = encoding.GetBytes(merchantKey);

            using (System.Security.Cryptography.HMACSHA1 cryptobj = new
                                                                    System.Security.Cryptography.HMACSHA1(key)) {
                string retVal =
                    System.Convert.ToBase64String(cryptobj.ComputeHash(cart));

                cryptobj.Clear();
                return(retVal);
            }
        }
Пример #13
0
 /// <summary>
 /// Authenticate packet and return authentication parameters value to the caller
 /// </summary>
 /// <param name="authenticationSecret">User authentication secret</param>
 /// <param name="engineId">SNMP agent authoritative engine id</param>
 /// <param name="wholeMessage">Message to authenticate</param>
 /// <returns>Authentication parameters value</returns>
 public byte[] authenticate(byte[] authenticationSecret, byte[] engineId, byte[] wholeMessage)
 {
     byte[] result = new byte[12];
     byte[] authKey = PasswordToKey(authenticationSecret, engineId);
     HMACSHA1 sha = new HMACSHA1(authKey);
     byte[] hash = sha.ComputeHash(wholeMessage);
     // copy 12 bytes of the hash into the wholeMessage
     for (int i = 0; i < 12; i++)
     {
         result[i] = hash[i];
     }
     sha.Clear(); // release resources
     return result;
 }
Пример #14
0
		public virtual void onButtonClick(object sender, EventArgs e) {
			
			// The HMAC secret as configured in the skin
			string hmacSecret = "TheHM4C$ecretF0rTheSk1n";

			// Generate the signing string
			string signingString =  paymentAmount.Text + currencyCode.Text + shipBeforeDate.Text 
									+ merchantReference.Text + skinCode.Text + merchantAccount.Text 
									+ sessionValidity.Text + shopperEmail.Text;
			
			// Values are always transferred using UTF-8 encoding
			System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
			
			// Calculate the HMAC
	        HMACSHA1 myhmacsha1 = new HMACSHA1(encoding.GetBytes(hmacSecret));
	        merchantSig.Text = System.Convert.ToBase64String(myhmacsha1.ComputeHash(encoding.GetBytes(signingString)));
			myhmacsha1.Clear();
			
			// Ready to pay
			button1.Text = "Pay";
		}
Пример #15
0
 private byte[] computeSignature(String baseString)
 {
     byte[] _key;
     lock (this)
     {
         if (key == null)
         {
             String keyString = Rfc3986.Encode(getConsumerSecret())
                                + "&" + Rfc3986.Encode(getTokenSecret());
             key = Encoding.GetEncoding(ENCODING).GetBytes(keyString);
         }
         _key = key;
     }
     using (HMACSHA1 crypto = new HMACSHA1())
     {
         crypto.Key = _key;
         byte[] hash = crypto.ComputeHash(Encoding.GetEncoding(ENCODING).GetBytes(baseString));
         crypto.Clear();
         return hash;
     }
 }
Пример #16
0
        /// <summary>
        /// Generate a TOTP using provided binary data.
        /// </summary>
        /// <param name="key">Binary data.</param>
        /// <returns>Time-based One Time Password encoded byte array.</returns>
        public byte[] Generate(byte[] key)
        {
            System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(key, true); //Instanciates a new hash provider with a key.
            byte[] hash = hmac.ComputeHash(GetBytes((ulong)Counter));                                          //Generates hash from key using counter.
            hmac.Clear();                                                                                      //Clear hash instance securing the key.

            /*int binary =                                        //Math.
             * ((hash[offset] & 0x7f) << 24)                   //Math.
             | ((hash[offset + 1] & 0xff) << 16)             //Math.
             | ((hash[offset + 2] & 0xff) << 8)              //Math.
             | (hash[offset + 3] & 0xff);                    //Math.
             |
             | int password = binary % (int)Math.Pow(10, length); //Math.*/

            int offset = hash[hash.Length - 1] & 0x0f;           //Math.

            byte[] totp = { hash[offset + 3], hash[offset + 2], hash[offset + 1], hash[offset] };
            return(totp);

            /*
             * return password.ToString(new string('0', length)); //Math.*/
        }
Пример #17
0
        /// <summary>
        /// Generate a TOTP using provided binary data.
        /// </summary>
        /// <param name="key">Binary data.</param>
        /// <returns>Time-based One Time Password encoded byte array.</returns>
        public byte[] Generate(byte[] key)
        {
            System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(key, true); //Instanciates a new hash provider with a key.
            byte[] hash = hmac.ComputeHash(GetBytes((ulong)Counter)); //Generates hash from key using counter.
            hmac.Clear(); //Clear hash instance securing the key.

            /*int binary =                                        //Math.
               ((hash[offset] & 0x7f) << 24)                   //Math.
               | ((hash[offset + 1] & 0xff) << 16)             //Math.
               | ((hash[offset + 2] & 0xff) << 8)              //Math.
               | (hash[offset + 3] & 0xff);                    //Math.

              int password = binary % (int)Math.Pow(10, length); //Math.*/

            int offset = hash[hash.Length - 1] & 0x0f;           //Math.
            byte[] totp = { hash[offset + 3], hash[offset + 2], hash[offset + 1], hash[offset] };
            return totp;

            /*
             return password.ToString(new string('0', length)); //Math.*/
        }
Пример #18
0
        public override int GetHashCode()
        {
            HMACSHA1 hmac = new HMACSHA1(this.Secret);

            CryptoStream cs = new CryptoStream(Stream.Null, hmac,
                    CryptoStreamMode.Write);
            byte[] hbytes = ASCIIEncoding.ASCII.GetBytes(this.handle);
            cs.Write(hbytes, 0, hbytes.Length);
            cs.Close();
            byte[] hash = hmac.Hash;
            hmac.Clear();
            long val = 0;
            for (long i = 0; i < hash.Length; i++)
                val ^= hash[i];
            val ^= this.Expires.ToFileTimeUtc();
            return (int)val;
        }
Пример #19
0
		/// <summary>
		/// Returns the hash code.
		/// </summary>
		/// <returns>
		/// A hash code for the current <see cref="T:System.Object"/>.
		/// </returns>
		public override int GetHashCode() {
			HMACSHA1 hmac = new HMACSHA1(this.SecretKey);
			try {
				CryptoStream cs = new CryptoStream(Stream.Null, hmac, CryptoStreamMode.Write);

				byte[] hbytes = ASCIIEncoding.ASCII.GetBytes(this.Handle);

				cs.Write(hbytes, 0, hbytes.Length);
				cs.Close();

				byte[] hash = hmac.Hash;
				hmac.Clear();

				long val = 0;
				for (int i = 0; i < hash.Length; i++) {
					val = val ^ (long)hash[i];
				}

				val = val ^ this.Expires.ToFileTimeUtc();

				return (int)val;
			} finally {
				((IDisposable)hmac).Dispose();
			}
		}
        private bool Verify(int version, string privateMac, string privateHash,
                string passphrase, string keyTypeName, string encryptionName, string comment, byte[] publicBlob, byte[] privateBlob)
        {
            byte[] macData;
            using (MemoryStream macDataBuff = new MemoryStream()) {
                if (version == 1) {
                    WriteMacData(macDataBuff, privateBlob);
                }
                else {
                    WriteMacData(macDataBuff, keyTypeName);
                    WriteMacData(macDataBuff, encryptionName);
                    WriteMacData(macDataBuff, comment);
                    WriteMacData(macDataBuff, publicBlob);
                    WriteMacData(macDataBuff, privateBlob);
                }
                macDataBuff.Close();
                macData = macDataBuff.ToArray();
            }

            if (privateMac != null) {
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                byte[] a = Encoding.ASCII.GetBytes("putty-private-key-file-mac-key");
                sha1.TransformBlock(a, 0, a.Length, null, 0);
                byte[] b = Encoding.UTF8.GetBytes(passphrase);
                sha1.TransformFinalBlock(b, 0, b.Length);
                byte[] key = sha1.Hash;
                sha1.Clear();

                System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(key);
                byte[] hash = hmacsha1.ComputeHash(macData);
                hmacsha1.Clear();
                string mac = BinToHex(hash);
                return mac == privateMac;
            }
            else if (privateHash != null) {
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                byte[] hash = sha1.ComputeHash(macData);
                sha1.Clear();
                string mac = BinToHex(hash);
                return mac == privateHash;
            }
            else {
                return true;
            }
        }
Пример #21
0
        /// <summary>
        /// Computes the hash.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="data">The scope bytes.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="length">The length bytes.</param>
        /// <returns></returns>
        public OctetString ComputeHash(VersionCode version, ISegment header, SecurityParameters parameters, ISnmpData data, IPrivacyProvider privacy, byte[] length)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }
            
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            
            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            var key = PasswordToKey(_password, parameters.EngineId.GetRaw());
            using (var sha1 = new HMACSHA1(key))
            {
                var hash = sha1.ComputeHash(ByteTool.PackMessage(length, version, header, parameters, data).ToBytes());
                sha1.Clear();
                var result = new byte[DigestLength];
                Buffer.BlockCopy(hash, 0, result, 0, result.Length);
                return new OctetString(result);
            }
        }
Пример #22
0
 private byte[] Sign(NameValueCollection l)
 {
     byte[] data = KVUtil.SeqToKV(l, false);
     HMACSHA1 hmac = new HMACSHA1(this.Secret);
     byte[] hash = hmac.ComputeHash(data);
     hmac.Clear();
     return hash;
 }
Пример #23
0
        private string GetPolicyBase64(string key, string redirectTo, string contentType, string contentDisposition,
                                       long maxUploadSize, out string sign)
        {
            var policyBuilder = new StringBuilder();
            policyBuilder.AppendFormat("{{\"expiration\": \"{0}\",\"conditions\":[",
                                       DateTime.UtcNow.AddMinutes(15).ToString(AWSSDKUtils.ISO8601DateFormat,
                                                                               CultureInfo.InvariantCulture));
            policyBuilder.AppendFormat("{{\"bucket\": \"{0}\"}},", _bucket);
            policyBuilder.AppendFormat("[\"starts-with\", \"$key\", \"{0}\"],", key);
            policyBuilder.Append("{\"acl\": \"public-read\"},");
            if (!string.IsNullOrEmpty(redirectTo))
            {
                policyBuilder.AppendFormat("{{\"success_action_redirect\": \"{0}\"}},", redirectTo);
            }
            policyBuilder.AppendFormat("{{\"success_action_status\": \"{0}\"}},", 201);
            if (!string.IsNullOrEmpty(contentType))
            {
                policyBuilder.AppendFormat("[\"eq\", \"$Content-Type\", \"{0}\"],", contentType);
            }
            if (!string.IsNullOrEmpty(contentDisposition))
            {
                policyBuilder.AppendFormat("[\"eq\", \"$Content-Disposition\", \"{0}\"],", contentDisposition);
            }
            policyBuilder.AppendFormat("[\"content-length-range\", 0, {0}]", maxUploadSize);
            policyBuilder.Append("]}");

            var policyBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(policyBuilder.ToString()));
            //sign = AWSSDKUtils.HMACSign(policyBase64, _secretAccessKeyId, new HMACSHA1());
            var algorithm = new HMACSHA1 { Key = Encoding.UTF8.GetBytes(_secretAccessKeyId) };
            try
            {
                algorithm.Key = Encoding.UTF8.GetBytes(key);
                sign = Convert.ToBase64String(algorithm.ComputeHash(Encoding.UTF8.GetBytes(policyBase64)));
            }
            finally
            {
                algorithm.Clear();
            }

            return policyBase64;
        }
        /// <summary>
        /// Get the Cart Signature used in the &quot;signature&quot;
        /// form field that is posted to Google Checkout.
        /// </summary>
        /// <param name="cart">The Cart Xml returned from the 
        /// <see cref="GCheckout.Checkout.CheckoutShoppingCartRequest.GetXml"/>
        /// method.</param>
        /// <param name="merchantKey">Your Google Merchant Key</param>
        /// <returns>A Base64 encoded string of the cart signature</returns>
        public static string GetCartSignature(byte[] cart, string merchantKey)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
              byte[] key = encoding.GetBytes(merchantKey);

              using (System.Security.Cryptography.HMACSHA1 cryptobj = new
               System.Security.Cryptography.HMACSHA1(key)) {

            string retVal =
              System.Convert.ToBase64String(cryptobj.ComputeHash(cart));

            cryptobj.Clear();
            return retVal;
              }
        }
Пример #25
0
 /// <summary>
 /// Verify SHA-1 authentication of a packet.
 /// </summary>
 /// <param name="authKey">Authentication key (not password)</param>
 /// <param name="authenticationParameters">Authentication parameters extracted from the packet being authenticated</param>
 /// <param name="wholeMessage">Entire packet being authenticated</param>
 /// <returns>True on authentication success, otherwise false</returns>
 public bool authenticateIncomingMsg(byte[] authKey, byte[] authenticationParameters, MutableByte wholeMessage)
 {
     HMACSHA1 sha = new HMACSHA1(authKey);
     byte[] hash = sha.ComputeHash(wholeMessage);
     MutableByte myhash = new MutableByte(hash, 12);
     sha.Clear(); // release resources
     if (myhash.Equals(authenticationParameters))
     {
         return true;
     }
     return false;
 }
Пример #26
0
        /// <summary>
        /// Generate a TOTP using provided binary data.
        /// </summary>
        /// <param name="key">Binary data.</param>
        /// <returns>Time-based One Time Password encoded byte array.</returns>
        public string GenerateByByte(byte[] key)
        {
            HMACSHA1 hmac = new HMACSHA1(key, true); //Instanciates a new hash provider with a key.

            byte[] codeInterval = BitConverter.GetBytes((ulong)Counter);

            if (BitConverter.IsLittleEndian)
                Array.Reverse(codeInterval);

            byte[] hash = hmac.ComputeHash(codeInterval); //Generates hash from key using counter.
            hmac.Clear(); //Clear hash instance securing the key.
            int start = hash[hash.Length - 1] & 0xf;
            byte[] totp = new byte[4];

            Array.Copy(hash, start, totp, 0, 4);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(totp);

            return this.encoder(totp, length);
        }
Пример #27
0
        private byte[] GenerateResponse(byte[] challenge, byte[] key)
        {
            HMACSHA1 hmac = new HMACSHA1(key);

            if (LT64)
                challenge = challenge.Take(challengeLenBytes - 1).ToArray();

            byte[] resp = hmac.ComputeHash(challenge);
            hmac.Clear();
            return resp;
        }