public void ComputeHash_WithKey_ExceptionTest() { HmacSha256 hmac = new HmacSha256(); Exception ex = Assert.Throws <ArgumentNullException>(() => hmac.ComputeHash(null, new byte[1])); Assert.Contains("Data can not be null", ex.Message); ex = Assert.Throws <ArgumentNullException>(() => hmac.ComputeHash(new byte[1], null)); Assert.Contains("Key can not be null", ex.Message); hmac.Dispose(); ex = Assert.Throws <ObjectDisposedException>(() => hmac.ComputeHash(new byte[1], new byte[1])); }
public void ComputeHash_Reuse_Test(byte[] key1, byte[] data1_1, byte[] exp1_1, byte[] data1_2, byte[] exp1_2, byte[] key2, byte[] data2_1, byte[] exp2_1, byte[] data2_2, byte[] exp2_2) { using HmacSha256 hmac = new HmacSha256(); byte[] actual1_1 = hmac.ComputeHash(data1_1, key1); Assert.Equal(exp1_1, actual1_1); byte[] actual2_1 = hmac.ComputeHash(data2_1, key2); // use different key on each call Assert.Equal(exp2_1, actual2_1); byte[] actual1_2 = hmac.ComputeHash(data1_2, key1); Assert.Equal(exp1_2, actual1_2); byte[] actual2_2 = hmac.ComputeHash(data2_2, key2); Assert.Equal(exp2_2, actual2_2); }
private static byte[] HKDF(byte[] salt, byte[] prk, byte[] info, int length) { var hmac = new HmacSha256(salt); var key = hmac.ComputeHash(prk); return(HKDFSecondStep(key, info, length)); }
public void ComputeHash_ExceptionTest() { HmacSha256 hmac = new HmacSha256(); Exception ex = Assert.Throws <ArgumentNullException>(() => hmac.ComputeHash(null)); Assert.Contains("Data can not be null", ex.Message); ex = Assert.Throws <ArgumentNullException>(() => hmac.ComputeHash(new byte[1])); Assert.Contains("Key must be set before calling this function", ex.Message); hmac.Key = new byte[1]; ex = Assert.Throws <ArgumentNullException>(() => hmac.ComputeHash(null)); Assert.Contains("Data can not be null", ex.Message); hmac.Dispose(); ex = Assert.Throws <ObjectDisposedException>(() => hmac.ComputeHash(new byte[1])); }
public void ComputeHash_CtorKey_ReuseTest(byte[] key1, byte[] data1_1, byte[] exp1_1, byte[] data1_2, byte[] exp1_2, byte[] key2, byte[] data2_1, byte[] exp2_1, byte[] data2_2, byte[] exp2_2) { using HmacSha256 hmac = new HmacSha256(key1); byte[] actual1_1 = hmac.ComputeHash(data1_1); Assert.Equal(exp1_1, actual1_1); byte[] actual1_2 = hmac.ComputeHash(data1_2); Assert.Equal(exp1_2, actual1_2); // change key hmac.Key = key2; byte[] actual2_1 = hmac.ComputeHash(data2_1); Assert.Equal(exp2_1, actual2_1); byte[] actual2_2 = hmac.ComputeHash(data2_2); Assert.Equal(exp2_2, actual2_2); }
public void ComputeHash_Empty_WithKey_Test(byte[] key, byte[] data) { using var sysHmac = new System.Security.Cryptography.HMACSHA256(key); byte[] expected = sysHmac.ComputeHash(data); using HmacSha256 hmac = new HmacSha256(); byte[] actual = hmac.ComputeHash(data, key); Assert.Equal(expected, actual); }
public void ComputeHash_NIST_CtorKey_Test(byte[] msg, byte[] key, byte[] expected, int len, bool truncate) { using HmacSha256 hmac = new HmacSha256(key); byte[] actual = hmac.ComputeHash(msg); if (truncate) { byte[] temp = new byte[len]; Buffer.BlockCopy(actual, 0, temp, 0, len); actual = temp; } Assert.Equal(expected, actual); }
public static String GetSASToken(String baseAddress, String SASKeyName, String SASKeyValue) { TimeSpan fromEpochStart = DateTime.UtcNow - new DateTime(1970, 1, 1); String expiry = Convert.ToString((Int32)fromEpochStart.TotalSeconds + 3600); String stringToSign = WebUtility.UrlEncode(baseAddress) + "\n" + expiry; HmacSha256 hmac = new HmacSha256(Encoding.UTF8.GetBytes(SASKeyValue)); String signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign))); String sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", WebUtility.UrlEncode(baseAddress), WebUtility.UrlEncode(signature), expiry, SASKeyName); return(sasToken); }
private static byte[] HKDFSecondStep(byte[] key, byte[] info, int length) { var hmac = new HmacSha256(key); var infoAndOne = info.Concat(new byte[] { 0x01 }).ToArray(); var result = hmac.ComputeHash(infoAndOne); if (result.Length > length) { Array.Resize(ref result, length); } return(result); }
/// <summary> /// This method handles when the user press the Register button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> async void btnRegister_Clicked(object sender, EventArgs e) { Activity.IsRunning = true; //We check if fields are entered properly if (String.IsNullOrEmpty(email.Text) && String.IsNullOrEmpty(username.Text) && String.IsNullOrEmpty(password.Text)) { await DisplayAlert("Oops", "Please fill in the fields", "OK"); } //We are using EmailValidatorBehavior to check if the email entered is correct using Regex [changes to red when wrong] //Display Alert if email is wrong else if (email.TextColor == Color.Red) { await DisplayAlert("Oops", "Invalid Email address", "OK"); } else { //Initialising........Storing text/data from the Entry fields string newEmail = email.Text; string newUser = username.Text; //Initailizing data to begin our HmacSHA256 encryption on the password //Our private key byte[] shaKey = Encoding.UTF8.GetBytes("test"); //Encode password.... //We first have to convert password to byte format byte[] newPassword = Encoding.UTF8.GetBytes(password.Text); //Encode password to sha256 HmacSha256 newHash256 = new HmacSha256(newPassword); byte[] newHashPassword = newHash256.ComputeHash(newPassword); //Read our password as a string this allows us to add it to our JSON file string newStringHashPassword = BitConverter.ToString(newHashPassword); //Creates a new user object and uses the data from the user and creates a JSON formatted data structure User NewUser = User.CreateUserFromJson("{\"Username\":\"" + newUser + "\", \"Email\":\"" + newEmail + "\", \"Password\":\"" + newStringHashPassword + "\"}"); /* Passes NewUser object with our JSON format to the RegisterJson object * RegisterJson object contains the method Save() which contacts the server */ ServerJson userjson = new ServerJson(); userjson.Save(NewUser); //Registration finished pop up await DisplayAlert("Alert", "User Registered", "OK"); await Navigation.PushModalAsync(new LoginPage()); } Activity.IsRunning = false; }
/// <summary> /// This method handles when the users press the login button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> async void btnLogin_Clicked(object sender, EventArgs e) { //Acitvity indicator Activity.IsRunning = true; ServerJson checkUser = new ServerJson(); //Checking for empty fields Debug.WriteLine("Check for Empty fields"); if (String.IsNullOrWhiteSpace(username.Text) || (String.IsNullOrWhiteSpace(password.Text))) { await DisplayAlert("Oops", "Please fill in the fields", "OK"); } else { //Initailizing data to begin our HmacSHA256 encryption on the password //Our private key byte[] shaKey = Encoding.UTF8.GetBytes("test"); //Encode password.... //We first have to convert password to byte format byte[] newPassword = Encoding.UTF8.GetBytes(password.Text); //Encode password to sha256 HmacSha256 newHash256 = new HmacSha256(newPassword); byte[] newHashPassword = newHash256.ComputeHash(newPassword); //Read our password as a string this allows us to add it to our JSON file string newStringHashPassword = BitConverter.ToString(newHashPassword); //Check if user password and username match Method is called in ServerJson.cs Debug.WriteLine("Check true of false for matching username and password"); bool result = await checkUser.CheckUserPasswordAsync(username.Text, newStringHashPassword); if (result == true) { //If result is true we log the user in and store it's username in data Application.Current.Properties["LoggedInUser"] = username.Text; await Application.Current.SavePropertiesAsync(); //Push user to mainpage after login await Navigation.PushModalAsync(new MainPage()); } if (result == false) { await DisplayAlert("Oops", "Invalid Login Credentials", "Ok"); } } Activity.IsRunning = false; }
/// <summary> /// Encrypts a message with this public key using Elliptic Curve Integrated Encryption Scheme (ECIES) /// with AES-128-CBC as cipher and HMAC-SHA256 as MAC. /// </summary> /// <exception cref="ArgumentNullException"/> /// <param name="message">Message to encrypt</param> /// <param name="magic"> /// [Default value = BIE1] /// A magic string added to encrypted result before computing its HMAC-SHA256 /// </param> /// <returns>Encrypted result as a base-64 encoded string</returns> public string Encrypt(string message, string magic = "BIE1") { if (message is null) { throw new ArgumentNullException(nameof(message), "Mesage can not be null."); } if (magic is null) { throw new ArgumentNullException(nameof(magic), "Magic can not be null."); } byte[] magicBytes = Encoding.UTF8.GetBytes(magic); // TODO: investigate if this can become deterministic (it can't be based on message or pubkey // otherwise the ephemeral key is revealed) using SharpRandom rng = new SharpRandom(); using PrivateKey ephemeral = new PrivateKey(rng); byte[] ecdhKey = new PublicKey(calc.Multiply(ephemeral.ToBigInt(), point)).ToByteArray(true); using Sha512 sha512 = new Sha512(); byte[] key = sha512.ComputeHash(ecdhKey); using Aes aes = new AesManaged { KeySize = 128, Key = key.SubArray(16, 16), Mode = CipherMode.CBC, IV = key.SubArray(0, 16), Padding = PaddingMode.PKCS7 }; using ICryptoTransform encryptor = aes.CreateEncryptor(); using MemoryStream encStream = new MemoryStream(); using CryptoStream cryptStream = new CryptoStream(encStream, encryptor, CryptoStreamMode.Write); using (StreamWriter swEncrypt = new StreamWriter(cryptStream)) { swEncrypt.Write(message); } byte[] encrypted = magicBytes.ConcatFast(ephemeral.ToPublicKey().ToByteArray(true)).ConcatFast(encStream.ToArray()); using HmacSha256 hmac = new HmacSha256(); byte[] mac = hmac.ComputeHash(encrypted, key.SubArray(32)); return(encrypted.ConcatFast(mac).ToBase64()); }
public void Test_HmacSha256() { // http://tools.ietf.org/html/rfc4868#section-2.7.1 { var key = NetworkConverter.FromHexString("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); var value = NetworkConverter.FromHexString("4869205468657265"); using (MemoryStream stream = new MemoryStream(value)) { var s = NetworkConverter.ToHexString(HmacSha256.ComputeHash(stream, key)); } using (HMACSHA256 hmacSha256 = new HMACSHA256(key)) { var s = NetworkConverter.ToHexString(hmacSha256.ComputeHash(value)); } } var list = new List <int>(); list.Add(1); list.Add(64); list.Add(128); byte[] buffer = new byte[1024 * 32]; _random.NextBytes(buffer); for (int i = 0; i < list.Count; i++) { byte[] key = new byte[list[i]]; _random.NextBytes(key); using (MemoryStream stream1 = new MemoryStream(buffer)) using (MemoryStream stream2 = new MemoryStream(buffer)) { using (HMACSHA256 hmacSha256 = new HMACSHA256(key)) { Assert.IsTrue(Unsafe.Equals(hmacSha256.ComputeHash(stream1), HmacSha256.ComputeHash(stream2, key))); } } } }
/// <summary> /// Generates a deterministic random value k (used for signatures) based on data that is being /// signed and private key value. /// </summary> /// <remarks> /// Source: https://tools.ietf.org/html/rfc6979#section-3.2 /// </remarks> /// <param name="data">Hashed data (it needs to be hashed by the caller using the appropriate hash function).</param> /// <param name="keyBytes">Private key bytes to use for signing (must be fixed 32 bytes, pad if needed).</param> /// <param name="extraEntropy">An extra entropy (can be null)</param> /// <returns>A deterministic random K.</returns> public BigInteger GetK(byte[] data, byte[] keyBytes, byte[] extraEntropy) { // Step a (compute hash of message) is performed by the caller // b. byte[] v = new byte[32]; ((Span <byte>)v).Fill(1); // c. byte[] k = new byte[32]; // d. // K = HMAC_K(V || 0x01 || int2octets(x) || bits2octets(h1)) int entLen = extraEntropy is null ? 0 : extraEntropy.Length; // 97 = 32 + 1 + 32 + 32 byte[] bytesToHash = new byte[97 + entLen]; byte[] dataBa = (data.ToBigInt(true, true) % order).ToByteArray(true, true); Buffer.BlockCopy(v, 0, bytesToHash, 0, 32); // Set item at index 32 to 0x00 Buffer.BlockCopy(keyBytes, 0, bytesToHash, 33, 32); Buffer.BlockCopy(dataBa, 0, bytesToHash, 97 - dataBa.Length, dataBa.Length); if (!(extraEntropy is null)) { Buffer.BlockCopy(extraEntropy, 0, bytesToHash, 97, extraEntropy.Length); } k = HmacK.ComputeHash(bytesToHash, k); // e. v = HmacK.ComputeHash(v, k); // f. Buffer.BlockCopy(v, 0, bytesToHash, 0, 32); // Set item at index 33 to 0x01 this time bytesToHash[32] = 0x01; k = HmacK.ComputeHash(bytesToHash, k); // g. v = HmacK.ComputeHash(v, k); while (true) { // h.1. & h.2. // Since hashLen is always equal to qLen there is no need for 2 steps // v is 32 bytes and T=byte[0] | V is 32 bytes too v = HmacK.ComputeHash(v, k); // h.3. BigInteger kTemp = BitsToInt(v); if (kTemp != 0 && kTemp < order) { return(kTemp); } else { k = HmacK.ComputeHash(v.AppendToEnd(0), k); v = HmacK.ComputeHash(v, k); } } }
public override void Send(Stream stream, TimeSpan timeout, Information options) { if (_disposed) { throw new ObjectDisposedException(this.GetType().FullName); } if (stream == null) { throw new ArgumentNullException("stream"); } if (stream.Length == 0) { throw new ArgumentOutOfRangeException("stream"); } if (!_connect) { throw new ConnectionException(); } lock (_sendLock) { try { using (RangeStream targetStream = new RangeStream(stream, stream.Position, stream.Length - stream.Position, true)) { if (_version.HasFlag(SecureConnectionVersion.Version3)) { using (BufferStream bufferStream = new BufferStream(_bufferManager)) { bufferStream.SetLength(8); bufferStream.Seek(8, SeekOrigin.Begin); if (_informationVersion3.CryptoAlgorithm.HasFlag(SecureVersion3.CryptoAlgorithm.Aes256)) { byte[] iv = new byte[16]; _random.GetBytes(iv); bufferStream.Write(iv, 0, iv.Length); using (var aes = Aes.Create()) { aes.KeySize = 256; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; using (CryptoStream cs = new CryptoStream(new WrapperStream(bufferStream, true), aes.CreateEncryptor(_informationVersion3.MyCryptoKey, iv), CryptoStreamMode.Write)) { byte[] sendBuffer = null; try { sendBuffer = _bufferManager.TakeBuffer(1024 * 4); int i = -1; while ((i = targetStream.Read(sendBuffer, 0, sendBuffer.Length)) > 0) { cs.Write(sendBuffer, 0, i); } } finally { if (sendBuffer != null) { _bufferManager.ReturnBuffer(sendBuffer); } } } } } else { throw new ConnectionException(); } _totalSendSize += (bufferStream.Length - 8); bufferStream.Seek(0, SeekOrigin.Begin); byte[] totalSendSizeBuff = NetworkConverter.GetBytes(_totalSendSize); bufferStream.Write(totalSendSizeBuff, 0, totalSendSizeBuff.Length); if (_informationVersion3.HashAlgorithm.HasFlag(SecureVersion3.HashAlgorithm.Sha256)) { bufferStream.Seek(0, SeekOrigin.Begin); byte[] hmacBuff = HmacSha256.ComputeHash(bufferStream, _informationVersion3.MyHmacKey); bufferStream.Seek(0, SeekOrigin.End); bufferStream.Write(hmacBuff, 0, hmacBuff.Length); } else { throw new ConnectionException(); } bufferStream.Seek(0, SeekOrigin.Begin); _connection.Send(bufferStream, timeout, options); } } else { throw new ConnectionException(); } } } catch (ConnectionException e) { throw e; } catch (Exception e) { throw new ConnectionException(e.Message, e); } } }
public override Stream Receive(TimeSpan timeout, Information options) { if (_disposed) { throw new ObjectDisposedException(this.GetType().FullName); } if (!_connect) { throw new ConnectionException(); } lock (_receiveLock) { try { if (_version.HasFlag(SecureConnectionVersion.Version3)) { using (Stream stream = _connection.Receive(timeout, options)) { byte[] totalReceiveSizeBuff = new byte[8]; if (stream.Read(totalReceiveSizeBuff, 0, totalReceiveSizeBuff.Length) != totalReceiveSizeBuff.Length) { throw new ConnectionException(); } long totalReceiveSize = NetworkConverter.ToInt64(totalReceiveSizeBuff); if (_informationVersion3.HashAlgorithm.HasFlag(SecureVersion3.HashAlgorithm.Sha256)) { const int hashLength = 32; _totalReceiveSize += (stream.Length - (8 + hashLength)); if (totalReceiveSize != _totalReceiveSize) { throw new ConnectionException(); } byte[] otherHmacBuff = new byte[hashLength]; stream.Seek(-hashLength, SeekOrigin.End); if (stream.Read(otherHmacBuff, 0, otherHmacBuff.Length) != otherHmacBuff.Length) { throw new ConnectionException(); } stream.SetLength(stream.Length - hashLength); stream.Seek(0, SeekOrigin.Begin); byte[] myHmacBuff = HmacSha256.ComputeHash(stream, _informationVersion3.OtherHmacKey); if (!Unsafe.Equals(otherHmacBuff, myHmacBuff)) { throw new ConnectionException(); } stream.Seek(8, SeekOrigin.Begin); } else { throw new ConnectionException(); } BufferStream bufferStream = new BufferStream(_bufferManager); if (_informationVersion3.CryptoAlgorithm.HasFlag(SecureVersion3.CryptoAlgorithm.Aes256)) { byte[] iv = new byte[16]; stream.Read(iv, 0, iv.Length); using (var aes = Aes.Create()) { aes.KeySize = 256; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; using (CryptoStream cs = new CryptoStream(new WrapperStream(bufferStream, true), aes.CreateDecryptor(_informationVersion3.OtherCryptoKey, iv), CryptoStreamMode.Write)) { byte[] receiveBuffer = null; try { receiveBuffer = _bufferManager.TakeBuffer(1024 * 4); int i = -1; while ((i = stream.Read(receiveBuffer, 0, receiveBuffer.Length)) > 0) { cs.Write(receiveBuffer, 0, i); } } finally { if (receiveBuffer != null) { _bufferManager.ReturnBuffer(receiveBuffer); } } } } } else { throw new ConnectionException(); } bufferStream.Seek(0, SeekOrigin.Begin); return(bufferStream); } } else { throw new ConnectionException(); } } catch (ConnectionException e) { throw e; } catch (Exception e) { throw new ConnectionException(e.Message, e); } } }
private byte[] CalculateMac(byte[] key, byte[] data) { return(HmacSha256.ComputeHash(key, data)); }
private byte[] GenerateKey(byte[] key, byte[] sharedSecret) { return(HmacSha256.ComputeHash(key, sharedSecret)); }
public byte[] Library_HmacSha256(byte[] data) => libHmac.ComputeHash(data);
public void ComputeHash_rfc_CtorKey_Test(byte[] msg, byte[] key, byte[] expected) { using HmacSha256 hmac = new HmacSha256(key); byte[] actual = hmac.ComputeHash(msg); Assert.Equal(expected, actual); }