Exemple #1
0
    private void Start()
    {
        int x = NativeLibsodium.sodium_init();

        Debug.Log(x);


        const string MESSAGE = "Test message to encrypt";

        byte[] nonce = StreamEncryption.GenerateNonceChaCha20();
        byte[] key   = StreamEncryption.GenerateKey();

        //encrypt it
        byte[] encrypted = StreamEncryption.EncryptChaCha20(MESSAGE, nonce, key);


        //decrypt it
        byte[] decrypted = StreamEncryption.DecryptChaCha20(encrypted, nonce, key);

        string str_origin    = MESSAGE;
        string str_encrypted = Encoding.UTF8.GetString(encrypted);
        string str_decrypted = Encoding.UTF8.GetString(decrypted);

        Debug.Log(str_origin);
        Debug.Log(str_encrypted);
        Debug.Log(str_decrypted);

        txt_origin.text    = str_origin;
        txt_encrypted.text = str_encrypted;
        txt_decrypted.text = str_decrypted;
    }
Exemple #2
0
        public static byte[] EncryptData(byte[] data, byte[] key)
        {
            long cipherTextLength = data.Length + 16;

            byte[] cipherText = new byte[cipherTextLength];
            byte[] nonce      = StreamEncryption.GetRandomBytes(X_NONC_ESIZE);

            int result = NativeLibsodium.crypto_aead_xchacha20poly1305_ietf_encrypt(
                cipherText,
                out cipherTextLength,
                data,
                data.Length,
                null, 0, null,
                nonce,
                key);

            if (result != 0)
            {
                throw new EncryptionError();
            }

            byte[] cipherTextWithNonce = ConcatNonceAndCipherText(nonce, cipherText);

            return(cipherTextWithNonce);
        }
        private void DeserializeObjects(Block block, byte[] data)
        {
            using (var ms = new MemoryStream(data))
            {
                using (var br = new BinaryReader(ms))
                {
                    // Version:
                    var context = new BlockDeserializeContext(br, _typeProvider);

                    // Nonce:
                    var nonce = context.br.ReadBuffer();
                    if (nonce != null)
                    {
                        // Data:
                        using (var dms = new MemoryStream(StreamEncryption.EncryptChaCha20(context.br.ReadBuffer(), nonce, _typeProvider.SecretKey)))
                        {
                            using (var dbr = new BinaryReader(dms))
                            {
                                var dc = new BlockDeserializeContext(dbr, _typeProvider);
                                block.DeserializeObjects(dc);
                            }
                        }
                    }
                    else
                    {
                        // Data:
                        block.DeserializeObjects(context);
                    }
                }
            }
        }
 public void StreamEncryptionEncryptChaCha20BadNonce()
 {
     StreamEncryption.EncryptChaCha20(
         Encoding.UTF8.GetBytes("Adam Caudill"),
         Encoding.UTF8.GetBytes("ABC"),
         Encoding.UTF8.GetBytes("12345678901234567890123456789012"));
 }
 public void StreamEncryptionDecryptBadNonce()
 {
     StreamEncryption.Decrypt(
         Utilities.HexToBinary("c7b7f04c00e14b02dd56c78c"),
         Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVW"),
         Encoding.UTF8.GetBytes("12345678901234567890123456789012"));
 }
        public void XSalsa20Test()
        {
            var    key     = StreamEncryption.GenerateKey();
            var    nonce   = StreamEncryption.GenerateNonce();
            string message = "Hello, World!";

            var cipherText = StreamEncryption.Encrypt(message, nonce, key);
            var decrypted  = StreamEncryption.Decrypt(cipherText, nonce, key);

            Assert.AreEqual(message, System.Text.Encoding.UTF8.GetString(decrypted));

            byte[] byteMessage = System.Text.Encoding.UTF8.GetBytes(message);
            cipherText = StreamEncryption.Encrypt(byteMessage, nonce, key);
            decrypted  = StreamEncryption.Decrypt(cipherText, nonce, key);
            Assert.AreEqual(Convert.ToBase64String(byteMessage), Convert.ToBase64String(decrypted));

            cipherText = StreamEncryption.EncryptXSalsa20(message, nonce, key);
            decrypted  = StreamEncryption.DecryptXSalsa20(cipherText, nonce, key);
            Assert.AreEqual(message, System.Text.Encoding.UTF8.GetString(decrypted));

            byteMessage = System.Text.Encoding.UTF8.GetBytes(message);
            cipherText  = StreamEncryption.EncryptXSalsa20(byteMessage, nonce, key);
            decrypted   = StreamEncryption.DecryptXSalsa20(cipherText, nonce, key);
            Assert.AreEqual(Convert.ToBase64String(byteMessage), Convert.ToBase64String(decrypted));
        }
Exemple #7
0
 private static void EncryptFile(string filePath, string encryptedFilePath, byte[] salt, byte[] encryptionKey, byte[] macKey)
 {
     try
     {
         using (var ciphertext = new FileStream(encryptedFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, Constants.FileBufferSize, FileOptions.SequentialScan))
             using (var plaintext = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, Constants.FileBufferSize, FileOptions.SequentialScan))
             {
                 WriteFileHeaders.WriteHeaders(ciphertext, salt);
                 byte[] fileBytes = FileHandling.GetBufferSize(plaintext.Length);
                 // Generate a counter starting at 0
                 byte[] counter = Generate.Counter();
                 int    bytesRead;
                 MemoryEncryption.DecryptByteArray(ref encryptionKey);
                 while ((bytesRead = plaintext.Read(fileBytes, 0, fileBytes.Length)) > 0)
                 {
                     byte[] encryptedBytes = StreamEncryption.EncryptXChaCha20(fileBytes, counter, encryptionKey);
                     ciphertext.Write(encryptedBytes, 0, bytesRead);
                     counter = Sodium.Utilities.Increment(counter);
                 }
             }
         Utilities.ZeroArray(encryptionKey);
         CompleteEncryption(filePath, encryptedFilePath, macKey);
     }
     catch (Exception ex) when(ExceptionFilters.FileEncryptionExceptions(ex))
     {
         Logging.LogException(ex.ToString(), Logging.Severity.High);
         DisplayMessage.Error(filePath, ex.GetType().Name, "Unable to encrypt the file.");
         FileHandling.DeleteFile(encryptedFilePath);
         Utilities.ZeroArray(encryptionKey);
         Utilities.ZeroArray(macKey);
     }
 }
Exemple #8
0
    void Start()
    {
        if (UseStream)
        {
            StreamEncryption.DecryptAssetBundle(Application.streamingAssetsPath + "/assets/cube.ab", "Cube", (prefab) => {
                var obj = GameObject.Instantiate <GameObject>(prefab as GameObject);
                obj.transform.localPosition = new Vector3(0, 0, 0);
                obj.transform.localRotation = Quaternion.Euler(0, 0, 0);
            });

            StartCoroutine(StreamEncryption.AsyncLoad(Application.streamingAssetsPath + "/assets/cube.ab", "Cube", (prefab) => {
                var obj = GameObject.Instantiate <GameObject>(prefab as GameObject);
                obj.transform.localPosition = new Vector3(0, 0, 0);
                obj.transform.localRotation = Quaternion.Euler(0, 0, 0);
                //为什么会有rotation,属性窗口有数值,但是右键reset,物体也没变化,就是000的
            }));
        }
        else
        {
            AESEncryption.DecryptAssetBundle(Application.streamingAssetsPath + "/assets/cube.ab", "Cube", (prefab) => {
                var obj = GameObject.Instantiate <GameObject>(prefab as GameObject);
                obj.transform.localPosition = new Vector3(0, 0, 0);
                obj.transform.localRotation = Quaternion.Euler(0, 0, 0);
            });

            StartCoroutine(AESEncryption.AsyncLoad(Application.streamingAssetsPath + "/assets/cube.ab", "Cube", (prefab) => {
                var obj = GameObject.Instantiate <GameObject>(prefab as GameObject);
                obj.transform.localPosition = new Vector3(0, 0, 0);
                obj.transform.localRotation = Quaternion.Euler(0, 0, 0);
                //为什么会有rotation,属性窗口有数值,但是右键reset,物体也没变化,就是000的
            }));
        }
    }
 public void StreamEncryptionDecryptChaCha20BadKey()
 {
     StreamEncryption.DecryptChaCha20(
         Utilities.HexToBinary("a6ce598d8b865fb328581bcd"),
         Encoding.UTF8.GetBytes("ABCDEFGH"),
         Encoding.UTF8.GetBytes("123456789012345678901234567890"));
 }
 public void StreamEncryptionEncryptChaCha20BadKey()
 {
     StreamEncryption.EncryptChaCha20(
         Encoding.UTF8.GetBytes("Adam Caudill"),
         Encoding.UTF8.GetBytes("ABCDEFGH"),
         Encoding.UTF8.GetBytes("123456789012345678901234567890"));
 }
Exemple #11
0
 private static void DecryptFile(string filePath, int parametersLength, byte[] macBackup, byte[] encryptionKey)
 {
     try
     {
         string decryptedFilePath = Regex.Replace(filePath, Constants.EncryptedExtension, string.Empty);
         int    headersLength     = Constants.SaltLength + parametersLength;
         using (var plaintext = new FileStream(decryptedFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, Constants.FileBufferSize, FileOptions.SequentialScan))
             using (var ciphertext = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, Constants.FileBufferSize, FileOptions.SequentialScan))
             {
                 // Skip the header bytes
                 ciphertext.Seek(headersLength, SeekOrigin.Begin);
                 byte[] fileBytes = FileHandling.GetBufferSize(ciphertext.Length);
                 // Generate a counter starting at 0
                 byte[] counter = Generate.Counter();
                 int    bytesRead;
                 MemoryEncryption.DecryptByteArray(ref encryptionKey);
                 while ((bytesRead = ciphertext.Read(fileBytes, 0, fileBytes.Length)) > 0)
                 {
                     byte[] decryptedBytes = StreamEncryption.DecryptXChaCha20(fileBytes, counter, encryptionKey);
                     plaintext.Write(decryptedBytes, 0, bytesRead);
                     counter = Sodium.Utilities.Increment(counter);
                 }
                 Utilities.ZeroArray(encryptionKey);
             }
         CompleteDecryption(filePath, decryptedFilePath);
     }
     catch (Exception ex) when(ExceptionFilters.FileEncryptionExceptions(ex))
     {
         Logging.LogException(ex.ToString(), Logging.Severity.High);
         DisplayMessage.Error(filePath, ex.GetType().Name, "Unable to decrypt the file.");
         Utilities.ZeroArray(encryptionKey);
         RestoreMAC(filePath, macBackup);
     }
 }
 public void StreamEncryptionEncryptBadNonce()
 {
     StreamEncryption.Encrypt(
         Encoding.UTF8.GetBytes("Adam Caudill"),
         Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVW"),
         Encoding.UTF8.GetBytes("12345678901234567890123456789012"));
 }
Exemple #13
0
        public ConnectPacketData GetConnectPacket()
        {
            var connectPacketData = new ConnectPacketData
            {
                AddressType  = _connection.AddressType,
                DestPort     = _connection.DestPort,
                RouteCount   = (uint)_connection.ReturnRoutes.Length,
                ReturnRoutes = // TODO
            };

            if (_connection.AddressType == DestAddressType.DomainName)
            {
                connectPacketData.DestDomainName = _connection.DestDomainName;
            }
            else
            {
                connectPacketData.DestIpAddress = _connection.DestIpAddress;
            }

            var bytesToEncrypt = new byte[PacketContent.MaxSendDataLen + 27];

            var buffer = new WriteBuffer(bytesToEncrypt, 0);

            buffer.Write(_connection.UserId);
            buffer.Write(_connection.ConnectionId);
            buffer.Write(_connection.NextSequenceId);
            buffer.Write((byte)PacketDataType.Connect);
            buffer.Write(connectPacketData);
            var paddingLength = bytesToEncrypt.Length - buffer.TotalWritten;

            buffer.Write(new byte[paddingLength]);

            var route     = GenerateRoute(_possibleNodes);
            var encrypted = SecretBox.Create(bytesToEncrypt, OneNonce, route.Nodes[2].SymmetricKey);

            var destIdAndDataLen = new byte[10];

            buffer.Buffer = destIdAndDataLen;
            buffer.Write((ulong)0);
            buffer.Write((ushort)(encrypted.Length - 16));

            var innerPacketBytes = new byte[bytesToEncrypt.Length + 67];

            buffer.Buffer = innerPacketBytes;

            buffer.Write(route.Nodes[2].Node.Id);
            buffer.Write(route.Nodes[2].EphemeralPublicKey);
            buffer.Write((byte)(route.Nodes[2].SymmetricKey[31] & 1));
            buffer.Write(StreamEncryption.EncryptChaCha20(destIdAndDataLen, ZeroNonce, route.Nodes[2].SymmetricKey));
            buffer.Write(encrypted);

            encrypted = SecretBox.Create(encrypted, OneNonce, route.Nodes[2].SymmetricKey);

            var destId = new byte[8];

            buffer.Buffer = destId;
            buffer.Write(route.Nodes[1].Node.Id);
        }
 public void CreateSecretBox()
 {
     var expected = Utilities.HexToBinary("c7b7f04c00e14b02dd56c78c");
     var actual = StreamEncryption.Encrypt(
       Encoding.UTF8.GetBytes("Adam Caudill"),
       Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
       Encoding.UTF8.GetBytes("12345678901234567890123456789012"));
     Assert.AreEqual(expected, actual);
 }
 public void CreateSecretBoxXChaCha20()
 {
     var expected = Utilities.HexToBinary("b99341769d6d1342541de1ad");
     var actual = StreamEncryption.EncryptXChaCha20(
       Encoding.UTF8.GetBytes("Adam Caudill"),
       Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
       Encoding.UTF8.GetBytes("12345678901234567890123456789012"));
     Assert.AreEqual(expected, actual);
 }
 public void OpenSecretBoxChaCha20()
 {
     const string EXPECTED = "Adam Caudill";
     var actual = Encoding.UTF8.GetString(StreamEncryption.DecryptChaCha20(
       Utilities.HexToBinary("a6ce598d8b865fb328581bcd"),
       Encoding.UTF8.GetBytes("ABCDEFGH"),
       Encoding.UTF8.GetBytes("12345678901234567890123456789012")));
     Assert.AreEqual(EXPECTED, actual);
 }
 public void CreateSecretBoxChaCha20()
 {
     var expected = Utilities.HexToBinary("a6ce598d8b865fb328581bcd");
     var actual = StreamEncryption.EncryptChaCha20(
       Encoding.UTF8.GetBytes("Adam Caudill"),
       Encoding.UTF8.GetBytes("ABCDEFGH"),
       Encoding.UTF8.GetBytes("12345678901234567890123456789012"));
     Assert.AreEqual(expected, actual);
 }
 public void OpenSecretBox()
 {
     const string EXPECTED = "Adam Caudill";
     var actual = Encoding.UTF8.GetString(StreamEncryption.Decrypt(
       Utilities.HexToBinary("c7b7f04c00e14b02dd56c78c"),
       Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
       Encoding.UTF8.GetBytes("12345678901234567890123456789012")));
     Assert.AreEqual(EXPECTED, actual);
 }
 public void OpenSecretBoxXChaCha20()
 {
     const string EXPECTED = "Adam Caudill";
     var actual = Encoding.UTF8.GetString(StreamEncryption.DecryptXChaCha20(
       Utilities.HexToBinary("b99341769d6d1342541de1ad"),
       Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
       Encoding.UTF8.GetBytes("12345678901234567890123456789012")));
     Assert.AreEqual(EXPECTED, actual);
 }
Exemple #20
0
        /// <summary>
        /// Creates a QuickPass from the given <paramref name="password"/> and
        /// <paramref name="imk"/> using the QuickPass settings stored in
        /// <paramref name="identity"/>, stores it in memory and establishes a
        /// timer that will clear the QuickPass after the timeout set forth in
        /// <paramref name="identity"/>'s QuickPass settings.
        /// </summary>
        /// <param name="password">The full identity master password.</param>
        /// <param name="imk">The identity's unencrypted Identity Master Key (IMK).</param>
        /// <param name="ilk">The identity's unencrypted Identity Lock Key (ILK).</param>
        /// <param name="identity">The identity that the QuickPass should be set for.</param>
        /// <param name="progress">An object implementing the IProgress interface for tracking the operation's progress (optional).</param>
        /// <param name="progressText">A string representing a text descrition for the progress indicator (optional).</param>
        public async void SetQuickPass(string password, byte[] imk, byte[] ilk, SQRLIdentity identity, IProgress <KeyValuePair <int, string> > progress = null, string progressText = null)
        {
            if (string.IsNullOrEmpty(password))
            {
                Log.Warning("Can't use QuickPass on an empty password, aborting SetQuickPass()!");
                return;
            }

            QuickPassItem qpi = new QuickPassItem()
            {
                EstablishedDate               = DateTime.Now,
                QuickPassLength               = identity.Block1.HintLength,
                IdentityUniqueId              = identity.Block0.UniqueIdentifier.ToHex(),
                ScryptRandomSalt              = SodiumCore.GetRandomBytes(16),
                Nonce                         = SodiumCore.GetRandomBytes(24),
                QuickPassTimeoutSecs          = identity.Block1.PwdTimeoutMins * 60,
                ClearQuickPassOnIdle          = identity.Block1.OptionFlags.ClearQuickPassOnIdle,
                ClearQuickPassOnSleep         = identity.Block1.OptionFlags.ClearQuickPassOnSleep,
                ClearQuickPassOnSwitchingUser = identity.Block1.OptionFlags.ClearQuickPassOnSwitchingUser,
                Timer                         = new Timer()
            };

            qpi.Timer.Enabled   = false;
            qpi.Timer.AutoReset = false; // Dont restart timer after calling elapsed
            qpi.Timer.Interval  = QP_GENERAL_TIMEOUT_SEC;
            qpi.Timer.Elapsed  += QuickPassTimerElapsed;

            string quickPass = password.Substring(0, qpi.QuickPassLength);

            var enScryptResult = await SQRL.EnScryptTime(
                quickPass,
                qpi.ScryptRandomSalt,
                (int)Math.Pow(2, 9),
                QP_KEYDERIV_SEC,
                progress,
                progressText);

            qpi.ScryptIterationCount = enScryptResult.IterationCount;
            qpi.EncryptedImk         = StreamEncryption.Encrypt(imk, qpi.Nonce, enScryptResult.Key);
            qpi.EncryptedIlk         = StreamEncryption.Encrypt(ilk, qpi.Nonce, enScryptResult.Key);

            // If we already have a QuickPass entry for this identity, remove it first
            if (HasQuickPass(qpi.IdentityUniqueId))
            {
                ClearQuickPass(qpi.IdentityUniqueId, QuickPassClearReason.Unspecified);
            }

            // Now, add the QuickPass item to our list and start the timer
            lock (_dataSyncObj)
            {
                _quickPassItems.Add(qpi.IdentityUniqueId, qpi);
                qpi.Timer.Start();
            }

            Log.Information("QuickPass set for identity {IdentityUniqueId}",
                            qpi.IdentityUniqueId);
        }
Exemple #21
0
 private static T DecryptStream <T>(
     BinaryReader reader,
     Func <BinaryReader, T> read)
 {
     using (BinaryReader decryptedReader =
                StreamEncryption.DecryptStream(SAVE_KEY, reader))
     {
         return(read(decryptedReader));
     }
 }
        public void Stream_Encryption_Basic()
        {
            var nonce         = StreamEncryption.GenerateNonceChaCha20();
            var key           = StreamEncryption.GenerateKey();
            var messageString = "Test message to encrypt";
            var encrypted     = StreamEncryption.EncryptChaCha20(messageString, nonce, key);
            var decrypted     = StreamEncryption.DecryptChaCha20(encrypted, nonce, key);

            Assert.AreEqual(messageString, Encoding.UTF8.GetString(decrypted));
        }
Exemple #23
0
        /// <summary>
        /// Encrypts data with the current session key.
        /// </summary>
        /// <returns>The encrypted data.</returns>
        /// <param name="message">Data to encrypt.</param>
        public byte[] EncryptWithSessionKey(byte[] message)
        {
            byte[] nonce = IEncryption.ConcatBytes(StreamEncryption.GetRandomBytes(X_NONC_ESIZE - 16), BitConverter.GetBytes(DateTime.UtcNow.Ticks), BitConverter.GetBytes(sessionSendKey.index));
            byte[] cipherTextWithNonce = EncryptData(message, GetCurrentSendKey(), nonce);

            // ratchat forward
            RatchetSendKey();

            return(cipherTextWithNonce);
        }
 public void StreamEncryptionEncryptChaCha20BadNonce()
 {
     Assert.Throws <NonceOutOfRangeException>(() =>
     {
         StreamEncryption.EncryptChaCha20(
             Encoding.UTF8.GetBytes("Adam Caudill"),
             Encoding.UTF8.GetBytes("ABC"),
             Encoding.UTF8.GetBytes("12345678901234567890123456789012"));
     });
 }
 public void StreamEncryptionDecryptBadNonce()
 {
     Assert.Throws <NonceOutOfRangeException>(() =>
     {
         StreamEncryption.Decrypt(
             Utilities.HexToBinary("c7b7f04c00e14b02dd56c78c"),
             Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVW"),
             Encoding.UTF8.GetBytes("12345678901234567890123456789012"));
     });
 }
 public void StreamEncryptionEncryptBadNonce()
 {
     Assert.Throws <NonceOutOfRangeException>(() =>
     {
         StreamEncryption.Encrypt(
             Encoding.UTF8.GetBytes("Adam Caudill"),
             Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVW"),
             Encoding.UTF8.GetBytes("12345678901234567890123456789012"));
     });
 }
 public void StreamEncryptionDecryptChaCha20BadNonce()
 {
     Assert.Throws <NonceOutOfRangeException>(() =>
     {
         StreamEncryption.DecryptChaCha20(
             Utilities.HexToBinary("a6ce598d8b865fb328581bcd"),
             Encoding.UTF8.GetBytes("ABC"),
             Encoding.UTF8.GetBytes("12345678901234567890123456789012"));
     });
 }
Exemple #28
0
 private static void DecryptStream(
     BinaryReader reader,
     Action <BinaryReader> read)
 {
     using (BinaryReader decryptedReader =
                StreamEncryption.DecryptStream(SAVE_KEY, reader))
     {
         read(decryptedReader);
     }
 }
Exemple #29
0
 private static byte[] DecryptFileBytes(byte[] fileBytes, byte[] nonce, byte[] key)
 {
     byte[] decryptedBytes = new byte[fileBytes.Length];
     if (Globals.EncryptionAlgorithm == (int)Cipher.XChaCha20)
     {
         decryptedBytes = StreamEncryption.DecryptXChaCha20(fileBytes, nonce, key);
     }
     else if (Globals.EncryptionAlgorithm == (int)Cipher.XSalsa20)
     {
         decryptedBytes = StreamEncryption.Decrypt(fileBytes, nonce, key);
     }
     return(decryptedBytes);
 }
    public byte[] Encrypt(byte[] message, long nonce, bool isInvalidClientPayload = false)
    {
        byte[] messageVar = new byte[] { };
        if (isInvalidClientPayload)
        {
            messageVar = StreamEncryption.EncryptChaCha20(message, BitConverter.GetBytes(nonce), Convert.FromBase64String(ChaChaEncryptionKey2));
        }
        else
        {
            messageVar = StreamEncryption.EncryptChaCha20(message, BitConverter.GetBytes(nonce), Convert.FromBase64String(ChaChaEncryptionKey));
        }

        return(messageVar);
    }