private static byte[] EncryptSecretSeed(byte[] seedBytes, byte[] keyHash) { byte[] nonceBytes = SecretBox.GenerateNonce(); byte[] cipherText = SecretBox.Create(seedBytes, nonceBytes, keyHash); byte[] encryptedSeed = new byte[cipherText.Length + nonceBytes.Length]; Array.Copy(nonceBytes, 0, encryptedSeed, 0, nonceBytes.Length); Array.Copy(cipherText, 0, encryptedSeed, nonceBytes.Length, cipherText.Length); return(encryptedSeed); }
public string EncryptString(string message, byte[] key) { var nonce = SecretBox.GenerateNonce(); var secretMessage = SecretBox.Create(message, nonce, key); byte[] rv = new byte[nonce.Length + secretMessage.Length]; System.Buffer.BlockCopy(nonce, 0, rv, 0, nonce.Length); System.Buffer.BlockCopy(secretMessage, 0, rv, nonce.Length, secretMessage.Length); return(Utilities.BinaryToHex(rv)); }
public void SecretBoxOpenWithGeneratedDataTest() { var key = SecretBox.GenerateKey(); var nonce = SecretBox.GenerateNonce(); String message = "Hello, World!"; byte[] plainText = System.Text.Encoding.UTF8.GetBytes(message); byte[] cipherText = SecretBox.Create(plainText, nonce, key); byte[] decrypted = SecretBox.Open(cipherText, nonce, key); Assert.AreEqual(plainText.ToString(), decrypted.ToString()); }
/// <summary> /// Encrypts the Data (with Authentication) /// /// Primitive: XSalsa20 wiht Poly1305 MAC (libsodium crypto_secretbox) /// </summary> /// <param name="data">Data to be encrypted</param> /// <example> /// <code> /// var TEST_STRING = "eine kuh macht muh, viele kühe machen mühe" /// // Create a new Symmertic Key /// var key = new Key(); /// // Create a locker with this key /// var locker = new SecretLocker(key); /// var bytes = Utils.Secure.Encode(TEST_STRING); /// // Encrypt the bytes /// var ciphertext = locker.Lock(bytes); /// // Decrypt the Text /// var plaintext = locker.UnlockBytes(ciphertext); /// // Clear Keys /// locker.Clear(); /// </code> /// </example> public ILocked Lock(byte[] data) { if (data == null || data?.Length == 0) { throw new ArgumentNullException(nameof(data)); } var nonce = SecretBox.GenerateNonce(); var locked = SecretBox.Create(data, nonce, key.Bytes); return(new Locked(locked, new Nonce(nonce))); }
public static Keystore Generate(Configuration cfg, RawKeyPair rawKeyPair, string walletPassword, string walletName) { // create derived key with Argon2 byte[] salt = Utils.Crypto.GenerateSalt(cfg.DefaultSaltLength); Argon2 arg = Utils.Crypto.GetArgon2FromType(cfg.Argon2Mode, walletPassword); arg.DegreeOfParallelism = cfg.Parallelism; arg.Iterations = cfg.OpsLimit; arg.MemorySize = cfg.MemLimitKIB; arg.Salt = salt; byte[] rawHash = arg.GetBytes(32); // chain public and private key byte arrays byte[] privateAndPublicKey = rawKeyPair.ConcatenatedPrivateKey; // encrypt the key arrays with nonce and derived key byte[] nonce = SecretBox.GenerateNonce(); byte[] ciphertext = SecretBox.Create(privateAndPublicKey, nonce, rawHash); // generate walletName if not given if (walletName == null || walletName.Trim().Length == 0) { walletName = "generated wallet file - " + DateTime.Now; } // generate the domain object for keystore Keystore wallet = new Keystore { PublicKey = rawKeyPair.GetPublicKey(), Id = Guid.NewGuid().ToString().Replace("-", ""), Name = walletName, Version = cfg.Version, Crypto = new Crypto { SecretType = cfg.SecretType, SymmetricAlgorithm = cfg.SymmetricAlgorithm, CipherText = Hex.ToHexString(ciphertext), Kdf = cfg.Argon2Mode, CipherParams = new CipherParams { Nonce = Hex.ToHexString(nonce) }, KdfParams = new KdfParams { MemLimitKib = cfg.MemLimitKIB, OpsLimit = cfg.OpsLimit, Salt = Hex.ToHexString(salt), Parallelism = cfg.Parallelism } } }; return(wallet); }
public async static Task SendSecretMessage(Stream s, byte[] key, byte[] message, CancellationToken token = default) { byte[] nonce = SecretBox.GenerateNonce(); byte[] ciphertext = SecretBox.Create(message, nonce, key); byte[] len = BitConverter.GetBytes((uint)ciphertext.Length); if (ciphertext.Length > MaxMessageLen) { throw new ArgumentOutOfRangeException($"Encrypted message would be {len} bytes long, which is larger than the limit of {MaxMessageLen}"); } await s.WriteAsync(len, 0, len.Length, token); await s.WriteAsync(nonce, 0, nonce.Length, token); await s.WriteAsync(ciphertext, 0, ciphertext.Length, token); }
private void metroButton2_Click(object sender, EventArgs e) { if (txt_name.Text == "" || txt_password.Text == "") { MessageBox.Show("Please provide Name and a password"); return; } try { //Create SqlConnection SqlConnection con = new SqlConnection(cs); SqlCommand cmd = new SqlCommand("INSERT INTO tbl_list (list_name,list_password,list_key,list_nonce) VALUES (@list_name,@list_password,@list_key,@list_nonce)", con); var list_nonce = SecretBox.GenerateNonce(); //24 byte nonce var list_key = SecretBox.GenerateKey(); //32 byte key var message = txt_password.Text; //encrypt the message var ciphertext = SecretBox.Create(message, list_nonce, list_key); cmd.Parameters.AddWithValue("@list_name", txt_name.Text); cmd.Parameters.AddWithValue("@list_password", ciphertext); cmd.Parameters.AddWithValue("@list_key", list_key); cmd.Parameters.AddWithValue("@list_nonce", list_nonce); Console.WriteLine(); Console.WriteLine("Original data: " + message); Console.WriteLine("Encrypting and writing to disk..."); con.Open(); int i = cmd.ExecuteNonQuery(); con.Close(); if (i != 0) { MessageBox.Show("Password Saved"); BindGridPasswords(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void SecretBoxGenerateNonceText() { Assert.AreEqual(24, SecretBox.GenerateNonce().Length); }
protected async Task Connect() { Socket = SystemClientWebSocket.ConnectAsync(new Uri("ws://remote.natfrp.com:2333"), Source.Token).Result; await Socket.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new Dictionary <string, object> { { "version", REMOTE_VERSION }, { "type", "launcher" }, { "token", Natfrp.Token }, { "identifier", Identifier } }))), WebSocketMessageType.Text, true, Source.Token); Main.LogManager.Log(LogManager.CATEGORY_SERVICE_INFO, "Service", "RemoteManager: 远程管理已连接"); var remote = new RemotePipeConnection(); byte[] buffer = new byte[8192]; while (!Source.IsCancellationRequested) { // Ensure message is complete int length = 0; WebSocketReceiveResult result = null; while (true) { result = await Socket.ReceiveAsync(new ArraySegment <byte>(buffer, length, buffer.Length - length), Source.Token); length += result.Count; if (result.EndOfMessage) { break; } else if (length >= buffer.Length) { Main.LogManager.Log(LogManager.CATEGORY_SERVICE_WARNING, "Service", "RemoteManager: 接收到过长消息, 已断开服务器连接, 将在稍后重连"); await Socket.CloseAsync(WebSocketCloseStatus.MessageTooBig, "消息过长", Source.Token); return; } } // Handle close message if (result.MessageType == WebSocketMessageType.Close) { switch (result.CloseStatus.Value) { case WebSocketCloseStatus.NormalClosure: Main.LogManager.Log(LogManager.CATEGORY_SERVICE_INFO, "Service", "RemoteManager: 服务端正常断开 [" + result.CloseStatusDescription + "] 将在稍后重连"); break; case WebSocketCloseStatus.PolicyViolation: Main.LogManager.Log(LogManager.CATEGORY_SERVICE_WARNING, "Service", "RemoteManager: 服务器拒绝请求, 已停止远程管理功能: " + result.CloseStatusDescription); Stop(); return; case WebSocketCloseStatus.InternalServerError: Main.LogManager.Log(LogManager.CATEGORY_SERVICE_WARNING, "Service", "RemoteManager: 服务器内部错误, " + result.CloseStatusDescription); break; default: Main.LogManager.Log(LogManager.CATEGORY_SERVICE_WARNING, "Service", "RemoteManager: 未知错误 [" + result.CloseStatus + "], " + result.CloseStatusDescription); break; } await Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, Source.Token); return; } // Hmm, ensure something unexpected won't crash the socket if (length < OVERHEAD) { Main.LogManager.Log(LogManager.CATEGORY_SERVICE_WARNING, "Service", "RemoteManager: 收到过短的消息"); return; } // Process payload using (var ms = new MemoryStream()) { ms.Write(buffer, 0, OVERHEAD); switch (buffer[0]) { case 0x01: // Heartbeat if (length != OVERHEAD) { Main.LogManager.Log(LogManager.CATEGORY_SERVICE_WARNING, "Service", "RemoteManager: 心跳包长度异常"); continue; } break; case 0x02: // Remote Command if (length < 24 + OVERHEAD) { Main.LogManager.Log(LogManager.CATEGORY_SERVICE_WARNING, "Service", "RemoteManager: 收到过短的指令"); continue; } byte[] nonce = new byte[24], data = new byte[length - nonce.Length - OVERHEAD]; Buffer.BlockCopy(buffer, OVERHEAD, nonce, 0, nonce.Length); Buffer.BlockCopy(buffer, nonce.Length + OVERHEAD, data, 0, data.Length); try { data = SecretBox.Open(data, nonce, EncryptKey); } catch { Main.LogManager.Log(LogManager.CATEGORY_SERVICE_WARNING, "Service", "RemoteManager: 指令解密失败, 原因可能为密钥错误, 如果您无故看到此错误请检查账户是否被盗"); break; } remote.Buffer = data; Main.Pipe_DataReceived(remote, data.Length); nonce = SecretBox.GenerateNonce(); ms.Write(nonce, 0, nonce.Length); data = SecretBox.Create(remote.Buffer, nonce, EncryptKey); ms.Write(data, 0, data.Length); break; default: Main.LogManager.Log(LogManager.CATEGORY_SERVICE_WARNING, "Service", "RemoteManager: 收到未知消息"); continue; } await Socket.SendAsync(new ArraySegment <byte>(ms.ToArray()), WebSocketMessageType.Binary, true, Source.Token); } } }
public static byte[] GenerateNonce() { return(SecretBox.GenerateNonce()); }
public void TestGenerateNonce() { Assert.AreEqual(24, SecretBox.GenerateNonce().Length); }
public static byte[] Encrypt(byte[] plaintext, byte[] txKey) { var nonce = SecretBox.GenerateNonce(); return(nonce.Concat(SecretBox.Create(plaintext, nonce, txKey)).ToArray()); }
/// <summary> /// Store/Export a key to file. /// </summary> public async void ExportKeyToFile() { MainViewError = string.Empty; IsWorking = true; string password; if (SelectedKey != null) { var exportKey = new Key { PublicKey = SelectedKey.PublicKey, PrivateKey = SelectedKey.PrivateKey, KeyType = SelectedKey.KeyType, KeyId = SelectedKey.KeyId ?? null, KeySalt = SelectedKey.KeySalt ?? PasswordHash.GenerateSalt(), KeyNonce = SelectedKey.KeyNonce ?? SecretBox.GenerateNonce() }; var saveFileDialog = new SaveFileDialog { OverwritePrompt = true, AddExtension = true, DefaultExt = ".lkey" }; if (exportKey.KeyId != null) { saveFileDialog.FileName = Utilities.BinaryToHex(exportKey.KeyId); } var result = saveFileDialog.ShowDialog(); if (result == true) { var filename = saveFileDialog.FileName; try { var win = new PasswordInputViewModel { DisplayName = "Enter a new protection password" }; dynamic settings = new ExpandoObject(); settings.WindowStartupLocation = WindowStartupLocation.CenterOwner; settings.Owner = GetView(); var inputOk = _windowManager.ShowDialog(win, null, settings); if (inputOk == true) { password = win.UserPassword; if (!string.IsNullOrEmpty(password)) { var encryptionKey = await Task.Run(() => { var tmpKey = new byte[32]; try { tmpKey = PasswordHash.ScryptHashBinary(Encoding.UTF8.GetBytes(password), exportKey.KeySalt, PasswordHash.Strength.MediumSlow, 32); } catch (OutOfMemoryException) { MainViewError = "Could not export key (out of memory)."; } catch (Exception) { MainViewError = "Could not export key."; } return(tmpKey); }).ConfigureAwait(true); if (encryptionKey != null) { exportKey.PrivateKey = SecretBox.Create(exportKey.PrivateKey, exportKey.KeyNonce, encryptionKey); using (var keyFileStream = File.OpenWrite(filename)) { Serializer.SerializeWithLengthPrefix(keyFileStream, exportKey, PrefixStyle.Base128, 0); } } else { MainViewError = "Could not export key (missing encryption key?)"; } } else { MainViewError = "Could not export key (missing password)"; } } } catch (Exception) { MainViewError = "Could not export key (failure)"; } } else { MainViewError = "Could not export key (missing password)"; } } IsWorking = false; }
public Task<byte[]> AcquireNonceAsync(byte[] key) { return Task.FromResult(SecretBox.GenerateNonce()); }
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(); } } }
/// <summary> /// Generate a 24 byte nonce to use for encryption /// </summary> public static byte[] GenerateNonce() => SecretBox.GenerateNonce();