/// <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> /// <returns></returns> public OctetString ComputeHash(VersionCode version, ISegment header, SecurityParameters parameters, ISnmpData data, IPrivacyProvider privacy) { 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"); } byte[] key = PasswordToKey(_password, parameters.EngineId.GetRaw()); using (HMACSHA1 sha1 = new HMACSHA1(key)) { byte[] hash = sha1.ComputeHash(SnmpMessageExtension.PackMessage(version, header, parameters, data).ToBytes()); sha1.Clear(); byte[] result = new byte[DigestLength]; Buffer.BlockCopy(hash, 0, result, 0, result.Length); return(new OctetString(result)); } }
/// <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(); } }
/// <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)); }
protected override void Dispose(bool disposing) { Array.Clear(_buffer, 0, _buffer.Length); Array.Clear(_salt, 0, _salt.Length); _hmac.Clear(); base.Dispose(disposing); }
/// <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(nameof(header)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } if (privacy == null) { throw new ArgumentNullException(nameof(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()); #if NET452 sha1.Clear(); #endif var result = new byte[DigestLength]; Buffer.BlockCopy(hash, 0, result, 0, result.Length); return(new OctetString(result)); } }
public static string GetHamcSha1ToBase64(string content, Encoding contentEncoding, string key, Encoding keyEncoding) { HMACSHA1 hmacSha1 = new HMACSHA1(keyEncoding.GetBytes(key)); byte[] result = hmacSha1.ComputeHash(contentEncoding.GetBytes(content)); hmacSha1.Clear(); return(Convert.ToBase64String(result)); }
/// <summary> /// Authenticate supplied message and return the hashed value /// </summary> /// <param name="data">Data to hash</param> /// <param name="offset">Offset within the data to begin hashing from</param> /// <param name="length">Length of data to hash</param> /// <returns>Hashed value</returns> public byte[] authenticateMessage(byte[] data, int offset, int length) { HMACSHA1 sha = new HMACSHA1(); byte[] res = sha.ComputeHash(data, offset, length); // UPDATE May/12 2009 - release SHA resources before exit sha.Clear(); return(res); }
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); } }
public static string HMACSHA1(string sourceText, string key) { var keyByte = Encoding.UTF8.GetBytes(key); var sourceBytes = Encoding.UTF8.GetBytes(sourceText); using (var hmacSha1 = new HMACSHA1(keyByte)) { var bytes = hmacSha1.ComputeHash(sourceBytes); hmacSha1.Clear(); return(BitConverter.ToString(bytes).Replace("-", "").ToLower()); } }
/// <summary> /// Authenticate message for sending. /// </summary> /// <param name="userPassword">User password</param> /// <param name="engineId">Authoritative engine id</param> /// <param name="wholeMessage">Un-authenticated message with authenticationParameter field set to 12 byte OctetString /// with all bytes initialized to 0x00.</param> /// <param name="authFieldOffset">Offset of the authentication field in the wholeMessage buffer</param> public void authenticateOutgoingMsg(byte[] userPassword, byte[] engineId, MutableByte wholeMessage, int authFieldOffset) { byte[] authKey = PasswordToKey(userPassword, 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++) { wholeMessage[authFieldOffset + i] = hash[i]; } sha.Clear(); // release resources }
public static byte[] CreateHash(string strTexto, byte[] objKey) { HMACSHA1 _objHMACSHA = new HMACSHA1(objKey); try { return(_objHMACSHA.ComputeHash(Encoding.UTF8.GetBytes(strTexto))); } finally { _objHMACSHA.Clear(); } }
// NOTE: .NET 4.0 finally implemented /// <summary> /// Disposes of the object /// </summary> public void Dispose() { base.Salt = new byte[8]; base.IterationCount = 1; //The base doesn't clear the key'd hash, which contains the password in clear text when < 20 bytes FieldInfo f_hmacsha1 = GetType().BaseType.GetField("m_hmacsha1", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField); if (f_hmacsha1 != null) { HMACSHA1 m_hmacsha1 = f_hmacsha1.GetValue(this) as HMACSHA1; m_hmacsha1.Clear(); } }
/// <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) { var sha = new HMACSHA1(authKey); var hash = sha.ComputeHash(wholeMessage); var myhash = new MutableByte(hash, 12); sha.Clear(); // release resources if (myhash.Equals(authenticationParameters)) { return(true); } return(false); }
public 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); }
public static string Encrypt(string strKey, string strSrc) { if (string.IsNullOrEmpty(strKey) || string.IsNullOrEmpty(strSrc)) { return(""); } ASCIIEncoding ascEnc = new ASCIIEncoding(); HMACSHA1 hmacsha1 = new HMACSHA1(ascEnc.GetBytes(strKey)); byte[] hashValue = hmacsha1.ComputeHash(ascEnc.GetBytes(strSrc)); hmacsha1.Clear(); return(Convert.ToBase64String(hashValue)); }
public string Execute(string signingString) { if (string.IsNullOrEmpty(signingString)) { throw new ArgumentException("signingString"); } var hmac = new HMACSHA1(Encoding.GetBytes(SharedSecret)); var mac = Convert.ToBase64String(hmac.ComputeHash(Encoding.GetBytes(signingString))); hmac.Clear(); return(mac); }
/// <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) { var result = new byte[12]; var authKey = PasswordToKey(authenticationSecret, engineId); var sha = new HMACSHA1(authKey); var hash = sha.ComputeHash(wholeMessage); // copy 12 bytes of the hash into the wholeMessage for (var i = 0; i < 12; i++) { result[i] = hash[i]; } sha.Clear(); // release resources return(result); }
public static string GetHamcSha1ToHexString(string content, Encoding contentEncoding, string key, Encoding keyEncoding) { HMACSHA1 hmacSha1 = new HMACSHA1(keyEncoding.GetBytes(key)); byte[] result = hmacSha1.ComputeHash(contentEncoding.GetBytes(content)); hmacSha1.Clear(); var hexStr = new StringBuilder(); foreach (byte b in result) { hexStr.Append(b.ToString("x2")); // to lower } return(hexStr.ToString()); }
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(); } }
/// <summary> /// Verifies correct SHA-1 authentication of the frame. Prior to calling this method, you have to extract authentication /// parameters from the wholeMessage and reset authenticationParameters field in the USM information block to 12 0x00 /// values. /// </summary> /// <param name="userPassword">User password</param> /// <param name="engineId">Authoritative engine id</param> /// <param name="authenticationParameters">Extracted USM authentication parameters</param> /// <param name="wholeMessage">Whole message with authentication parameters zeroed (0x00) out</param> /// <returns>True if message authentication has passed the check, otherwise false</returns> public bool authenticateIncomingMsg(byte[] userPassword, byte[] engineId, byte[] authenticationParameters, MutableByte wholeMessage) { byte[] authKey = PasswordToKey(userPassword, engineId); 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); }
/// <summary> /// Authenticate packet and return authentication parameters value to the caller /// </summary> /// <param name="authKey">Authentication key (not password)</param> /// <param name="wholeMessage">Message to authenticate</param> /// <returns>Authentication parameters value</returns> public byte[] authenticate(byte[] authKey, byte[] wholeMessage) { byte[] result = new byte[12]; 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); }
/// <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="scopeBytes">The scope bytes.</param> /// <param name="privacy">The privacy provider.</param> /// <returns></returns> private OctetString ComputeHash(VersionCode version, ISegment header, SecurityParameters parameters, ISnmpData scopeBytes, IPrivacyProvider privacy) { if (scopeBytes == null) { throw new ArgumentNullException("scopeBytes"); } byte[] key = PasswordToKey(_password, parameters.EngineId.GetRaw()); using (HMACSHA1 sha1 = new HMACSHA1(key)) { byte[] hash = sha1.ComputeHash(SnmpMessageExtension.PackMessage(version, header, parameters, scopeBytes, privacy).ToBytes()); sha1.Clear(); byte[] result = new byte[DigestLength]; Array.Copy(hash, result, result.Length); return(new OctetString(result)); } }
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> /// 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); #if !NETCOREAPP11 && !NETSTANDARD15 sha.Clear(); // release resources #else sha.Dispose(); #endif if (myhash.Equals(authenticationParameters)) { return(true); } return(false); }
/// <summary> /// Authenticate packet and return authentication parameters value to the caller /// </summary> /// <param name="authKey">Authentication key (not password)</param> /// <param name="wholeMessage">Message to authenticate</param> /// <returns>Authentication parameters value</returns> public byte[] authenticate(byte[] authKey, byte[] wholeMessage) { byte[] result = new byte[12]; 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]; } #if !NETCOREAPP11 && !NETSTANDARD15 sha.Clear(); // release resources #else sha.Dispose(); #endif return(result); }
public static string Encriptar_PWD(string strTexto) { string sResult = ""; try { byte[] bKey = Encoding.UTF8.GetBytes(KeyMaster); HMACSHA1 _objHMACSHA = new HMACSHA1(bKey); byte[] bResult = _objHMACSHA.ComputeHash(Encoding.UTF8.GetBytes(strTexto)); sResult = Convert.ToBase64String(bResult); _objHMACSHA.Clear(); } catch (Exception ex) { sResult = ""; } return(sResult); }
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); } }
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"; }
public string EncodeFile(string stringkey, String input) { byte[] key = Encoding.UTF8.GetBytes(stringkey); // Initialize the keyed hash object. HMACSHA1 myhmacsha1 = new HMACSHA1(key); byte[] inStream1 = Encoding.UTF8.GetBytes(input);// Convert.FromBase64String(input); MemoryStream inStream = new MemoryStream(); //MemoryStream outStream = new MemoryStream(); // FileStream inStream = new FileStream(sourceFile, FileMode.Open); //FileStream outStream = new FileStream(destFile, FileMode.Create); // Compute the hash of the input file. byte[] hashValue = myhmacsha1.ComputeHash(inStream1); // Reset inStream to the beginning of the file. //inStream.Position = 0; string rv = Convert.ToBase64String(hashValue); // Write the computed hash value to the output file. //outStream.Write(hashValue, 0, hashValue.Length); //StreamReader reader = new StreamReader(outStream); //string rv = reader.ReadToEnd(); myhmacsha1.Clear(); // Close the streams inStream.Close(); //state += "orig sig" + rv; //outStream.Close(); //string safeRv = MakeUrlSafe(rv); //state += " safe sig" + safeRv; return(rv); //return safeRv; } // end EncodeFile
} //compute hash from arguments and return hash value as string private static string GetHMACSHA1Hash(string text) { //create variables for computing hash and making it a string UnicodeEncoding UniCode = new UnicodeEncoding(); byte[] HashResult; byte[] msg = UniCode.GetBytes(text); HMACSHA1 hashString = new HMACSHA1(); string Str = ""; //compute hash with HMACSHA1 module and format output as string //convert bytes in HashResult to string values HashResult = hashString.ComputeHash(msg); foreach (byte x in HashResult) { Str += String.Format("{0:x2}", x); } //clear excess resource usage hashString.Clear(); return(Str); } //compute hash from arguments and return hash value as string
/// <summary> /// Computes the hash. /// </summary> /// <param name="buffer"></param> /// <param name="engineId"></param> /// <returns></returns> public OctetString ComputeHash(byte[] buffer, OctetString engineId) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (engineId == null) { throw new ArgumentNullException("engineId"); } var key = PasswordToKey(_password, engineId.GetRaw()); using (var sha1 = new HMACSHA1(key)) { var hash = sha1.ComputeHash(buffer); sha1.Clear(); var result = new byte[DigestLength]; Buffer.BlockCopy(hash, 0, result, 0, result.Length); return(new OctetString(result)); } }
static string MakeOAuthSignature(string compositeSigningKey, string signatureBase) { using (HMACSHA1 crypto = new HMACSHA1()) { byte[] bkey = Encoding.ASCII.GetBytes(compositeSigningKey); // Keys longer than 60 characters aparently do not work with OpenNetCF... if (bkey.Length > 60) { bkey = (new System.Security.Cryptography.SHA1CryptoServiceProvider()).ComputeHash(bkey); } crypto.Key = bkey; string hash = Convert.ToBase64String(crypto.ComputeHash(Encoding.ASCII.GetBytes(signatureBase))); crypto.Clear(); return hash; } }