public static void DecryptPacket(Socket socket, ServerState state, byte[] packet) { var messageId = BitConverter.ToInt32(new byte[2].Concat(packet.Take(2)).Reverse().ToArray(), 0); var payloadLength = BitConverter.ToInt32(new byte[1].Concat(packet.Skip(2).Take(3)).Reverse().ToArray(), 0); var unknown = BitConverter.ToInt32(new byte[2].Concat(packet.Skip(2).Skip(3).Take(2)).Reverse().ToArray(), 0); var cipherText = packet.Skip(2).Skip(3).Skip(2).ToArray(); byte[] plainText; if (messageId == 10100) { plainText = cipherText; } else if (messageId == 10101) { state.clientKey = cipherText.Take(32).ToArray(); var nonce = GenericHash.Hash(state.clientKey.Concat(state.serverKey.PublicKey).ToArray(), null, 24); cipherText = cipherText.Skip(32).ToArray(); plainText = PublicKeyBox.Open(cipherText, nonce, state.serverKey.PrivateKey, state.clientKey); state.sessionKey = plainText.Take(24).ToArray(); state.clientState.nonce = plainText.Skip(24).Take(24).ToArray(); plainText = plainText.Skip(24).Skip(24).ToArray(); } else { state.clientState.nonce = Utilities.Increment(Utilities.Increment(state.clientState.nonce)); plainText = SecretBox.Open(new byte[16].Concat(cipherText).ToArray(), state.clientState.nonce, state.sharedKey); } Console.WriteLine("[UCR] {0}" + Environment.NewLine + "{1}", PacketInfos.GetPacketName(messageId), Utilities.BinaryToHex(packet.Take(7).ToArray()) + Utilities.BinaryToHex(plainText)); ClientCrypto.EncryptPacket(state.clientState.socket, state.clientState, messageId, unknown, plainText); }
private string Decrypt(string cipherText, string sendersPublicKey, byte[] nonce) { byte[] cipherBytes = Convert.FromBase64String(cipherText); byte[] spkBytes = Convert.FromBase64String(sendersPublicKey); byte[] plainBytes = PublicKeyBox.Open(cipherBytes, nonce, privateKey, spkBytes); return(Encoding.UTF8.GetString(plainBytes)); }
public void Decrypt() { try { if (this.m_vType == 10101) { byte[] array = this.m_vData; this.Client.CPublicKey = array.Take(32).ToArray <byte>(); this.Client.CSharedKey = this.Client.CPublicKey; this.Client.CRNonce = Client.GenerateSessionKey(); byte[] nonce = GenericHash.Hash(this.Client.CPublicKey.Concat(Key.Crypto.PublicKey).ToArray <byte>(), null, 24); array = array.Skip(32).ToArray <byte>(); byte[] source = PublicKeyBox.Open(array, nonce, Key.Crypto.PrivateKey, this.Client.CPublicKey); this.Client.CSessionKey = source.Take(24).ToArray <byte>(); this.Client.CSNonce = source.Skip(24).Take(24).ToArray <byte>(); this.SetData(source.Skip(24).Skip(24).ToArray <byte>()); } else { this.Client.CSNonce = Sodium.Utilities.Increment(Sodium.Utilities.Increment(this.Client.CSNonce)); this.SetData(SecretBox.Open(new byte[16].Concat(this.m_vData).ToArray <byte>(), this.Client.CSNonce, this.Client.CSharedKey)); } } catch (Exception) { this.Client.CState = 0; } }
public void Decrypt() { try { if (m_vType == 10101) { byte[] cipherText = m_vData; Client.CPublicKey = cipherText.Take(32).ToArray(); Client.CSharedKey = Client.CPublicKey; Client.CRNonce = Client.GenerateSessionKey(); byte[] nonce = GenericHash.Hash(Client.CPublicKey.Concat(Key.Crypto.PublicKey).ToArray(), null, 24); cipherText = cipherText.Skip(32).ToArray(); var PlainText = PublicKeyBox.Open(cipherText, nonce, Key.Crypto.PrivateKey, Client.CPublicKey); Client.CSessionKey = PlainText.Take(24).ToArray(); Client.CSNonce = PlainText.Skip(24).Take(24).ToArray(); SetData(PlainText.Skip(24).Skip(24).ToArray()); } else { Client.CSNonce = Utilities.Increment(Utilities.Increment(Client.CSNonce)); SetData(SecretBox.Open(new byte[16].Concat(m_vData).ToArray(), Client.CSNonce, Client.CSharedKey)); } } catch (Exception ex) { Client.CState = 0; return; } }
public static void DecryptPacket(ServerState state, byte[] packet) { using (var reader = new Reader(packet)) { var ID = reader.ReadUInt16(); reader.Seek(3, SeekOrigin.Current); var Version = reader.ReadUInt16(); byte[] cipherText = reader.ReadAllBytes, plainText; var Name = Packet_Names.GetName(ID); switch (ID) { case 10100: { plainText = cipherText; break; } case 10101: { state.ClientKey = cipherText.Take(32).ToArray(); var nonce = GenericHash.Hash(state.ClientKey.Concat(state.ServerKey.PublicKey).ToArray(), null, 24); cipherText = cipherText.Skip(32).ToArray(); plainText = PublicKeyBox.Open(cipherText, nonce, state.ServerKey.PrivateKey, state.ClientKey); state.SessionKey = plainText.Take(24).ToArray(); state.ClientState.Nonce = plainText.Skip(24).Take(24).ToArray(); plainText = plainText.Skip(24).Skip(24).ToArray(); break; } default: { state.ClientState.Nonce = Utilities.Increment(Utilities.Increment(state.ClientState.Nonce)); plainText = SecretBox.Open(new byte[16].Concat(cipherText).ToArray(), state.ClientState.Nonce, state.SharedKey); break; } } ClientCrypto.EncryptPacket(state.ClientState, ID, Version, plainText); Console.WriteLine( $"[{DateTime.Now.ToLongTimeString()}, CLIENT, {ID}] {Resources.Definition.Decode(new Reader(plainText), ID)}"); Logger.Write(BitConverter.ToString(plainText).Replace("-", string.Empty), $"{ID}_{Name}", LogType.PACKET); } }
/// <summary> /// Internal implementation to decrypt a message given a public key and nonce /// </summary> /// <param name="response">The byte array encrypted message</param> /// <param name="publicKey">32 byte public key</param> /// <param name="nonce">24 byte nonce</param> /// <returns>Decrypted message as a string</returns> private String DecryptBody(byte[] response, byte[] publicKey, byte[] nonce) { if (publicKey.Length != PublicKeyBox.PublicKeyBytes) { throw new ArgumentException(String.Format("Public key should be %d bytes.", PublicKeyBox.PublicKeyBytes)); } if (nonce.Length < 24) // PublicKeyBox.NONCEBYTES { throw new ArgumentException(String.Format("Message should be at minimum %d bytes.", 2)); } if (response.Length < 16) // PublicKeyBox.MAC_BYTES { throw new ArgumentException(String.Format("Message should be at minimum %d bytes.", 16)); } try { byte[] message = PublicKeyBox.Open( response, nonce, this.secretKey, publicKey ); return(System.Text.Encoding.UTF8.GetString(message)); } catch (Exception e) { throw new DecryptionFailedException("Unable to decrypt message.", e); } }
public void PublicKeyBoxOpenBadNonce() { PublicKeyBox.Open( Utilities.HexToBinary("aed04284c55860ad0f6379f235cc2cb8c32aba7a811b35cfac94f64d"), Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVW"), Utilities.HexToBinary("d4c8438482d5d103a2315251a5eed7c46017864a02ddc4c8b03f0ede8cb3ef9b"), Utilities.HexToBinary("753cb95919b15b76654b1969c554a4aaf8334402ef1468cb40a602b9c9fd2c13")); }
public static string Decrypt(byte[] cipherText, KeyPair keypair) { var nonce = new byte[24]; var cipher = new byte[cipherText.Length - 24]; Array.Copy(cipherText, nonce, 24); Array.Copy(cipherText, 24, cipher, 0, cipherText.Length - 24); return(PublicKeyBox.Open(cipher, nonce, keypair.PrivateKey, keypair.PublicKey).ToString()); }
public static byte[] Decrypt(byte[] cipherText, byte[] yourPrivateKey, byte[] theirPublicKey) { var nonce = new byte[24]; var cipher = new byte[cipherText.Length - 24]; Array.Copy(cipherText, nonce, 24); Array.Copy(cipherText, 24, cipher, 0, cipherText.Length - 24); return(PublicKeyBox.Open(cipher, nonce, yourPrivateKey, theirPublicKey)); }
private static string SecretboxDecryptionFromBase64(byte[] privateKey, byte[] publicKey, string ciphertextBase64) { string[] parts = ciphertextBase64.Split(':'); byte[] nonce = Base64Decoding(parts[0]); byte[] ciphertext = Base64Decoding(parts[1]); var decrypted = PublicKeyBox.Open(ciphertext, nonce, privateKey, publicKey); return(System.Text.Encoding.UTF8.GetString(decrypted, 0, decrypted.Length)); }
public static string RSADecryption(string privateKey, string cipherText, string nonce, string publicKey) { var encodedPrivateKey = Encoding.UTF8.GetBytes(privateKey); var encodedPublicKey = Encoding.UTF8.GetBytes(publicKey); var cipher = Encoding.UTF8.GetBytes(cipherText); var privateNonce = Encoding.UTF8.GetBytes(nonce); var plainText = PublicKeyBox.Open(cipher, privateNonce, encodedPrivateKey, encodedPublicKey); return(Encoding.UTF8.GetString(plainText)); }
public void SimpleLegacyOpenTest() { var expected = Encoding.UTF8.GetBytes("Adam Caudill"); var actual = PublicKeyBox.Open( Utilities.HexToBinary("00000000000000000000000000000000aed04284c55860ad0f6379f235cc2cb8c32aba7a811b35cfac94f64d"), Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"), Utilities.HexToBinary("d4c8438482d5d103a2315251a5eed7c46017864a02ddc4c8b03f0ede8cb3ef9b"), Utilities.HexToBinary("753cb95919b15b76654b1969c554a4aaf8334402ef1468cb40a602b9c9fd2c13")); CollectionAssert.AreEqual(expected, actual); }
public void CreateAndOpenWithOneKeyTest() { var kp = PublicKeyBox.GenerateKeyPair(); var nonce = PublicKeyBox.GenerateNonce(); byte[] message = System.Text.Encoding.UTF8.GetBytes("Hello, World!"); var encrypted = PublicKeyBox.Create(message, nonce, kp.Secret, kp.Public); var decrypted = PublicKeyBox.Open(encrypted, nonce, kp.Secret, kp.Public); Assert.AreEqual(decrypted.ToString(), message.ToString()); }
/// <summary> /// Unlock the Data /// </summary> /// <param name="senderPubKey">The Public Key of the Sender</param> /// <param name="recieverPrivKey">The Private Key of the Reciever</param> /// <returns>The unlocked Data</returns> public byte[] UnlockBytes(IPublicKey senderPubKey, IPrivateSecretKey recieverPrivKey) { if (senderPubKey == null) { throw new ArgumentNullException(nameof(senderPubKey)); } if (recieverPrivKey == null) { throw new ArgumentNullException(nameof(recieverPrivKey)); } return(PublicKeyBox.Open(Cipher, Nonce.Bytes, secretKey: recieverPrivKey.Bytes, publicKey: senderPubKey.Bytes)); }
private void ReceiverLoop() { audioClient = new UdpClient(4321); var endpoint = new IPEndPoint(IPAddress.Any, 1); while (true) { var data = new byte[0]; try { data = audioClient.Receive(ref endpoint); } catch { return; } var method = Encoding.ASCII.GetString(data.Take(3).ToArray()); if (method != "Aud") { continue; } var session = data.Skip(3).Take(4).ToArray(); var seq = data.Skip(7).Take(8).ToArray(); var nonce = data.Skip(15).Take(24).ToArray(); var encryptedData = data.Skip(39).ToArray(); var opusData = new byte[0]; try { opusData = PublicKeyBox.Open(encryptedData, nonce, localKeyPair.PrivateKey, remotePublicKey); } catch { continue; } var samples = new short[960]; decoder.Decode(opusData, 0, opusData.Length, samples, 0, 480); var sampleBuffer = new byte[1920]; for (int i = 0; i < 960; i++) { var splitSample = BitConverter.GetBytes(samples[i]); sampleBuffer[i * 2] = splitSample[0]; sampleBuffer[i * 2 + 1] = splitSample[1]; } waveProvider.AddSamples(sampleBuffer, 0, 1920); var ack = Encoding.ASCII.GetBytes("Ack") .Concat(seq) .ToArray(); audioClient.Send(ack, ack.Length, endpoint); } }
public void OpenWithKeyAndNonce() { // Key, CipherText, and Nonce generated from libsodium var cipherText = Convert.FromBase64String("9Zz8uwvPNqaSzebM4Lf1Gx9RmsaSiww+P0cUogk="); var nonce = Convert.FromBase64String("xMD3oIf1lzGK/3X0zFwB0pkcR4ajrb6N"); var key = Convert.FromBase64String("xIsxKqHum01qF1EmiV8WLm2jCiEfcHsXZYYucvOStDE="); var kp = PublicKeyBox.GenerateKeyPair(key); byte[] message = System.Text.Encoding.UTF8.GetBytes("Hello, World!"); var decrypted = PublicKeyBox.Open(cipherText, nonce, kp.Secret, kp.Public); Assert.AreEqual(decrypted.ToString(), message.ToString()); }
public static byte[] Decrypt(byte[] Payload, KeyPair keyPair) { ushort Id; int Length; ushort Version; using (Reader reader = new Reader(Payload)) { Id = reader.ReadUInt16(); Length = reader.ReadInt24(); Version = reader.ReadUInt16(); Payload = Payload.Skip(2).Skip(3).Skip(2).ToArray(); } if (!Form1.Config.UseRC4) { switch (Id) { case 20100: decryptedPayload = Payload; break; case 20103: decryptedPayload = Payload; break; case 20104: ClientConfig.ServerNonce = GenericHash.Hash(ClientConfig.SNonce.Concat(keyPair.PublicKey).Concat(Keys.ServerKey).ToArray(), null, 24); decryptedPayload = PublicKeyBox.Open(Payload, ClientConfig.ServerNonce, keyPair.PrivateKey, Keys.ServerKey); ClientConfig.RNonce = decryptedPayload.Take(24).ToArray(); ClientConfig.SharedKey = decryptedPayload.Skip(24).Take(32).ToArray(); decryptedPayload = decryptedPayload.Skip(24).Skip(32).ToArray(); break; default: ClientConfig.RNonce = Utilities.Increment(Utilities.Increment(ClientConfig.RNonce)); byte[] toDecrypt = new byte[16].Concat(Payload).ToArray(); decryptedPayload = SecretBox.Open(toDecrypt, ClientConfig.RNonce, ClientConfig.SharedKey); Logger.Write(Encoding.UTF8.GetString(decryptedPayload), "Decrypted OHD"); break; } } else if (Form1.Config.UseRC4) { decryptedPayload = RC4.Decrypt(Payload); } else { } return(decryptedPayload); }
public void PublicKeyBoxOpenBadPublicKey() { var bobPk = 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 }; PublicKeyBox.Open( Utilities.HexToBinary("aed04284c55860ad0f6379f235cc2cb8c32aba7a811b35cfac94f64d"), Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"), Utilities.HexToBinary("d4c8438482d5d103a2315251a5eed7c46017864a02ddc4c8b03f0ede8cb3ef9b"), bobPk); }
private void OnClientDataReceive(ArraySegment <byte> data, int channel) { try { var rawData = data.Array; int pos = data.Offset; OpCodes opcode = (OpCodes)rawData.ReadByte(ref pos); switch (opcode) { case OpCodes.ServerPublicKey: _serverPublicKey = rawData.ReadBytes(ref pos); pos = 0; _clientSendBuffer.WriteByte(ref pos, (byte)OpCodes.ClientPublicKey); _clientSendBuffer.WriteBytes(ref pos, _keyPair.PublicKey); CommunicationTransport.ClientSend(Channels.Reliable, new ArraySegment <byte>(_clientSendBuffer, 0, pos)); if (showDebugLogs) { Debug.Log($"<color=green>MONKE | CLIENT RECIEVED SERVER PUBLIC KEY!</color>"); } OnClientConnected?.Invoke(); break; case OpCodes.Data: _readBuffer = rawData.ReadBytes(ref pos); _nonce = rawData.ReadBytes(ref pos); _encryptionBuffer = PublicKeyBox.Open(_readBuffer, _nonce, _keyPair.PrivateKey, _serverPublicKey); OnClientDataReceived?.Invoke(new ArraySegment <byte>(_encryptionBuffer), channel); if (showDebugLogs) { Debug.Log($"<color=green>MONKE | CLIENT DATA | RAW DATA: " + _readBuffer.Length + " DECRYPTED DATA LENGTH: " + _encryptionBuffer.Length + "</color>" + " <color=yellow>DELTA: " + (_readBuffer.Length - _encryptionBuffer.Length) + "</color>"); } break; } } catch (Exception e) { Debug.LogError("Error: " + e); } }
public void PublicKeyBoxOpenBadPrivateKey() { var bobPk = 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 }; PublicKeyBox.Open( Utilities.HexToBinary("aed04284c55860ad0f6379f235cc2cb8c32aba7a811b35cfac94f64d"), Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"), bobPk, Utilities.HexToBinary("753cb95919b15b76654b1969c554a4aaf8334402ef1468cb40a602b9c9fd2c13")); }
private void decryptAdminString_Click(object sender, EventArgs e) { try { var adminStringByteArray = Convert.FromBase64String(adminString.Text); var nonce = ArrayHelpers.SubArray(adminStringByteArray, 0, 24); var publicKey = ArrayHelpers.SubArray(adminStringByteArray, 24, 32); var cipher = ArrayHelpers.SubArray(adminStringByteArray, 56); var privateKey = Utilities.HexToBinary(TargetPrivateKeyHex); decryptionKey.Text = Utilities.BinaryToHex(PublicKeyBox.Open(cipher, nonce, privateKey, publicKey)); } catch { } }
public static string Decrypt(string crypt, string secretKey, string publicKey, string nonce) { byte[] secret_bytes; byte[] public_bytes; byte[] nonce_bytes; byte[] crypt_bytes; if (Utils.IsBase64(nonce)) { nonce_bytes = Convert.FromBase64String(nonce); } else { throw new ArgumentException($"{nameof(nonce)} must be a Base64-encoded string"); } if (Utils.IsBase64(crypt)) { crypt_bytes = Convert.FromBase64String(crypt); } else { throw new ArgumentException($"{nameof(crypt)} must be a Base64-encoded string"); } if (!Utils.IsBase64(secretKey)) { secret_bytes = Encoding.ASCII.GetBytes(secretKey); } else { secret_bytes = Convert.FromBase64String(secretKey); } if (!Utils.IsBase64(publicKey)) { public_bytes = Encoding.ASCII.GetBytes(publicKey); } else { public_bytes = Convert.FromBase64String(publicKey); } var plaintext = PublicKeyBox.Open(crypt_bytes, nonce_bytes, secret_bytes, public_bytes); return(Encoding.UTF8.GetString(plaintext)); }
void OnServerDataReceive(int conn, ArraySegment <byte> data, int channel) { try { var rawData = data.Array; int pos = data.Offset; OpCodes opcode = (OpCodes)rawData.ReadByte(ref pos); switch (opcode) { case OpCodes.ClientPublicKey: byte[] clientPublicKey = rawData.ReadBytes(ref pos); _serverSessions.Add(conn, clientPublicKey); if (showDebugLogs) { Debug.Log($"<color=green>MONKE | SERVER RECIEVED CLIENT PUBLIC KEY!</color>"); } OnServerConnected?.Invoke(conn); break; case OpCodes.Data: _readBuffer = rawData.ReadBytes(ref pos); _nonce = rawData.ReadBytes(ref pos); if (_serverSessions.ContainsKey(conn)) { _encryptionBuffer = PublicKeyBox.Open(_readBuffer, _nonce, _keyPair.PrivateKey, _serverSessions[conn]); OnServerDataReceived?.Invoke(conn, new ArraySegment <byte>(_encryptionBuffer), channel); if (showDebugLogs) { Debug.Log($"<color=green>MONKE | SERVER DATA | RAW DATA: " + _readBuffer.Length + " DATA DECRYPTED FROM CONN ID: " + conn + " SIZE: " + _encryptionBuffer.Length + "</color>" + " <color=yellow>DELTA: " + (_readBuffer.Length - _encryptionBuffer.Length) + "</color>"); } } break; } } catch (Exception e) { Debug.LogError("Error: " + e); } }
public string Decrypt(string datos, MAEUserSession user) { // Revisa si el parametro esta encriptado (si la cadena es base64) try { var isEncrypted = Convert.FromBase64String(datos); } catch (Exception) { return(datos); } var bytes = Convert.FromBase64String(datos); var eBytes = PublicKeyBox.Open(bytes, Convert.FromBase64String(user.Nonce), Convert.FromBase64String(user.ServerPublic), Convert.FromBase64String(user.ClientSecret)); var txt = Encoding.UTF8.GetString(eBytes); return(txt); }
public static byte[] Decrypt(byte[] encrypted) { byte[] decrypted; ushort id; int length; ushort version; using (var reader = new Reader(encrypted)) { id = reader.ReadUInt16(); length = reader.ReadInt24(); version = reader.ReadUInt16(); } encrypted = encrypted.Skip(2).Skip(3).Skip(2).ToArray(); switch (id) { case 10100: decrypted = encrypted; break; case 10101: ServerConfig.clientPublicKey = encrypted.Take(32).ToArray(); encrypted = encrypted.Skip(32).ToArray(); ServerConfig.clientSharedKey = ServerConfig.clientPublicKey; ServerConfig.clientRNonce = Utils.GenerateRandomBytes(24); byte[] nonce = GenericHash.Hash(ServerConfig.clientPublicKey.Concat(Keys.ServerKey).ToArray(), null, 24); decrypted = PublicKeyBox.Open(encrypted, nonce, ServerConfig.privateKey, ServerConfig.clientPublicKey); ServerConfig.clientSessionKey = decrypted.Take(24).ToArray(); ServerConfig.clientSNonce = decrypted.Skip(24).Take(24).ToArray(); ServerConfig.clientSNonce = ServerConfig.clientSNonce; decrypted = decrypted.Skip(24).Skip(24).ToArray(); Console.WriteLine(BitConverter.ToString(ServerConfig.clientSNonce).Replace("-", "")); Console.WriteLine(BitConverter.ToString(ServerConfig.clientSessionKey).Replace("-", "")); Console.WriteLine(BitConverter.ToString(nonce).Replace("-", "")); Console.WriteLine(BitConverter.ToString(ServerConfig.clientPublicKey).Replace("-", "")); break; default: ServerConfig.clientSNonce = Utilities.Increment(Utilities.Increment(ServerConfig.clientSNonce)); decrypted = SecretBox.Open(new byte[16].Concat(encrypted).ToArray(), ServerConfig.clientSNonce, ServerConfig.clientSharedKey); break; } return(decrypted); }
public static void DecryptPacket(Socket socket, ServerState state, byte[] packet) { int messageId = BitConverter.ToInt32(new byte[2].Concat(packet.Take(2)).Reverse().ToArray(), 0); int payloadLength = BitConverter.ToInt32(new byte[1].Concat(packet.Skip(2).Take(3)).Reverse().ToArray(), 0); int unknown = BitConverter.ToInt32(new byte[2].Concat(packet.Skip(2).Skip(3).Take(2)).Reverse().ToArray(), 0); byte[] cipherText = packet.Skip(2).Skip(3).Skip(2).ToArray(); byte[] plainText; if (messageId == 10100) { plainText = cipherText; } else if (messageId == 10101) { state.clientKey = cipherText.Take(32).ToArray(); byte[] nonce = GenericHash.Hash(state.clientKey.Concat(state.serverKey.PublicKey).ToArray(), null, 24); cipherText = cipherText.Skip(32).ToArray(); plainText = PublicKeyBox.Open(cipherText, nonce, state.serverKey.PrivateKey, state.clientKey); state.sessionKey = plainText.Take(24).ToArray(); state.clientState.nonce = plainText.Skip(24).Take(24).ToArray(); plainText = plainText.Skip(24).Skip(24).ToArray(); } else { state.clientState.nonce = Utilities.Increment(Utilities.Increment(state.clientState.nonce)); plainText = SecretBox.Open(new byte[16].Concat(cipherText).ToArray(), state.clientState.nonce, state.sharedKey); } try { JObject decoded = state.decoder.decode(messageId, 0, plainText); var msg = new Message(messageId, "[C > S] " + decoded["name"], plainText, unknown, state, decoded["fields"].ToString()); MainWindow.Context.AddMessageToQueueLog(msg); } catch (Exception) { var msg = new Message(messageId, "[C > S] " + "Undefined", plainText, unknown, state, ""); MainWindow.Context.AddMessageToQueueLog(msg); } ClientCrypto.EncryptPacket(state.clientState.socket, state.clientState, messageId, unknown, plainText); }
public void CreateAndOpenWithKeyExchangeTest() { var alice = PublicKeyBox.GenerateKeyPair(); var bob = PublicKeyBox.GenerateKeyPair(); var nonce = PublicKeyBox.GenerateNonce(); String message = "Hello, World!"; byte[] byteMessage = System.Text.Encoding.UTF8.GetBytes(message); var encrypted = PublicKeyBox.Create(byteMessage, nonce, alice.Secret, bob.Public); var decrypted = PublicKeyBox.Open(encrypted, nonce, bob.Secret, alice.Public); Assert.AreEqual(decrypted.ToString(), byteMessage.ToString()); var newEncrypted = PublicKeyBox.Create(message, nonce, alice.Secret, bob.Public); Assert.AreEqual(Convert.ToBase64String(encrypted), Convert.ToBase64String(newEncrypted)); var newDecrypted = PublicKeyBox.Open(newEncrypted, nonce, bob.Secret, alice.Public); Assert.AreEqual(decrypted.ToString(), newDecrypted.ToString()); }
public static byte[] Decrypt(byte[] record, byte[] privateKey, byte[] publicKey) { //validate that the version header is right if (record[0] == VERSION) { var offset = 1; var nonce = new byte[NONCE_SIZE_BYTES]; Buffer.BlockCopy(record, 1, nonce, 0, NONCE_SIZE_BYTES); offset += NONCE_SIZE_BYTES; var cipherText = new byte[record.Length - 25]; Buffer.BlockCopy(record, offset, cipherText, 0, record.Length - 25); return(PublicKeyBox.Open(cipherText, nonce, privateKey, publicKey)); } else { //unsupported data versions throw new CryptographicException("Unsupported encrypted format."); } }
public static void DecryptPacket(Socket socket, ServerState state, byte[] packet) { int messageId = BitConverter.ToInt32(new byte[2].Concat(packet.Take(2)).Reverse().ToArray(), 0); int payloadLength = BitConverter.ToInt32(new byte[1].Concat(packet.Skip(2).Take(3)).Reverse().ToArray(), 0); int unknown = BitConverter.ToInt32(new byte[2].Concat(packet.Skip(2).Skip(3).Take(2)).Reverse().ToArray(), 0); byte[] cipherText = packet.Skip(2).Skip(3).Skip(2).ToArray(); byte[] plainText; if (messageId == 10100) { plainText = cipherText; } else if (messageId == 10101) { state.clientKey = cipherText.Take(32).ToArray(); byte[] nonce = GenericHash.Hash(state.clientKey.Concat(state.serverKey.PublicKey).ToArray(), null, 24); cipherText = cipherText.Skip(32).ToArray(); plainText = PublicKeyBox.Open(cipherText, nonce, state.serverKey.PrivateKey, state.clientKey); state.sessionKey = plainText.Take(24).ToArray(); state.clientState.nonce = plainText.Skip(24).Take(24).ToArray(); plainText = plainText.Skip(24).Skip(24).ToArray(); } else { state.clientState.nonce = Utilities.Increment(Utilities.Increment(state.clientState.nonce)); plainText = SecretBox.Open(new byte[16].Concat(cipherText).ToArray(), state.clientState.nonce, state.sharedKey); } try { JObject decoded = state.decoder.decode(messageId, unknown, plainText); Console.WriteLine("{0}: {1}", decoded["name"], decoded["fields"]); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine("{0} {1}", messageId, Utilities.BinaryToHex(BitConverter.GetBytes(messageId).Reverse().Skip(2).Concat(BitConverter.GetBytes(plainText.Length).Reverse().Skip(1)).Concat(BitConverter.GetBytes(unknown).Reverse().Skip(2)).Concat(plainText).ToArray())); } ClientCrypto.EncryptPacket(state.clientState.socket, state.clientState, messageId, unknown, plainText); }
public static byte[] DecryptMessage(byte[] message, KeyPair key) { const int VERSION_LENGTH = 1; const int NONCE_LENGTH = 24; const int SENDER_KEY_LENGTH = 32; const int RECIP_VERIFIER_LENGTH = 16; var version = ArrayHelpers.SubArray(message, 0, VERSION_LENGTH)[0]; byte[] ret; switch (version) { case 0x00: var nonce = ArrayHelpers.SubArray(message, 1, NONCE_LENGTH); var senderKey = ArrayHelpers.SubArray(message, 25, SENDER_KEY_LENGTH); var verifier = ArrayHelpers.SubArray(message, 57, RECIP_VERIFIER_LENGTH); var encrypted = ArrayHelpers.SubArray(message, 73); //check the verifier, to make sure that the message is for this KeyPair before going on var recipVarifier = GenericHash.Hash(ArrayHelpers.ConcatArrays(nonce, key.PublicKey), null, 16); if (Utilities.ByteArrayCompare(verifier, recipVarifier)) { throw new CryptographicException("Invalid verifier; message not encrypted for this key."); } var decrypted = PublicKeyBox.Open(encrypted, nonce, key.PrivateKey, senderKey); ret = decrypted; break; default: //TODO: Unsupported version throw new NotImplementedException(); } return(ret); }