public string computeFromPreKnownKey(string foreignKey, byte[] privateKey) { var encodedForeignSecret = Encoding.UTF8.GetBytes(foreignKey); sharedSecret = ScalarMult.Mult(privateKey, encodedForeignSecret); return(Encoding.UTF8.GetString(sharedSecret)); }
public void ConvertToCurve25519Test() { // Keypair seed from libsodium-net var keypairSeed = new byte[] { 0x42, 0x11, 0x51, 0xa4, 0x59, 0xfa, 0xea, 0xde, 0x3d, 0x24, 0x71, 0x15, 0xf9, 0x4a, 0xed, 0xae, 0x42, 0x31, 0x81, 0x24, 0x09, 0x5a, 0xfa, 0xbe, 0x4d, 0x14, 0x51, 0xa5, 0x59, 0xfa, 0xed, 0xee }; var kp = PublicKeyAuth.GenerateKeyPair(keypairSeed); var ed25519Pk = kp.Public; var ed25519SkPk = kp.Secret; var curve25519Pk = PublicKeyAuth.ConvertEd25519PublicKeyToCurve25519PublicKey(ed25519Pk); var curve25519Sk = PublicKeyAuth.ConvertEd25519SecretKeyToCurve25519SecretKey(ed25519SkPk); Assert.AreEqual(Convert.ToBase64String(curve25519Pk), "8YFPDo/xBD2KRNJbq/887crmwiw+2qSPhXrnDeK6rlA="); Assert.AreEqual(Convert.ToBase64String(curve25519Sk), "gFIDA3bUcRK+f3PtegGSk90SrZELZURVeYtGZ9c94WY="); for (var i = 0; i < 500; i++) { kp = PublicKeyAuth.GenerateKeyPair(); ed25519Pk = kp.Public; ed25519SkPk = kp.Secret; curve25519Pk = PublicKeyAuth.ConvertEd25519PublicKeyToCurve25519PublicKey(ed25519Pk); curve25519Sk = PublicKeyAuth.ConvertEd25519SecretKeyToCurve25519SecretKey(ed25519SkPk); var curve25519Pk2 = ScalarMult.Base(curve25519Sk); CollectionAssert.AreEqual(curve25519Pk, curve25519Pk2); } }
/// <summary> /// Takes a 'plaintext' Buffer of the message you want to encrypt,<para /> /// and an array of recipient public keys.<para /> /// Returns a message that is encrypted to all recipients<para /> /// and openable by them with 'PrivateBox.MultiboxOpen'.<para /> /// The 'recipients' must be between 1 and 7 items long. /// </summary> /// <param name="msg"></param> /// <param name="recipients"></param> /// <param name="maxRecipients"></param> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public static byte[] Multibox(byte[] msg, byte[][] recipients, int maxRecipients = DEFAULT_MAX) { if (maxRecipients < 1 || maxRecipients > 255) { throw new ArgumentOutOfRangeException("max recipients must be between 1 and 255."); } if (recipients.Length > maxRecipients) { throw new ArgumentOutOfRangeException("max recipients is:" + maxRecipients + " found:" + recipients.Length); } var nonce = RandomBytes(24); var key = RandomBytes(32); var onetime = PublicKeyBox.GenerateKeyPair(); var length_and_key = new List <byte>(); length_and_key.Add((byte)recipients.Length); length_and_key.AddRange(key); var res = new List <byte>(); res.AddRange(nonce); res.AddRange(onetime.PublicKey); foreach (var rec in recipients) { res.AddRange(SecretBox.Create(length_and_key.ToArray(), nonce, ScalarMult.Mult(onetime.PrivateKey, rec))); } res.AddRange(SecretBox.Create(msg, nonce, key)); return(res.ToArray()); }
public void PublicKeyAuthConvertToCurve25519() { var keypairSeed = new byte[] { 0x42, 0x11, 0x51, 0xa4, 0x59, 0xfa, 0xea, 0xde, 0x3d, 0x24, 0x71, 0x15, 0xf9, 0x4a, 0xed, 0xae, 0x42, 0x31, 0x81, 0x24, 0x09, 0x5a, 0xfa, 0xbe, 0x4d, 0x14, 0x51, 0xa5, 0x59, 0xfa, 0xed, 0xee }; var keys = PublicKeyAuth.GenerateKeyPair(keypairSeed); var ed25519Pk = keys.PublicKey; var ed25519SkPk = keys.PrivateKey; var curve25519Pk = PublicKeyAuth.ConvertEd25519PublicKeyToCurve25519PublicKey(ed25519Pk); var curve25519Sk = PublicKeyAuth.ConvertEd25519SecretKeyToCurve25519SecretKey(ed25519SkPk); Assert.AreEqual(Utilities.BinaryToHex(curve25519Pk, Utilities.HexFormat.None, Utilities.HexCase.Upper), "F1814F0E8FF1043D8A44D25BABFF3CEDCAE6C22C3EDAA48F857AE70DE2BAAE50"); Assert.AreEqual(Utilities.BinaryToHex(curve25519Sk, Utilities.HexFormat.None, Utilities.HexCase.Upper), "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE166"); for (var i = 0; i < 500; i++) { keys = PublicKeyAuth.GenerateKeyPair(); ed25519Pk = keys.PublicKey; ed25519SkPk = keys.PrivateKey; curve25519Pk = PublicKeyAuth.ConvertEd25519PublicKeyToCurve25519PublicKey(ed25519Pk); curve25519Sk = PublicKeyAuth.ConvertEd25519SecretKeyToCurve25519SecretKey(ed25519SkPk); var curve25519Pk2 = ScalarMult.Base(curve25519Sk); CollectionAssert.AreEqual(curve25519Pk, curve25519Pk2); } }
public void ScalarMult5() { var aliceSk = new byte[] { 0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16, 0xc1, 0x72, 0x51, 0xb2, 0x66, 0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, 0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9, 0x2c, 0x2a }; var bobPk = new byte[] { 0xde, 0x9e, 0xdb, 0x7d, 0x7b, 0x7d, 0xc1, 0xb4, 0xd3, 0x5b, 0x61, 0xc2, 0xec, 0xe4, 0x35, 0x37, 0x3f, 0x83, 0x43, 0xc8, 0x5b, 0x78, 0x67, 0x4d, 0xad, 0xfc, 0x7e, 0x14, 0x6f, 0x88, 0x2b, 0x4f }; var k = ScalarMult.Mult(aliceSk, bobPk); var result = new byte[] { 0x4a, 0x5d, 0x9d, 0x5b, 0xa4, 0xce, 0x2d, 0xe1, 0x72, 0x8e, 0x3b, 0xf4, 0x80, 0x35, 0x0f, 0x25, 0xe0, 0x7e, 0x21, 0xc9, 0x47, 0xd1, 0x9e, 0x33, 0x76, 0xf0, 0x9b, 0x3c, 0x1e, 0x16, 0x17, 0x42 }; Assert.AreEqual(Convert.ToBase64String(k), Convert.ToBase64String(result)); }
private void DeriveSecrets() { var curve25519Sk = PublicKeyAuth .ConvertEd25519SecretKeyToCurve25519SecretKey( this._longterm_client_keypair.PrivateKey ); var curve25519Pk = PublicKeyAuth .ConvertEd25519PublicKeyToCurve25519PublicKey( _longterm_server_pk ); this._shared_ab = ScalarMult.Mult( this._ephemeral_client_keypair.PrivateKey, this._ephemeral_server_pk ); this._shared_aB = ScalarMult.Mult( this._ephemeral_client_keypair.PrivateKey, curve25519Pk ); this._shared_Ab = ScalarMult.Mult( curve25519Sk, _ephemeral_server_pk ); }
// 4.1. DH functions /// <summary> /// Create a X25519 static keyPair out of a private key. /// </summary> /// <param name="privateKey">Private key, if null - generates a random key pair</param> /// <returns>X25519 key pair</returns> public static KeyPair GenerateKeyPair(byte[] privateKey = null) { var keyPair = new KeyPair() { PublicKey = new byte[Asymmetric.DhLen], PrivateKey = new byte[Asymmetric.DhLen] }; if (privateKey == null) { var random = new RNGCryptoServiceProvider(); #if !DEBUG_DETERMINISTIC random.GetBytes(keyPair.PrivateKey, 0, keyPair.PrivateKey.Length); #endif } else { if (privateKey.Length != Asymmetric.DhLen) { throw new Exception($"disco: expecting {Asymmetric.DhLen} byte key array"); } privateKey.CopyTo(keyPair.PrivateKey, 0); } keyPair.PublicKey = ScalarMult.Base(keyPair.PrivateKey); return(keyPair); }
public void ScalarMult6() { var bobSk = new byte[] { 0x5d, 0xab, 0x08, 0x7e, 0x62, 0x4a, 0x8a, 0x4b, 0x79, 0xe1, 0x7f, 0x8b, 0x83, 0x80, 0x0e, 0xe6, 0x6f, 0x3b, 0xb1, 0x29, 0x26, 0x18, 0xb6, 0xfd, 0x1c, 0x2f, 0x8b, 0x27, 0xff, 0x88, 0xe0, 0xeb }; var alicePk = new byte[] { 0x85, 0x20, 0xf0, 0x09, 0x89, 0x30, 0xa7, 0x54, 0x74, 0x8b, 0x7d, 0xdc, 0xb4, 0x3e, 0xf7, 0x5a, 0x0d, 0xbf, 0x3a, 0x0d, 0x26, 0x38, 0x1a, 0xf4, 0xeb, 0xa4, 0xa9, 0x8e, 0xaa, 0x9b, 0x4e, 0x6a }; var k = ScalarMult.Mult(bobSk, alicePk); var result = new byte[] { 0x4a, 0x5d, 0x9d, 0x5b, 0xa4, 0xce, 0x2d, 0xe1, 0x72, 0x8e, 0x3b, 0xf4, 0x80, 0x35, 0x0f, 0x25, 0xe0, 0x7e, 0x21, 0xc9, 0x47, 0xd1, 0x9e, 0x33, 0x76, 0xf0, 0x9b, 0x3c, 0x1e, 0x16, 0x17, 0x42 }; Assert.AreEqual(Convert.ToBase64String(k), Convert.ToBase64String(result)); }
private static byte[] GenerateSymmetricKey(byte[] nodePublicKey, byte[] nodePrivateKey, byte[] ephemeralPublicKey, byte[] ephemeralPrivateKey) { if (nodePrivateKey == null && ephemeralPrivateKey == null) { throw new ArgumentNullException("nodePrivateKey", "Expected exactly one of nodePrivateKey or ephemeralPrivateKey to be null, but both were null."); } if (nodePrivateKey != null && ephemeralPrivateKey != null) { throw new ArgumentNullException("nodePrivateKey", "Expected exactly one of nodePrivateKey or ephemeralPrivateKey to be null, but both were provided."); } var privateKey = nodePrivateKey ?? ephemeralPrivateKey; var publicKey = nodePrivateKey != null ? ephemeralPublicKey : nodePublicKey; var q = ScalarMult.Mult(privateKey, publicKey); var bytes = new byte[q.Length + ephemeralPublicKey.Length + nodePublicKey.Length]; var writer = new WriteBuffer(bytes, 0); writer.Write(q); writer.Write(ephemeralPublicKey); writer.Write(nodePublicKey); return(GenericHash.Hash(bytes, null, 32)); }
public void BaseBadKey() { var aliceSk = new byte[] { 0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16, 0xc1, 0x72, 0x51, 0xb2, 0x66, 0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, 0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9 }; Assert.Throws <KeyOutOfRangeException>(() => ScalarMult.Base(aliceSk)); }
public void BaseBadKey() { var aliceSk = new byte[] { 0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16, 0xc1, 0x72, 0x51, 0xb2, 0x66, 0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, 0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9 }; ScalarMult.Base(aliceSk); }
/// <summary> /// Encrypts data with a public key /// </summary> /// <param name="data">String data to encrypt</param> /// <param name="publicKey">32 byte public key</param> /// <param name="version">Int version to generated</param> /// <param name="nonce">24 byte nonce.</param> /// <returns>byte[] containing the encrypted data</returns> public byte[] Encrypt(String data, byte[] publicKey, int version, byte[] nonce) { if (publicKey.Length != PublicKeyBox.PublicKeyBytes) { throw new ArgumentException(String.Format("Public key should be %d bytes", PublicKeyBox.PublicKeyBytes)); } if (nonce.Length != 24) { throw new ArgumentException(String.Format("Nonce should be %d bytes", 24)); } this.nonce = nonce; if (version == 2) { try { byte[] header = Sodium.Utilities.HexToBinary("DE259002"); byte[] body = this.EncryptBody(data, publicKey, nonce); if (body == null) { throw new EncryptionFailedException(); } publicKey = ScalarMult.Base(this.secretKey); byte[] sigPubKey = PublicKeyAuth.ExtractEd25519PublicKeyFromEd25519SecretKey(this.signatureSecretKey); byte[] signature = this.Sign(data); if (signature == null) { throw new EncryptionFailedException(); } MemoryStream m = new MemoryStream(); m.Write(header, 0, header.Length); m.Write(nonce, 0, nonce.Length); m.Write(publicKey, 0, publicKey.Length); m.Write(body, 0, body.Length); m.Write(sigPubKey, 0, sigPubKey.Length); m.Write(signature, 0, signature.Length); byte[] payload = m.ToArray(); byte[] checksum = GenericHash.Hash(payload, nonce, 64); m.Write(checksum, 0, checksum.Length); return(m.ToArray()); } catch (Exception e) { throw new EncryptionFailedException("Unable to encrypt message.", e); } } return(this.EncryptBody(data, publicKey, nonce)); }
private void DeriveAb() { var curve25519Pk = PublicKeyAuth .ConvertEd25519PublicKeyToCurve25519PublicKey( this._longterm_client_pk ); this._shared_Ab = ScalarMult.Mult( this._ephemeral_server_keypair.PrivateKey, curve25519Pk ); }
public bool computeSharedSecret(string foreignSecret) { try { var encodedForeignSecret = Encoding.UTF8.GetBytes(foreignSecret); receivedPublicKey = encodedForeignSecret; sharedSecret = ScalarMult.Mult(secretKey, encodedForeignSecret); return(true); } catch { return(false); } }
public static Tuple <byte[], byte[]> GenerateClientSessionKeys(KeyPair clientKeys, byte[] serverPublicKey) { var junk = new byte[Math.Max(crypto_kx_SESSIONKEYBYTES, clientKeys.PublicKey.Length)]; var clientSecret = ScalarMult.Mult(clientKeys.PrivateKey, serverPublicKey); using (var clientHash = new GenericHash.GenericHashAlgorithm((byte[])null, 2 * crypto_kx_SESSIONKEYBYTES)) { clientHash.Initialize(); clientHash.TransformBlock(clientSecret, 0, clientSecret.Length, junk, 0); clientHash.TransformBlock(clientKeys.PublicKey, 0, clientSecret.Length, junk, 0); clientHash.TransformFinalBlock(serverPublicKey, 0, clientSecret.Length); var rx = clientHash.Hash.Take(crypto_kx_SESSIONKEYBYTES); var tx = clientHash.Hash.Skip(crypto_kx_SESSIONKEYBYTES); return(Tuple.Create(rx.ToArray(), tx.ToArray())); } }
public void MultBadKey() { var aliceSk = new byte[] { 0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16, 0xc1, 0x72, 0x51, 0xb2, 0x66, 0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, 0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9 }; var bobPk = new byte[] { 0xde, 0x9e, 0xdb, 0x7d, 0x7b, 0x7d, 0xc1, 0xb4, 0xd3, 0x5b, 0x61, 0xc2, 0xec, 0xe4, 0x35, 0x37, 0x3f, 0x83, 0x43, 0xc8, 0x5b, 0x78, 0x67, 0x4d, 0xad, 0xfc, 0x7e, 0x14, 0x6f, 0x88, 0x2b, 0x4f }; Assert.Throws <KeyOutOfRangeException>(() => ScalarMult.Mult(aliceSk, bobPk)); }
public void ScalarMult2() { var bobSk = new byte[] { 0x5d, 0xab, 0x08, 0x7e, 0x62, 0x4a, 0x8a, 0x4b, 0x79, 0xe1, 0x7f, 0x8b, 0x83, 0x80, 0x0e, 0xe6, 0x6f, 0x3b, 0xb1, 0x29, 0x26, 0x18, 0xb6, 0xfd, 0x1c, 0x2f, 0x8b, 0x27, 0xff, 0x88, 0xe0, 0xeb }; var bobPk = ScalarMult.Base(bobSk); var result = new byte[] { 0xde, 0x9e, 0xdb, 0x7d, 0x7b, 0x7d, 0xc1, 0xb4, 0xd3, 0x5b, 0x61, 0xc2, 0xec, 0xe4, 0x35, 0x37, 0x3f, 0x83, 0x43, 0xc8, 0x5b, 0x78, 0x67, 0x4d, 0xad, 0xfc, 0x7e, 0x14, 0x6f, 0x88, 0x2b, 0x4f }; Assert.AreEqual(Convert.ToBase64String(bobPk), Convert.ToBase64String(result)); }
public void ScalarMult1() { var aliceSk = new byte[] { 0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16, 0xc1, 0x72, 0x51, 0xb2, 0x66, 0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, 0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9, 0x2c, 0x2a }; var alicePk = ScalarMult.Base(aliceSk); var result = new byte[] { 0x85, 0x20, 0xf0, 0x09, 0x89, 0x30, 0xa7, 0x54, 0x74, 0x8b, 0x7d, 0xdc, 0xb4, 0x3e, 0xf7, 0x5a, 0x0d, 0xbf, 0x3a, 0x0d, 0x26, 0x38, 0x1a, 0xf4, 0xeb, 0xa4, 0xa9, 0x8e, 0xaa, 0x9b, 0x4e, 0x6a }; Assert.AreEqual(Convert.ToBase64String(alicePk), Convert.ToBase64String(result)); }
public static SessionKeys ClientSessionKeys(KeyPair client, byte[] serverPublic) { var secret = ScalarMult.Mult(client.PrivateKey, serverPublic); var combined = secret .Concat(client.PublicKey) .Concat(serverPublic) .ToArray(); var hash = GenericHash.Hash(combined, null, 64); byte[] rx = new byte[32]; byte[] tx = new byte[32]; for (var i = 0; i < 32; i++) { rx[i] = hash[i]; tx[i] = hash[i + 32]; } return(new SessionKeys(rx, tx)); }
/// <summary> /// MultiboxOpenKey /// </summary> /// <param name="cypherText"></param> /// <param name="secretKey"></param> /// <param name="maxRecipients"></param> /// <returns>return null if secretKey is not valid</returns> public static byte[] MultiboxOpenKey(byte[] cypherText, byte[] secretKey, int maxRecipients = DEFAULT_MAX) { if (maxRecipients < 1 || maxRecipients > 255) { throw new ArgumentOutOfRangeException("max recipients must be between 1 and 255."); } var nonce = SubArray(cypherText, 0, 24); var onetime_pk = SubArray(cypherText, 24, 32); var my_key = ScalarMult.Mult(secretKey, onetime_pk); var start = 24 + 32; var size = 32 + 1 + 16; for (var i = 0; i <= maxRecipients; i++) { var s = start + size * i; if (s + size > (cypherText.Length - 16)) { return(null); } try { var length_and_key = SecretBox.Open(SubArray(cypherText, s, size), nonce, my_key); if (length_and_key != null) { return(length_and_key); } } catch (System.Security.Cryptography.CryptographicException) { } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } return(null); }
public static (byte[] ephemeralSharedSecret, byte[] ephemeralPublicKey) GetPrivateKeySharedSecret(byte[] privateKey) { using var ephemeralKeyPair = PublicKeyBox.GenerateKeyPair(); byte[] ephemeralSharedSecret = ScalarMult.Mult(privateKey, ephemeralKeyPair.PublicKey); return(ephemeralSharedSecret, ephemeralKeyPair.PublicKey); }
public static byte[] GetSharedSecret(byte[] privateKey, byte[] publicKey) { return(ScalarMult.Mult(privateKey, publicKey)); }
public static byte[] GetPrivateKeySharedSecret(byte[] privateKey, out byte[] ephemeralPublicKey) { using var ephemeralKeyPair = PublicKeyBox.GenerateKeyPair(); ephemeralPublicKey = ephemeralKeyPair.PublicKey; return(ScalarMult.Mult(privateKey, ephemeralKeyPair.PublicKey)); }
/// <summary> /// Perform DH on public key /// </summary> /// <param name="keyPair">Containing private key</param> /// <param name="publicKey">Remote party's public key</param> /// <returns>DH result</returns> public static byte[] Dh(KeyPair keyPair, byte[] publicKey) { return(ScalarMult.Mult(keyPair.PrivateKey, publicKey)); }
public static byte[] GetCurve25519PublicKey(byte[] privateKey) { byte[] publicKey = ScalarMult.Base(privateKey); return(Utilities.ConcatArrays(Constants.Curve25519KeyHeader, publicKey)); }
public void OnPost() { String PrivateKeyString = Request.Form["DHSKey"]; String ID = HttpContext.Session.GetString("Chat_ID"); String Current_User = HttpContext.Session.GetString("User_Name"); String Exception = ""; Boolean CheckConnection = MyOwnMySQLConnectionClass.LoadConnection(ref Exception); MySqlCommand MySQLQuery = new MySqlCommand(); MySqlDataReader PublicKeyStringReader; String PublicKeyString = ""; int Checker = 0; BigInteger PrivateKey = 0; BigInteger PublicKey = 0; Byte[] PrivateKeyBytes = new Byte[] { }; Byte[] PublicKeyBytes = new Byte[] { }; if (ID != null && PrivateKeyString != null) { PrivateKey = BigInteger.Parse(PrivateKeyString); MySQLQuery.CommandText = "SELECT COUNT(*) FROM `DF_Public_Key` WHERE `Requestor_1`=@Current_User AND `ID`=@ID"; MySQLQuery.Parameters.Add("@Current_User", MySqlDbType.Text).Value = Current_User; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); Checker = int.Parse(MySQLQuery.ExecuteScalar().ToString()); if (Checker == 1) { MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "SELECT `Requestor_1_PK` FROM `DF_Public_Key` WHERE `Requestor_1`=@Current_User AND `ID`=@ID"; MySQLQuery.Parameters.Add("@Current_User", MySqlDbType.Text).Value = Current_User; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); PublicKeyStringReader = MySQLQuery.ExecuteReader(); while (PublicKeyStringReader.Read()) { PublicKeyString = PublicKeyStringReader.GetValue(0).ToString(); } } else { MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "SELECT `Requestor_2_PK` FROM `DF_Public_Key` WHERE `Requestor_2`=@Current_User AND `ID`=@ID"; MySQLQuery.Parameters.Add("@Current_User", MySqlDbType.Text).Value = Current_User; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); PublicKeyStringReader = MySQLQuery.ExecuteReader(); while (PublicKeyStringReader.Read()) { PublicKeyString = PublicKeyStringReader.GetValue(0).ToString(); } } MyOwnMySQLConnectionClass.MyMySQLConnection.Close(); PrivateKeyBytes = PrivateKey.ToByteArray(); PublicKeyBytes = ScalarMult.Base(PrivateKeyBytes); PublicKey = new BigInteger(PublicKeyBytes); if (PublicKeyString.CompareTo(PublicKey.ToString()) == 0) { Response.Redirect("ChatSpace"); HttpContext.Session.SetString("PrivateKeyString", PrivateKeyString); } else { ViewData["Result"] = "The private/public key didn't match.. Perhaps try again?"; } } }
public void OnGet() { String PrivateKeyString = HttpContext.Session.GetString("PrivateKeyString"); String PublicKeyString = ""; String ID = HttpContext.Session.GetString("Chat_ID"); String Exception = ""; Boolean CheckConnection = MyOwnMySQLConnectionClass.LoadConnection(ref Exception); MySqlCommand MySQLQuery = new MySqlCommand(); MySqlDataReader RecordReader; List <BigInteger> MessageIntList = new List <BigInteger> { }; List <BigInteger> SaltIntList = new List <BigInteger> { }; List <BigInteger> NonceIntList = new List <BigInteger> { }; Byte[] CurrentMessageByte = new Byte[] { }; Byte[] CurrentSaltByte = new Byte[] { }; Byte[] CurrentNonceByte = new Byte[] { }; Byte[] PrivateKeyByte = new Byte[] { }; Byte[] PublicKeyByte = new Byte[] { }; Byte[] SharedSecretByte = new Byte[] { }; Byte[] DerivedKeyByte = new Byte[] { }; Byte[] DecryptedMessageByte = new Byte[] { }; BigInteger PrivateKey = 0; BigInteger PublicKey = 0; BigInteger DerivedKeyInt = 0; int Loop = 0; int Checker = 0; long OUTPUT_LENGTH = 32; Current_User = HttpContext.Session.GetString("User_Name"); if (PrivateKeyString != null && ID != null && Current_User != null) { MySQLQuery.CommandText = "SELECT COUNT(*) FROM `DF_Public_Key` WHERE `Requestor_1`=@Current_User AND `ID`=@ID"; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Parameters.Add("@Current_User", MySqlDbType.Text).Value = Current_User; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); Checker = int.Parse(MySQLQuery.ExecuteScalar().ToString()); if (Checker == 1) { MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "SELECT `Requestor_2_PK`,`Requestor_2` FROM `DF_Public_Key` WHERE `Requestor_1`=@Current_User AND `ID`=@ID"; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Parameters.Add("@Current_User", MySqlDbType.Text).Value = Current_User; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); RecordReader = MySQLQuery.ExecuteReader(); while (RecordReader.Read()) { PublicKeyString = RecordReader.GetValue(0).ToString(); Other_User = RecordReader.GetValue(1).ToString(); } MyOwnMySQLConnectionClass.MyMySQLConnection.Close(); } else { MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "SELECT `Requestor_1_PK`,`Requestor_1` FROM `DF_Public_Key` WHERE `Requestor_2`=@Current_User AND `ID`=@ID"; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Parameters.Add("@Current_User", MySqlDbType.Text).Value = Current_User; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); RecordReader = MySQLQuery.ExecuteReader(); while (RecordReader.Read()) { PublicKeyString = RecordReader.GetValue(0).ToString(); Other_User = RecordReader.GetValue(1).ToString(); } MyOwnMySQLConnectionClass.MyMySQLConnection.Close(); } CheckConnection = MyOwnMySQLConnectionClass.LoadConnection(ref Exception); PublicKey = BigInteger.Parse(PublicKeyString); PublicKeyByte = PublicKey.ToByteArray(); PrivateKey = BigInteger.Parse(PrivateKeyString); PrivateKeyByte = PrivateKey.ToByteArray(); SharedSecretByte = ScalarMult.Mult(PrivateKeyByte, PublicKeyByte); MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "SELECT COUNT(*) FROM `Chat_Message` WHERE `FK_ID`=@FK_ID"; MySQLQuery.Parameters.Add("@FK_ID", MySqlDbType.Text).Value = ID; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); Current_Count = int.Parse(MySQLQuery.ExecuteScalar().ToString()); MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "UPDATE `Chat_Message` SET `Receiver_Status`=@Receiver_Status WHERE `FK_ID`=@FK_ID AND `Receiver_Status`!=@Receiver_Status AND `Sender_Name`!=@Current_User"; MySQLQuery.Parameters.Add("@FK_ID", MySqlDbType.Text).Value = ID; MySQLQuery.Parameters.Add("@Receiver_Status", MySqlDbType.Text).Value = "Received"; MySQLQuery.Parameters.Add("@Current_User", MySqlDbType.Text).Value = Current_User; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); MySQLQuery.ExecuteNonQuery(); MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "SELECT `Salt`,`Nonce`,`Message`,`Sender_Name`,`Receiver_Status` FROM `Chat_Message` WHERE `FK_ID`=@FK_ID"; MySQLQuery.Parameters.Add("@FK_ID", MySqlDbType.Text).Value = ID; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); RecordReader = MySQLQuery.ExecuteReader(); while (RecordReader.Read()) { SaltIntList.Add(BigInteger.Parse(RecordReader.GetValue(0).ToString())); NonceIntList.Add(BigInteger.Parse(RecordReader.GetValue(1).ToString())); MessageIntList.Add(BigInteger.Parse(RecordReader.GetValue(2).ToString())); Sender_NameList.Add(RecordReader.GetValue(3).ToString()); Receiver_StatusList.Add(RecordReader.GetValue(4).ToString()); } MyOwnMySQLConnectionClass.MyMySQLConnection.Close(); Loop = 0; while (Loop < SaltIntList.Count) { CurrentSaltByte = SaltIntList[Loop].ToByteArray(); CurrentNonceByte = NonceIntList[Loop].ToByteArray(); CurrentMessageByte = MessageIntList[Loop].ToByteArray(); if (Loop == 0) { DerivedKeyByte = PasswordHash.ArgonHashBinary(SharedSecretByte, CurrentSaltByte, PasswordHash.StrengthArgon.Medium, OUTPUT_LENGTH, PasswordHash.ArgonAlgorithm.Argon_2ID13); } else { DerivedKeyByte = PasswordHash.ArgonHashBinary(DerivedKeyByte, CurrentSaltByte, PasswordHash.StrengthArgon.Medium, OUTPUT_LENGTH, PasswordHash.ArgonAlgorithm.Argon_2ID13); } DecryptedMessageByte = SecretBox.Open(CurrentMessageByte, CurrentNonceByte, DerivedKeyByte); Message_List.Add(Encoding.UTF8.GetString(DecryptedMessageByte)); Loop += 1; } HttpContext.Session.SetString("CurrentCount", Current_Count.ToString()); if (aTimer == null) { SetRefreshTimer(); } } }
public void OnPost() { String ID = HttpContext.Session.GetString("ID"); String Exception = ""; Boolean CheckConnection = MyOwnMySQLConnectionClass.LoadConnection(ref Exception); MySqlCommand MySQLQuery = new MySqlCommand(); MySqlDataReader PublicKeyDBReader; int Checker = 0; DateTime MyUTCDateTime = DateTime.UtcNow.AddHours(8); String PrivateKeyString = Request.Form["SK_Diffie_Hellman"].ToString(); String Current_User = HttpContext.Session.GetString("User_Name"); String PublicKeyStringDB = ""; BigInteger PrivateKey = BigInteger.Parse(PrivateKeyString); BigInteger PublicKey = 0; Byte[] PrivateKeyBytes = new Byte[] { }; Byte[] PublicKeyBytes = new Byte[] { }; PrivateKeyBytes = PrivateKey.ToByteArray(); PublicKeyBytes = ScalarMult.Base(PrivateKeyBytes); PublicKey = new BigInteger(PublicKeyBytes); MySQLQuery.CommandText = "SELECT COUNT(*) FROM `DF_Public_Key` WHERE `Requestor_1`=@Current_User AND `ID`=@ID"; MySQLQuery.Parameters.Add("@Current_User", MySqlDbType.Text).Value = Current_User; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); Checker = int.Parse(MySQLQuery.ExecuteScalar().ToString()); if (Checker == 1) { MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "SELECT `Requestor_1_PK` FROM `DF_Public_Key` WHERE `ID`=@ID"; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); PublicKeyDBReader = MySQLQuery.ExecuteReader(); while (PublicKeyDBReader.Read()) { PublicKeyStringDB = PublicKeyDBReader.GetValue(0).ToString(); } MyOwnMySQLConnectionClass.MyMySQLConnection.Close(); CheckConnection = MyOwnMySQLConnectionClass.LoadConnection(ref Exception); MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "UPDATE `DF_Public_Key` SET `Last_Checked_Date_R1`=@Last_Checked_Date_R1,`Requestor_1_PK`=@Requestor_1_PK WHERE `ID`=@ID"; MySQLQuery.Parameters.Add("@Last_Checked_Date_R1", MySqlDbType.DateTime).Value = MyUTCDateTime; MySQLQuery.Parameters.Add("@Requestor_1_PK", MySqlDbType.Text).Value = PublicKey.ToString(); MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); MySQLQuery.ExecuteNonQuery(); } else { MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "SELECT `Requestor_2_PK` FROM `DF_Public_Key` WHERE `ID`=@ID"; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); PublicKeyDBReader = MySQLQuery.ExecuteReader(); while (PublicKeyDBReader.Read()) { PublicKeyStringDB = PublicKeyDBReader.GetValue(0).ToString(); } MyOwnMySQLConnectionClass.MyMySQLConnection.Close(); CheckConnection = MyOwnMySQLConnectionClass.LoadConnection(ref Exception); MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "UPDATE `DF_Public_Key` SET `Last_Checked_Date_R2`=@Last_Checked_Date_R2,`Requestor_2_PK`=@Requestor_2_PK WHERE `ID`=@ID"; MySQLQuery.Parameters.Add("@Last_Checked_Date_R2", MySqlDbType.DateTime).Value = MyUTCDateTime; MySQLQuery.Parameters.Add("@Requestor_2_PK", MySqlDbType.Text).Value = PublicKey.ToString(); MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); MySQLQuery.ExecuteNonQuery(); } if (PublicKeyStringDB.CompareTo(PublicKey.ToString()) == 0) { ViewData["Result"] = "Your public key value hasn't been tampered with.."; } else { ViewData["Result"] = "You better watch out someone has modified ur public key value.."; } HttpContext.Session.Remove("ID"); }
public string exportPublicKey() { byte[] export = ScalarMult.Base(secretKey); return(Encoding.UTF8.GetString(export)); }
public void OnPost() { String PrivateKeyString = HttpContext.Session.GetString("PrivateKeyString"); String ID = HttpContext.Session.GetString("Chat_ID"); String Current_User = HttpContext.Session.GetString("User_Name"); String Chat_Message = Request.Form["Chat_Message"]; String Exception = ""; Boolean CheckConnection = MyOwnMySQLConnectionClass.LoadConnection(ref Exception); MySqlCommand MySQLQuery = new MySqlCommand(); MySqlDataReader PublicKeyStringReader; MySqlDataReader RecordReader; String PublicKeyString = ""; BigInteger PrivateKey = 0; BigInteger Nonce = 0; BigInteger PublicKey = 0; BigInteger MessageInt = 0; BigInteger SaltInt = 0; Byte[] NonceByte = new Byte[] { }; Byte[] PrivateKeyByte = new Byte[] { }; Byte[] PublicKeyByte = new Byte[] { }; Byte[] SharedSecretByte = new Byte[] { }; Byte[] MessageByte = new Byte[] { }; Byte[] SaltByte = new Byte[] { }; Byte[] NewKeyByte = new Byte[] { }; int Checker = 0; int Count = 1; long OUTPUT_LENGTH = 32; if (Chat_Message != null) { MySQLQuery.CommandText = "SELECT COUNT(*) FROM `DF_Public_Key` WHERE `Requestor_1`=@Current_User AND `ID`=@ID"; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Parameters.Add("@Current_User", MySqlDbType.Text).Value = Current_User; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); Checker = int.Parse(MySQLQuery.ExecuteScalar().ToString()); if (Checker == 1) { MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "SELECT `Requestor_2_PK` FROM `DF_Public_Key` WHERE `Requestor_1`=@Current_User AND `ID`=@ID"; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Parameters.Add("@Current_User", MySqlDbType.Text).Value = Current_User; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); PublicKeyStringReader = MySQLQuery.ExecuteReader(); while (PublicKeyStringReader.Read()) { PublicKeyString = PublicKeyStringReader.GetValue(0).ToString(); } MyOwnMySQLConnectionClass.MyMySQLConnection.Close(); } else { MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "SELECT `Requestor_1_PK` FROM `DF_Public_Key` WHERE `Requestor_2`=@Current_User AND `ID`=@ID"; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Parameters.Add("@Current_User", MySqlDbType.Text).Value = Current_User; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); PublicKeyStringReader = MySQLQuery.ExecuteReader(); while (PublicKeyStringReader.Read()) { PublicKeyString = PublicKeyStringReader.GetValue(0).ToString(); } MyOwnMySQLConnectionClass.MyMySQLConnection.Close(); } CheckConnection = MyOwnMySQLConnectionClass.LoadConnection(ref Exception); PublicKey = BigInteger.Parse(PublicKeyString); PublicKeyByte = PublicKey.ToByteArray(); PrivateKey = BigInteger.Parse(PrivateKeyString); PrivateKeyByte = PrivateKey.ToByteArray(); SharedSecretByte = ScalarMult.Mult(PrivateKeyByte, PublicKeyByte); MySQLQuery = new MySqlCommand(); Checker = 0; MySQLQuery.CommandText = "SELECT COUNT(*) FROM `Chat_Message` WHERE `FK_ID`=@ID"; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); Checker = int.Parse(MySQLQuery.ExecuteScalar().ToString()); if (Checker != 0) { MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "SELECT `Salt` FROM `Chat_Message` WHERE `FK_ID`=@ID"; MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID; MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); RecordReader = MySQLQuery.ExecuteReader(); while (RecordReader.Read()) { SaltInt = BigInteger.Parse(RecordReader.GetValue(0).ToString()); SaltByte = SaltInt.ToByteArray(); if (Count == 1) { NewKeyByte = PasswordHash.ArgonHashBinary(SharedSecretByte, SaltByte, PasswordHash.StrengthArgon.Medium, OUTPUT_LENGTH, PasswordHash.ArgonAlgorithm.Argon_2ID13); } else { NewKeyByte = PasswordHash.ArgonHashBinary(NewKeyByte, SaltByte, PasswordHash.StrengthArgon.Medium, OUTPUT_LENGTH, PasswordHash.ArgonAlgorithm.Argon_2ID13); } Count += 1; } } if (NewKeyByte.Length == 0) { SaltByte = PasswordHash.ArgonGenerateSalt(); NewKeyByte = PasswordHash.ArgonHashBinary(SharedSecretByte, SaltByte, PasswordHash.StrengthArgon.Medium, OUTPUT_LENGTH, PasswordHash.ArgonAlgorithm.Argon_2ID13); SaltInt = new BigInteger(SaltByte); NonceByte = SecretBox.GenerateNonce(); MessageByte = SecretBox.Create(Encoding.UTF8.GetBytes(Chat_Message), NonceByte, NewKeyByte); MessageInt = new BigInteger(MessageByte); Nonce = new BigInteger(NonceByte); } else { SaltByte = PasswordHash.ArgonGenerateSalt(); NewKeyByte = PasswordHash.ArgonHashBinary(NewKeyByte, SaltByte, PasswordHash.StrengthArgon.Medium, OUTPUT_LENGTH, PasswordHash.ArgonAlgorithm.Argon_2ID13); SaltInt = new BigInteger(SaltByte); NonceByte = SecretBox.GenerateNonce(); MessageByte = SecretBox.Create(Encoding.UTF8.GetBytes(Chat_Message), NonceByte, NewKeyByte); MessageInt = new BigInteger(MessageByte); Nonce = new BigInteger(NonceByte); } MyOwnMySQLConnectionClass.MyMySQLConnection.Close(); CheckConnection = MyOwnMySQLConnectionClass.LoadConnection(ref Exception); MySQLQuery = new MySqlCommand(); MySQLQuery.CommandText = "INSERT INTO `Chat_Message`(`FK_ID`,`Message`,`Sender_Name`,`Receiver_Status`,`Salt`,`Nonce`) VALUES (@FK_ID,@Message,@Sender_Name,@Receiver_Status,@Salt,@Nonce)"; MySQLQuery.Parameters.Add("@FK_ID", MySqlDbType.Text).Value = ID; MySQLQuery.Parameters.Add("@Message", MySqlDbType.Text).Value = MessageInt.ToString(); MySQLQuery.Parameters.Add("@Sender_Name", MySqlDbType.Text).Value = Current_User; MySQLQuery.Parameters.Add("@Receiver_Status", MySqlDbType.Text).Value = "Sent"; MySQLQuery.Parameters.Add("@Salt", MySqlDbType.Text).Value = SaltInt.ToString(); MySQLQuery.Parameters.Add("@Nonce", MySqlDbType.Text).Value = Nonce.ToString(); MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection; MySQLQuery.Prepare(); MySQLQuery.ExecuteNonQuery(); MyOwnMySQLConnectionClass.MyMySQLConnection.Close(); Determiner = 0; if (Determiner == 0 && ConfirmationTimer == null) { SetConfirmationTimer(); } } }