Ejemplo n.º 1
0
    public static string CreateFileSafe(string path, SecureString password, string safeName)
    {
        string[]     files      = Directory.GetFiles(path);
        StreamWriter dataWriter = new StreamWriter(safeName + ".safe");

        foreach (var file in files)
        {
            //File name encryption
            byte[] fileNameBytes = Encoding.Unicode.GetBytes(Path.GetFileName(file));
            string fileName      = AESEncryptor.Encrypt(UniqueHash.SecureHashString("1npr0gramsecretKey"), fileNameBytes);

            System.Console.WriteLine(Path.GetFileName(file));

            byte[] fileData      = File.ReadAllBytes(file);
            string encryptedData = AESEncryptor.Encrypt(password, fileData);

            dataWriter.WriteLine(fileName);
            dataWriter.WriteLine(encryptedData);

            dataWriter.Flush();
        }
        System.Console.WriteLine("Befejezve");
        dataWriter.Dispose();

        return("Sucess");
    }
Ejemplo n.º 2
0
        public Locker <List <LockerKey> > GetNewLocker(string password, string filePath = null)
        {
            AESEncryptor encryptor = new AESEncryptor(_AESSalt, _AESIterations);
            GenericBinarySerializer <List <LockerKey> > serializer = new GenericBinarySerializer <List <LockerKey> >();

            return(new Locker <List <LockerKey> >(encryptor, serializer, password, filePath));
        }
Ejemplo n.º 3
0
        public static string EncryptMySecret()
        {
            //this is your 64-bit key string
            string myKeyString = AESEncryptor.CreateNewKey();

            using (var manager = new EncryptionManager(myKeyString))
            {
                //This is your initializor, or public key
                string iv = AESEncryptor.CreateInitializor();

                //This is how you encrypt with your specified key and iv
                encryptedSecretInfo = manager.Encrypt(secretInfo, iv);
            }


            //you can also encrypt with private keys of int a, b and c
            using (var manager = new EncryptionManager(100, 50, 10))
            {
                //This is your initializor, or public key
                string iv = manager.CreateInitializor();

                //This is your second public key, used with a, b, and c to compute the private key
                long ticks = DateTime.Now.Ticks;

                //This is how you encrypt with your specified key and iv
                encryptedSecretInfo = manager.Encrypt(secretInfo, iv, ticks);
            }

            return(encryptedSecretInfo);
        }
Ejemplo n.º 4
0
        public void Init()
        {
            Aes aes = AESEncryptor.CreateAES("DotnetDownloadConfig");

            byte[] iv = ByteHelper.ParseHexString("0102030405060708090a0a0c0d010208");
            _fileEncryptor = new AESEncryptor(aes.Key, iv);
        }
Ejemplo n.º 5
0
        private bool Validate()
        {
            var message = string.Empty;

            if (string.IsNullOrWhiteSpace(_oldPass))
            {
                message = Translations.GetTranslation()["OldPassValid"].ToString();
            }
            else if (AESEncryptor.decryptPassword(GlobalBase.CurrentUser.Password) != _oldPass)
            {
                message = Translations.GetTranslation()["ResPassCurPassNotMatch"].ToString();
            }
            else if (_newPass.Length < 8 || string.IsNullOrWhiteSpace(_newPass) || _newPass == string.Empty || !Regex.IsMatch(_newPass, @"^[a-zA-Z0-9]{8,}$"))
            {
                message = Translations.GetTranslation()["PassValidation"].ToString();
            }

            if (message != string.Empty)
            {
                Application.Current.Dispatcher.Invoke(new Action((() => { CustomMessageBox.Show(Translations.GetTranslation()["Error"].ToString(), message); })));
                return(false);
            }

            return(true);
        }
Ejemplo n.º 6
0
        public void Locker_Read()
        {
            //Arrange
            string testFilePath = Path.Combine(TestContext.DeploymentDirectory, "existingtestlocker.bin");
            Locker <List <LockerKey> > keyLocker = null;
            Exception exception = null;

            byte[]       salt      = { 1, 2, 3, 4, 5, 6, 7, 8 };
            AESEncryptor encryptor = new AESEncryptor(salt, 1234);
            GenericBinarySerializer <List <LockerKey> > serializer = new GenericBinarySerializer <List <LockerKey> >();

            //Act
            try
            {
                CreateAndSaveLockerWithOneKey(testFilePath, "password", salt, "first", "one");
                keyLocker = new Locker <List <LockerKey> >(encryptor, serializer, "password");
                keyLocker.Open(testFilePath);
            }
            catch (Exception e)
            {
                exception = e;
            }

            //Assert
            Assert.IsNull(exception, $"Was not expecting an exception [{exception?.Message}]");

            Assert.IsNotNull(keyLocker.Keys);
            Assert.AreEqual(1, keyLocker.Keys.Count, "was expecting 1 key");
            var key = keyLocker.Keys.FirstOrDefault(k => k.Key == "first");

            Assert.AreEqual("one", key.Value, "Mismatched first value");
        }
Ejemplo n.º 7
0
        public void Encrypt_MissingKey()
        {
            //Arrange
            string testData = "testing";
            ArgumentNullException exception      = null;
            Exception             otherException = null;

            byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8 };

            //Act
            AESEncryptor encryptor = new AESEncryptor(salt, 1234);

            try
            {
                encryptor.Encrypt(testData.ToBytes(), null);
            }
            catch (ArgumentNullException e)
            {
                exception = e;
            }
            catch (Exception e)
            {
                otherException = e;
            }

            //Assert
            Assert.IsNull(otherException, $"Was expecting an ArgumentNullException [{otherException}]");
            Assert.IsNotNull(exception, "Was expecting an ArgumentNullException exception");
            Assert.AreEqual(exception.ParamName, "password", "Was expecting exception to be for password parameter");
        }
Ejemplo n.º 8
0
        public void Decrypt_Missingkey()
        {
            string encryptedMessage              = "njkP6V+HTbQW2a9nmtAtvnN70XEgWTWUypOMIMu1PtU=";
            ArgumentNullException exception      = null;
            Exception             otherException = null;

            byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8 };

            //Act
            AESEncryptor encryptor = new AESEncryptor(salt, 1234);

            try
            {
                byte[] actualResult = encryptor.Decrypt(Convert.FromBase64String(encryptedMessage), null);
            }
            catch (ArgumentNullException e)
            {
                exception = e;
            }
            catch (Exception e)
            {
                otherException = e;
            }

            //Assert
            Assert.IsNull(otherException, $"Was expecting an ArgumentNullException [{otherException}]");
            Assert.IsNotNull(exception, "Was expecting an ArgumentNullException exception");
            Assert.AreEqual(exception.ParamName, "password", "Was expecting exception to be for password parameter");
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Occurs when the client has been sucessfully authenticated by the loginserver.
        /// Called by UILoginDialog.cs.
        /// </summary>
        /// <param name="Client">The client that received the packet.</param>
        /// <param name="Packet">The packet that was received.</param>
        public static void OnLoginNotify(NetworkClient Client, ProcessedPacket Packet)
        {
            //Should this be stored for permanent access?
            byte[] ServerPublicKey = Packet.ReadBytes(Packet.ReadByte());
            byte[] EncryptedData   = Packet.ReadBytes(Packet.ReadByte());

            AESEncryptor Enc = (AESEncryptor)Client.ClientEncryptor;

            Enc.PublicKey          = ServerPublicKey;
            Client.ClientEncryptor = Enc;
            lock (NetworkFacade.Client)
                NetworkFacade.Client.ClientEncryptor = Enc;

            ECDiffieHellmanCng PrivateKey = Client.ClientEncryptor.GetDecryptionArgsContainer().AESDecryptArgs.PrivateKey;

            byte[] NOnce = Client.ClientEncryptor.GetDecryptionArgsContainer().AESDecryptArgs.NOnce;

            byte[] ChallengeResponse = StaticStaticDiffieHellman.Decrypt(PrivateKey,
                                                                         ECDiffieHellmanCngPublicKey.FromByteArray(ServerPublicKey, CngKeyBlobFormat.EccPublicBlob),
                                                                         NOnce, EncryptedData);

            MemoryStream StreamToEncrypt = new MemoryStream();
            BinaryWriter Writer          = new BinaryWriter(StreamToEncrypt);

            Writer.Write((byte)ChallengeResponse.Length);
            Writer.Write(ChallengeResponse, 0, ChallengeResponse.Length);

            Writer.Write(Client.ClientEncryptor.Username);
            Writer.Write((byte)PlayerAccount.Hash.Length);
            Writer.Write(PlayerAccount.Hash);
            Writer.Flush();

            //Encrypt data using key and IV from server, hoping that it'll be decrypted correctly at the other end...
            Client.SendEncrypted((byte)PacketType.CHALLENGE_RESPONSE, StreamToEncrypt.ToArray());
        }
Ejemplo n.º 10
0
        public MemoryStream SaveToStream()
        {
            MemoryStream stream = null;
            string       json   = m_saveData.ToJSON();

            //Compress the data using LZF compression
            byte[] compressed = null;
            using (MemoryStream compMemStream = new MemoryStream())
            {
                using (StreamWriter writer = new StreamWriter(compMemStream, Encoding.UTF8))
                {
                    writer.Write(json);
                    writer.Close();
                    compressed = CLZF2.Compress(compMemStream.ToArray());
                }
            }
            if (compressed != null)
            {
                byte[] encrypted = AESEncryptor.Encrypt(m_cryptoKey, m_cryptoIV, compressed);

                if (encrypted != null)
                {
                    stream = new MemoryStream();
                    //Write version and headers!
                    byte[] version = SaveUtilities.SerializeVersion(HeaderVersion);
                    stream.Write(version, 0, version.Length);
                    byte[] header = SaveUtilities.SerializeHeader(m_modifiedTime, m_deviceName, SaveUtilities.CalculateMD5Hash(encrypted), encrypted.Length);
                    stream.Write(header, 0, header.Length);
                    //Write encrypted and compressed data to stream
                    stream.Write(encrypted, 0, encrypted.Length);
                }
            }
            return(stream);
        }
Ejemplo n.º 11
0
        private bool ValidateOnLogin()
        {
            try
            {
                var message = string.Empty;

                if (string.IsNullOrWhiteSpace(LoginText))
                {
                    message = Translations.GetTranslation()["EmptyLogin"].ToString();
                }
                else if (Password.Length < 8 || string.IsNullOrWhiteSpace(Password) || Password == string.Empty || !Regex.IsMatch(Password, @"^[a-zA-Z0-9]{8,}$"))
                {
                    message = Translations.GetTranslation()["PassValidation"].ToString();
                }
                else if (UserServiceClient.GetUser(LoginText, AESEncryptor.encryptPassword(Password)) == null)
                {
                    message = Translations.GetTranslation()["LogPassValid"].ToString();
                }

                if (message != string.Empty)
                {
                    Application.Current.Dispatcher.Invoke(new Action((() => { CustomMessageBox.Show(Translations.GetTranslation()["Error"].ToString(), message); })));
                    return(false);
                }

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 12
0
 public void InvalidAESKeyCausesError()
 {
     Assert.Throws(typeof(CryptographicException), () =>
     {
         var encryptor = new AESEncryptor(new byte[] { 20, 19, 29, 28, 13 });
         var data      = Encoding.UTF8.GetBytes("Test message of awesome");
         var encypted  = Convert.ToBase64String(encryptor.Encrypt(data));
     });
 }
Ejemplo n.º 13
0
        public static Locker GetLocker(GlobalArguments arguments)
        {
            IEncryptor encryptor = new AESEncryptor(arguments.Salt.ToBytes(), arguments.Iterations);
            GenericBinarySerializer <Dictionary <string, string> > serializer = new GenericBinarySerializer <Dictionary <string, string> >();
            Locker locker = new Locker(encryptor, serializer, arguments.Password, arguments.LockerPath);

            locker.Open();
            return(locker);
        }
Ejemplo n.º 14
0
    public static byte[] EncryptBytes(byte[] bytes)
    {
        byte[] encrypted = null;

        string[] parts = Encoding.UTF8.GetString(Convert.FromBase64String(PKIV)).Split('/');
        encrypted = AESEncryptor.Encrypt(KeyToBytes(parts[0]), KeyToBytes(parts[1]), bytes);

        return(encrypted);
    }
        public void Init()
        {
            Aes _newAES = AESEncryptor.CreateAES("yanzhiweizhuzhouhunanchina");

            _newAES.IV = new byte[16] {
                0x01, 0x02, 0x03, 0x4, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x4, 0x05, 0x06, 0x07, 0x08
            };
            aesHelper = new AESEncryptor(_newAES.Key, _newAES.IV);
        }
        public void EncryptFileTest()
        {
            string path = $"{IOHelpers.DesktopPath}/test.jpeg";

            // get a handle to the file
            FileInfo fi = new FileInfo(path);

            if (!fi.Exists)
            {
                Assert.Fail("No file to test");
                return;
            }

            // base file name
            string name = Path.GetFileNameWithoutExtension(fi.Name);
            string ext  = fi.Extension.TrimStart(new char[] { '.' });

            // 4.2 Gig limit or throws an exception
            byte[] data = File.ReadAllBytes(path);

            // encrypt
            AESEncryptor  enc     = new AESEncryptor();
            CipherMessage results = enc.Encrypt(data, key);

            // write to file - never overwrite
            using FileStream fs = new FileStream($"{IOHelpers.DesktopPath}/{name}.rayx", FileMode.CreateNew, FileAccess.Write);

            // 4 bytes - write a magic number - which is 'ray' followed by 0
            fs.Write(new byte[] { 0x72, 0x61, 0x79, 0x00 });

            // 2 bytes - write the file format version which is 1.0
            fs.Write(new byte[] { 0x01, 0x00 });

            // 16 bytes - first write the IV out which is 16 bytes
            fs.Write(results.IV, 0, results.IV.Length);

            // 2 bytes - write a delimiator which is 01
            fs.Write(new byte[] { 0x00, 0x01 });

            // write the original extension which is 1+len
            byte[] eb  = Encoding.UTF8.GetBytes(ext);
            byte[] ebl = BitConverter.GetBytes(eb.Length);
            fs.WriteByte(ebl[0]);
            fs.Write(eb);

            // 2 bytes - write a delimiator which is 01
            fs.Write(new byte[] { 0x00, 0x01 });

            // write the encrypted data
            fs.Write(results.CipherBytes, 0, results.CipherBytes.Length);

            // flush and close
            fs.Flush();
            fs.Close();

            Assert.IsTrue(results.CipherBytes.Length > 0);
        }
Ejemplo n.º 17
0
        public JsonResult Create(IFormCollection collection)
        {
            var entity = new AppUserEntity();

            TryUpdateModelAsync(entity);
            entity.Pw = AESEncryptor.Encrypt("123456");
            var result = service.Create(entity, AppUser);

            return(Json(result));
        }
Ejemplo n.º 18
0
        public static TreeNode ListDirectory(AESEncryptor aesEncryptor, string fileName)
        {
            var rootDirectoryInfo = new DirectoryInfo(fileName);
            // var buffer = aesEncryptor.Encrypt(fileName);
            // var encryptedName = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
            TreeNode root = new TreeNode(fileName);

            root.children.Add(CreateDirectoryNode(aesEncryptor, rootDirectoryInfo));
            return(root);
        }
Ejemplo n.º 19
0
        public void can_encrypt_and_decrypt_using_aes()
        {
            var encryptor = new AESEncryptor("SBcvpEo21MnyWamdiPxf1O+kBKk53s5GWRnrv3JoUVQ=", "vLWsT81pAOlk7hKd4cyz5A==");
            var encr      = encryptor.Encrypt("some string");

            var stringy   = Convert.ToBase64String(encr);
            var decryptor = new AESDecryptor("SBcvpEo21MnyWamdiPxf1O+kBKk53s5GWRnrv3JoUVQ=", "vLWsT81pAOlk7hKd4cyz5A==");
            var decr      = decryptor.Decrypt(encr);

            decr.ShouldBe("some string");
        }
Ejemplo n.º 20
0
 private byte[] GetDecryptedBytes()
 {
     if (settings.encryptionType == ES2Settings.EncryptionType.AES128)        // AES 128-bit encryption
     {
         AESEncryptor aesEncryptor = new AESEncryptor(settings.encryptionPassword, MoodkieSecurity.AESBits.BITS128);
         return(aesEncryptor.Decrypt(reader.ReadBytes(reader.ReadInt32())));
     }
     else         // XOR Obfuscation
     {
         return(Obfuscator.Obfuscate(reader.ReadBytes(reader.ReadInt32()), settings.encryptionPassword));
     }
 }
Ejemplo n.º 21
0
 public byte[] GetEncryptedBytes(string password)
 {
     if (settings.encryptionType == ES2Settings.EncryptionType.AES128)        // AES 128-bit encryption
     {
         AESEncryptor aesEncryptor = new AESEncryptor(password, MoodkieSecurity.AESBits.BITS128);
         return(aesEncryptor.Encrypt((writer.BaseStream as MemoryStream).ToArray()));
     }
     else         // XOR Obfuscation
     {
         return(Obfuscator.Obfuscate((writer.BaseStream as MemoryStream).ToArray(), password));
     }
 }
Ejemplo n.º 22
0
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Result ResetPw(int id)
        {
            var entity = Load(id);

            if (entity == null || entity.IsDel)
            {
                return(ResultUtil.Fail("用户不存在或已被删除"));
            }
            string sql = "UPDATE [Base_User] SET Pw=@Pw WHERE Id=@Id";
            var    row = db.Execute(sql, new { Id = id, Pw = AESEncryptor.Encrypt("123456") });

            return(row > 0 ? ResultUtil.Success() : ResultUtil.Fail());
        }
Ejemplo n.º 23
0
        /// <summary>
        /// private constructor to satisfy the singleton base class
        /// </summary>
        private ExtensionManager()
        {
            ExtensionHomePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Definitions.Constants.FolderName);

            if (!Directory.Exists(ExtensionHomePath))
            {
                Directory.CreateDirectory(ExtensionHomePath);
            }

            SettingsFileFullname = Path.Combine(ExtensionHomePath, Definitions.Constants.SettingsFilename);

            Encryptor = new AESEncryptor();
        }
Ejemplo n.º 24
0
        private Locker <List <LockerKey> > CreateAndSaveLockerWithOneKey(string lockerPath, string password, byte[] salt, string key, string value)
        {
            AESEncryptor encryptor = new AESEncryptor(salt, 1234);
            GenericBinarySerializer <List <LockerKey> > serializer = new GenericBinarySerializer <List <LockerKey> >();

            var keyLocker = new Locker <List <LockerKey> >(encryptor, serializer, password);

            keyLocker.Keys.Add(new LockerKey {
                Key = key, Value = value
            });
            keyLocker.Save(lockerPath);
            return(keyLocker);
        }
Ejemplo n.º 25
0
    public static Dictionary <string, object> DecryptDecodeDeserialize(byte[] bytes, Encoding encoding)
    {
        try
        {
            string[] parts = Encoding.UTF8.GetString(Convert.FromBase64String(PKIV)).Split('/');
            return(AESEncryptor.DecryptDecodeDeserialize(KeyToBytes(parts[0]), KeyToBytes(parts[1]), bytes, encoding));
        }
        catch (Exception e)
        {
            Debug.LogError("GameDataUtils (DecryptBytes):: Error Dencrypting Bytes - " + e);
        }

        return(null);
    }
Ejemplo n.º 26
0
        public static int CreateFile(CreateArguments arguments)
        {
            int        result    = 0;
            IEncryptor encryptor = new AESEncryptor(arguments.Salt.ToBytes(), arguments.Iterations);
            GenericBinarySerializer <Dictionary <string, string> > serializer = new GenericBinarySerializer <Dictionary <string, string> >();
            Locker locker = new Locker(encryptor, serializer, arguments.Password, arguments.LockerPath);

            // If ia key name is passed in add the kay to the keys list before saving
            if (String.IsNullOrWhiteSpace(arguments.Key) == false)
            {
                locker.Keys.Add(arguments.Key, arguments.Value);
            }
            locker.Save();
            return(result);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// A client requested login.
        /// </summary>
        /// <param name="Client">NetworkClient instance.</param>
        /// <param name="Packet">ProcessedPacket instance.</param>
        public static void InitialClientConnect(NetworkClient Client, ProcessedPacket Packet)
        {
            Console.WriteLine("Server receives data - test 1");

            PacketStream EncryptedPacket = new PacketStream(0x02, 0);

            EncryptedPacket.WriteHeader();

            ClientPublicKey = Packet.ReadBytes((Packet.ReadByte()));

            AESEncryptor Enc = (AESEncryptor)Client.ClientEncryptor;

            Enc.NOnce              = Packet.ReadBytes((Packet.ReadByte()));
            Enc.PublicKey          = ClientPublicKey;
            Enc.PrivateKey         = ServerPrivateKey;
            Client.ClientEncryptor = Enc;

            //THIS IS IMPORTANT - public key must be derived from private!
            ServerPublicKey = ServerPrivateKey.PublicKey.ToByteArray();

            ChallengeResponse = new byte[16];
            m_Random.GetNonZeroBytes(ChallengeResponse);

            MemoryStream StreamToEncrypt = new MemoryStream();
            BinaryWriter Writer          = new BinaryWriter(StreamToEncrypt);

            Writer.Write(ChallengeResponse, 0, ChallengeResponse.Length);
            Writer.Flush();

            byte[] EncryptedData = StaticStaticDiffieHellman.Encrypt(ServerPrivateKey,
                                                                     ECDiffieHellmanCngPublicKey.FromByteArray(ClientPublicKey, CngKeyBlobFormat.EccPublicBlob), Enc.NOnce,
                                                                     StreamToEncrypt.ToArray());

            EncryptedPacket.WriteUInt16((ushort)(PacketHeaders.UNENCRYPTED +
                                                 (1 + ServerPublicKey.Length) +
                                                 (1 + EncryptedData.Length)));

            EncryptedPacket.WriteByte((byte)ServerPublicKey.Length);
            EncryptedPacket.WriteBytes(ServerPublicKey);
            EncryptedPacket.WriteByte((byte)EncryptedData.Length);
            EncryptedPacket.WriteBytes(EncryptedData);

            Client.Send(EncryptedPacket.ToArray());

            NetworkFacade.Listener.UpdateClient(Client);

            Console.WriteLine("Test 1: passed!");
        }
Ejemplo n.º 28
0
    public static byte[] DecryptBytes(byte[] bytes)
    {
        byte[] decrypted = null;

        try
        {
            string[] parts = Encoding.UTF8.GetString(Convert.FromBase64String(PKIV)).Split('/');
            decrypted = AESEncryptor.Decrypt(KeyToBytes(parts[0]), KeyToBytes(parts[1]), bytes);
        }
        catch (Exception e)
        {
            Debug.LogError("GameDataUtils (DecryptBytes):: Error Dencrypting Bytes - " + e);
        }

        return(decrypted);
    }
Ejemplo n.º 29
0
        public void Decrypt_Success()
        {
            string password         = "******";
            string encryptedMessage = "nQaemyTbqIii/fAy69BLYpo9jl64stTDlRNy4s1d8uM=";
            string expectedResult   = "testing";

            byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8 };

            //Act
            AESEncryptor encryptor = new AESEncryptor(salt, 1234);

            byte[] actualResult = encryptor.Decrypt(Convert.FromBase64String(encryptedMessage), password);

            //Assert
            Assert.IsTrue(actualResult.AreEqual(expectedResult.ToBytes()), "Expected results to match");
        }
Ejemplo n.º 30
0
        public static TreeNode CreateDirectoryNode(AESEncryptor aesEncryptor, DirectoryInfo directoryInfo)
        {
            var node = new TreeNode(directoryInfo.Name);

            // var node = new TreeNode(encryptedName);
            foreach (var directory in directoryInfo.GetDirectories())
            {
                node.children.Add(CreateDirectoryNode(aesEncryptor, directory));
            }

            foreach (var file in directoryInfo.GetFiles())
            {
                node.children.Add(new TreeNode(file.Name));
            }
            return(node);
        }