Exemplo n.º 1
0
        public IHttpActionResult updateUserAndPassword(int id, usuario usuario)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != usuario.id_usuario)
            {
                return(BadRequest());
            }
            usuario.password        = AES256.encryptPassword(usuario.password);
            usuario.rol             = db.rols.Find(usuario.id_rol);
            db.Entry(usuario).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!usuarioExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemplo n.º 2
0
        public static byte[] getCCD()
        {
            LogManager.WriteLine("--- Get CCD ---");
            byte[] ccdcBytes = (byte[])StorageUtils.getData(StorageUtils.kCCDC);
            LogManager.WriteLine("CCDC: ");
            PrintByteArray(ccdcBytes);
            byte[] cccBytes;
            if (!StorageUtils.IsStoredFlagActive(StorageUtils.kIsBlockingCodeActive))
            {
                cccBytes = PBKDF2.calculateCCCwithIDA(StorageUtils.getIDA());
            }
            else
            {
                try
                {
                    cccBytes = PBKDF2.calculateCCCwithCodBlq(lockCode, StorageUtils.getIDA());
                }
                catch (Exception)
                {
                    throw new LockCodeException();
                }
            }

            LogManager.WriteLine("CCC: ");
            PrintByteArray(cccBytes);
            byte[] ccdBytes = AES256.DecryptAES256CBC(StorageUtils.getAppIV(), ccdcBytes, cccBytes);
            LogManager.WriteLine("CCD: ");
            PrintByteArray(ccdBytes);
            return(ccdBytes);
        }
Exemplo n.º 3
0
        public IHttpActionResult Postusuario(usuario usuario)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (usuario.productos == null)
            {
            }
            else
            {
                int count = usuario.productos.Count;

                for (int i = 0; i < usuario.productos.Count; i++)
                {
                    producto pproducto = usuario.productos.ElementAt(i);
                    usuario.productos.Remove(pproducto);
                    usuario.productos.Add(db.productos.Find(pproducto.id_producto));
                }
            }
            usuario.password = AES256.encryptPassword(usuario.password);
            db.usuarios.Add(usuario);
            db.SaveChanges();
            historial_contrasennas historial = new historial_contrasennas();

            historial.id_usuario = usuario.id_usuario;
            historial.contraseña = usuario.password;
            db.historial_contrasennas.Add(historial);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = usuario.id_usuario }, usuario));
        }
Exemplo n.º 4
0
        public void Aes_EncryptFile_Test()
        {
            //Arrange
            var tempPath = Path.GetTempPath();

            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            var path         = $"{tempPath}Security.txt";
            var originalData = Resources.ResourceManager.GetString("Security");

            File.WriteAllText(path, originalData);

            var encryptedPath = $"{tempPath}Security.encrypt";
            var decryptPath   = $"{tempPath}security2.txt";
            var aes           = new AES256();

            //Act
            aes.EncryptFile(EncryptionKey, path, encryptedPath);
            aes.DecryptFile(EncryptionKey, encryptedPath, decryptPath);

            var inputFile  = File.ReadAllText(path);
            var outputFile = File.ReadAllText(decryptPath);

            //Assert
            Assert.AreEqual(inputFile, outputFile);

            File.Delete(path);
            File.Delete(encryptedPath);
            File.Delete(decryptPath);
        }
        public GenerateTokenOut GenerateToken(GenerateTokenIn input)
        {
            var    output          = new GenerateTokenOut();
            AES256 securityAES256  = new AES256();
            var    expireMinutes   = TokenExpireMinutes;
            var    symmetricKey    = Convert.FromBase64String(TokenSecret);
            var    tokenHandler    = new JwtSecurityTokenHandler();
            var    now             = DateTime.UtcNow;
            var    tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim("sessionId", input.sessionId),
                    new Claim("usrID", input.usrID.ToString())
                }),

                Expires            = now.AddMinutes(expireMinutes),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature)
            };
            var stoken = tokenHandler.CreateToken(tokenDescriptor);
            var token  = tokenHandler.WriteToken(stoken);

            output.token = securityAES256.Encrypt(token);
            return(output);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Retrieves an AES 256 encrypted value from the configuration file.
        /// </summary>
        /// <param name="log">The event log to log exceptions to. May be null for no logging.</param>
        /// <returns>The value or null if not found or it could not be decrypted.</returns>
        protected string SecureGet(EventLog.EventLog log)
        {
            // Get the raw value of the encrypted string.
            string value = Get(log);

            // Decrypt the string if the raw value contains one.
            if (!string.IsNullOrWhiteSpace(value))
            {
                // Get the encrypted string containing the key, initialization vector, value, and key and
                // initialization vector lengths from the file.
                // Read only the first line of the file, as this is all that is necessary for the encrypted
                // format.
                StringReader reader         = new StringReader(Get(log));
                string       encryptedValue = reader.ReadLine();

                // Check that an encrypted value was retrieved.
                if (!string.IsNullOrWhiteSpace(encryptedValue))
                {
                    // The encrypted value was retrieved.

                    // Decrypt the encrypted value.
                    return(AES256.DecryptConsolidatedString(encryptedValue));
                }
            }
            // Could not retrieve the encrypted value.
            return(null);
        }
Exemplo n.º 7
0
        public void EncryptAndDecryptString()
        {
            string encrypted = AES256.Encrypt("test", "password");
            string decrypted = AES256.Decrypt(encrypted, "password");

            Assert.AreEqual(decrypted, "test");
        }
Exemplo n.º 8
0
        public static string SendCommand(string Text, HenkTcpClient Client, byte[] EncryptionKeyServer, string Password, byte[] Salt)
        {
            if (Text.Equals("!users"))
            {
                int Online = BitConverter.ToInt32(Client.WriteAndGetReply(new byte[] { 42, 6, 1 }, TimeSpan.FromSeconds(1)).DecryptedData, 0);

                string Users = string.Empty;
                for (int x = 0; x < Online; x++)
                {
                    Users += ", " + AES256.decrypt(Client.WriteAndGetReply(CombineBytes(new byte[] { 42, 6, 1 }, BitConverter.GetBytes(x)), TimeSpan.FromSeconds(1)).Data, Password, Salt);
                }
                return($"({Online}) {Users.Remove(0, 2)}");
            }
            if (Text.StartsWith("!admin "))
            {
                Rfc2898DeriveBytes HashedAdminPassword = new Rfc2898DeriveBytes(Text.Remove(0, 7), Salt, 500000);
                return(_SendCommand(CombineBytes(new byte[] { 42, 6 }, HenkTcp.Encryption.Encrypt(Aes.Create(), Encoding.UTF8.GetBytes("!admin " + Convert.ToBase64String(HashedAdminPassword.GetBytes(20))), EncryptionKeyServer)), Client));
            }
            else if (Text.StartsWith("!kick "))
            {
                return(_SendCommand(CombineBytes(new byte[] { 42, 6, 2 }, AES256.encrypt(Text.Remove(0, 6), Password, Salt)), Client));
            }
            else if (Text.StartsWith("!ban "))
            {
                return(_SendCommand(CombineBytes(new byte[] { 42, 6, 3 }, AES256.encrypt(Text.Remove(0, 5), Password, Salt)), Client));
            }
            else
            {
                return(_SendCommand(CombineBytes(new byte[] { 42, 6 }, HenkTcp.Encryption.Encrypt(Aes.Create(), Encoding.UTF8.GetBytes(Text), EncryptionKeyServer)), Client));
            }
        }
Exemplo n.º 9
0
 /// <summary>
 /// Initializes all required instances.
 /// </summary>
 public CipherRegister()
 {
     aes256     = new AES256();
     des        = new DES();
     psi_128bit = new implementations.psi.utility.UsageHelper_Crypto();
     rsa2048    = new RSA2048();
     tripledes  = new TripleDES();
 }
Exemplo n.º 10
0
        static void Main()
        {
            string teste = "{ola:\"mundo\"}";

            byte[] testeB = Encoding.UTF8.GetBytes(teste);

            AES256 aes = new AES256();

            Console.WriteLine(Encoding.UTF8.GetString(aes.Decrypt(aes.Encrypt(testeB))));
        }
        /**
         * Repete o mesmo procedimento de encriptação e compara as hashs resultantes com
         * o que está salvo no banco de dados.
         */
        public static bool Uncrypt(string password, string hash, string username)
        {
            string hashedPassword    = SHA_256.GenerateSHA256String(password);
            string nounced           = hashedPassword + username;
            string myHash            = BCrypt.HashPassword(nounced, hash);
            string mySalt            = myHash.Substring(0, 29);
            string result            = mySalt + AES256.AES_Encrypt(myHash.Substring(29, myHash.Length - 29));
            bool   doesPasswordMatch = Pepper.Check(result, hash, mySalt);

            return(doesPasswordMatch);
        }
        /**
         * O procedimento é:
         * - recebe senha X
         * - Hasheia X com SHA256, resultando em Y
         * - "Acopla" o nounce (login) no final deste resultado (Y), resultando em Z
         * - gera um Salt aleatório, com 29 caracteres
         * - Utiliza o BCrypt para gerar outra hash, sendo esta resultado do Salt + Z, resultando em W
         * - Como os primeiros 29 caracteres de W são o proprio salt, encripta-se, com o AES, apenas os caracteres que não fazem parte do Salt, resultando Salt + R
         * - aclopa-se, então, uma Pepper aleatória ao final da string, sendo esta, agora, composta por Salt + R + Pepper; resultando em G
         * - Por fim, hasheia-se G com SHA512 e adiciona ao início da string o Salt; resultando em Salt+F
         */
        public static string Encrypt(string password, string username)
        {
            string hashedPassword = SHA_256.GenerateSHA256String(password);
            string nounced        = hashedPassword + username;
            string mySalt         = BCrypt.GenerateSalt();
            string myHash         = BCrypt.HashPassword(nounced, mySalt);
            string result         = mySalt + AES256.AES_Encrypt(myHash.Substring(29, myHash.Length - 29)) + Pepper.Generate();

            result = mySalt + SHA_512.GenerateSHA512String(result);
            return(result);
        }
Exemplo n.º 13
0
        public void Aes_StringEncryption_Test()
        {
            //Arrange
            var data = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
            var aes  = new AES256();
            //Act
            var encryptedString = aes.EncryptString(data, EncryptionKey);
            var result          = aes.DecryptString(encryptedString, EncryptionKey);

            //Assert
            Assert.AreEqual(data, result);
        }
Exemplo n.º 14
0
 public void Configure(EntityTypeBuilder <User> builder)
 {
     builder.HasData(new User
     {
         CompanyId = 1,
         Email     = AES256.EncryptAndEncode("*****@*****.**"),
         Password  = AES256.EncryptAndEncode("test"),
         FirstName = "test",
         LastName  = "test",
         Status    = true
     });
 }
Exemplo n.º 15
0
        public void EncryptAndDecryptLargeString()
        {
            string encrypted = AES256.Encrypt(
                "test string that is longer than 16 characters",
                "password"
                );
            string decrypted = AES256.Decrypt(encrypted, "password");

            Assert.AreEqual(
                decrypted,
                "test string that is longer than 16 characters"
                );
        }
Exemplo n.º 16
0
        public void EncryptAndDecryptExactly16chars()
        {
            string encrypted = AES256.Encrypt(
                "0123456789abcdef",
                "password"
                );
            string decrypted = AES256.Decrypt(encrypted, "password");

            Assert.AreEqual(
                decrypted,
                "0123456789abcdef"
                );
        }
Exemplo n.º 17
0
        private static void CallLogService(string appName, string msg, Guid ClientTransactionId)
        {
            //{"clientId":"84239dab-07f1-4ad9-a0d9-35ab0432a8c5","Stamp":1576564602,"Msg":"2019 year Dec","LocalTimeZone":"WT",
            //"ClientTransactionId":"5f96e6dd-54bf-4625-9c42-962060c9a2a5", "LogServiceInstanceId":"6b12528e-3c8d-4782-9732-40d7e49f39be" }

            Int32    unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            TimeZone localZone     = TimeZone.CurrentTimeZone;
            // Guid ClientTransactionId = Guid.NewGuid();
            StringBuilder strB = new StringBuilder();

            strB.AppendFormat("\"clientId\":\"84239dab-07f1-4ad9-a0d9-35ab0432a8c5\",\"Stamp\":{0},\"AppName\":\"{1}\"," +
                              "\"Msg\":\"{2}\"," +
                              "\"LocalTimeZone\":\"{3}\"," +
                              "\"ClientTransactionId\":\"{4}\"," +
                              " \"LogServiceInstanceId\":\"{5}\"", unixTimestamp.ToString(), appName, msg, localZone.StandardName, ClientTransactionId.ToString(), Guid.NewGuid().ToString());
            strB.Insert(0, "{", 1);
            strB.Insert(strB.Length, "}", 1);

            AES256 aes           = new AES256();
            string cryptedBody   = aes.Encrypt(strB.ToString(), PASSWORD);
            string cryptedAPIKey = aes.Encrypt(API_KEY, PASSWORD);

            //soap sample starts here

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BASE_URL + DIR_GET_URL + ConvertStringToHex(cryptedAPIKey, Encoding.ASCII));

            request.Method        = "POST";
            request.ContentType   = "application/json";
            request.ContentLength = cryptedBody.Length;
            using (Stream webStream = request.GetRequestStream())
                using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
                {
                    requestWriter.Write(cryptedBody);
                }

            try
            {
                WebResponse webResponse = request.GetResponse();
                using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
                    using (StreamReader responseReader = new StreamReader(webStream))
                    {
                        string response = responseReader.ReadToEnd();
                        Console.Out.WriteLine(response);
                    }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("-----------------");
                Console.Out.WriteLine(e.Message);
            }
        }
Exemplo n.º 18
0
        // To retrieve (last used) IDC
        public static string getLastUsedIDC()
        {
            byte[] ccd     = CryptoUtils.getCCD();
            byte[] idcData = AES256.decryptDataAndGetFromMem(StorageUtils.kLastUsedIDC, ccd);

            if (idcData != null)
            {
                string result = CryptoUtils.toHexStringFromBytes(idcData);
                result = result.Replace(" ", "").Replace("<", "").Replace(">", "");
                return(result);
            }

            return(null);
        }
Exemplo n.º 19
0
        public void EncryptAndDecryptCheckPadding()
        {
            string encrypted = AES256.Encrypt("test", "password");

            byte[] decrypted = AES256.DecryptToByteArray(
                encrypted,
                Encoding.UTF8.GetBytes("password")
                );
            Assert.That(
                decrypted,
                Is.EqualTo(
                    new byte[] { 116, 101, 115, 116 }
                    )
                );
        }
Exemplo n.º 20
0
 private void EncryptFileOnUpload(String pathFile, String encryptionKey, Boolean isImage)
 {
     AES256.EncryptFile(pathFile, encryptionKey);
     if (isImage)
     {
         foreach (ImageFormat format in ImagesFormats)
         {
             String pathFileWithExtension = DocumentUtils.GetNewPathFileName(pathFile, format.Name);
             if (File.Exists(pathFileWithExtension))
             {
                 AES256.EncryptFile(pathFileWithExtension, encryptionKey);
             }
         }
     }
 }
Exemplo n.º 21
0
 public SaveSessionResults SaveSession(LoginRequestBody login, IPAddress clientIp)
 {
     if (login != null && login.SessionId != null && login.SessionId.Length > 0)
     {
         var session = GetSession(login.SessionId, clientIp);
         if (session != null && session.Data != null)
         {
             byte[] key  = null;
             byte[] mPwd = null;
             try
             {
                 key = generateSessionKey(session);
                 try
                 {
                     mPwd = AES256.DecryptToByteArray(login.Password, key);
                 }
                 catch (CryptographicException)
                 {
                     return(SaveSessionResults.InvalidPassword);
                 }
                 if (session.Data.IsOriginalPassword(mPwd))
                 {
                     saveSessionData(session, mPwd, key);
                     return(SaveSessionResults.Success);
                 }
                 else
                 {
                     return(SaveSessionResults.OriginalPasswordDiffers);
                 }
             }
             finally
             {
                 // The byte array might already be cleared but it
                 // doesn't hurt to do it more than one time.
                 if (mPwd != null)
                 {
                     Array.Clear(mPwd, 0, mPwd.Length);
                 }
                 if (key != null)
                 {
                     Array.Clear(key, 0, key.Length);
                 }
             }
         }
     }
     // Could also mean invalid IP address in this case.
     return(SaveSessionResults.InvalidSession);
 }
Exemplo n.º 22
0
        /// <summary>
        /// Checks if user credentials are valid
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool AuthenticateUser(ref User user)
        {
            DataTable dtUser = new DataTable();

            dtUser = _db.GetData($"SELECT Usuario, Contrasena FROM Usuario WHERE Usuario = '{user.Username}' AND Estatus = 1", autoConnect: true);

            if (dtUser.Rows.Count > 0)
            {
                if (AES256.Decrypt(dtUser.Rows[0]["Contrasena"].ToString(), _config.Database.EncryptionKey) == user.Password)
                {
                    GetUserDataByUsername(ref user);
                }
            }

            return((user.Id == default) ? false : true);
        }
Exemplo n.º 23
0
    public void AESEncrypt()
    {
        var sample = "something";

        string key = "z,mv--342krnsdrfJDSf33dq2423nsda";
        string iv  = "12325346457462343654867843523421";

        var aes = new AES256(key, iv);

        var encryptedStr = aes.Encrypt(sample);
        var decryptedStr = aes.Decrypt(encryptedStr);

        var len1 = sample.Length;
        var len2 = decryptedStr.Length;

        True(sample.Length == decryptedStr.Length, "not match, dec:" + decryptedStr + " len1:" + len1 + " len2:" + len2);
    }
        public ValidateTokenOut ValidateToken(ValidateTokenIn input)
        {
            var    output       = new ValidateTokenOut();
            AES256 aes256       = new AES256();
            string tokenDecrypt = aes256.Decrypt(input.token);
            // Se obtiene la información del token
            ClaimsPrincipal simplePrinciple = GetPrincipal(tokenDecrypt);

            if (simplePrinciple != null)
            {
                // Se obtienen las propiedades
                var identity = simplePrinciple.Identity as ClaimsIdentity;
                if (identity != null)
                {
                    // Si no esta autenticado se denega el acceso
                    if (identity.IsAuthenticated)
                    {
                        // Se obtienen las variables de las propiedades que se le asignaron al Token cuando se genero
                        var sessionId = identity.FindFirst("sessionId");
                        var usrID     = identity.FindFirst("usrID");
                        var ip        = System.Web.HttpContext.Current.Request.UserHostAddress;
                        if (sessionId?.Value != null &&
                            usrID?.Value != null &&
                            ip != null)
                        {
                            var autentication      = new SystemManagement.Business.Authentication.Authentication();
                            var validateSessionOut = autentication.ValidateSession(new MethodParameters.Authentication.ValidateSessionIn()
                            {
                                sessionId = sessionId.Value,
                                userId    = Convert.ToDecimal(usrID.Value)
                            });
                            if (validateSessionOut.result == Entities.Common.Result.Success &&
                                validateSessionOut.session.usrID == Convert.ToDecimal(usrID.Value) &&
                                validateSessionOut.session.sesID == sessionId.Value &&
                                validateSessionOut.session.ses_status == "V")
                            {
                                output.tokenInformation           = new Entities.Authentication.TokenInformation();
                                output.tokenInformation.sessionId = sessionId.Value;
                                output.tokenInformation.usrID     = usrID.Value;
                            }
                        }
                    }
                }
            }
            return(output);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Writes an AES 256 encrypted value to its configuration file.
        /// </summary>
        /// <param name="value">The value to write to the file.</param>
        /// <param name="log">The event log to log execptions to. May be null for no logging.</param>
        /// <returns>True if the write was successful, false otherwise.</returns>
        protected bool SecureWrite(string value, EventLog.EventLog log)
        {
            // Create a consolidated encrypted string value for storage in the file.
            string consolidatedString = AES256.CreateConsolidatedString(value);

            // Check that the consolidated string value was created successfully.
            if (!string.IsNullOrWhiteSpace(consolidatedString))
            {
                // The consolidated string value was created successfully.

                // Write the consolidated string value containing the encrypted value to a file.
                return(Write(consolidatedString, log));
            }
            else
            {
                // The consolidated string value was not created.
                return(false);
            }
        }
Exemplo n.º 26
0
        public IHttpActionResult Login(usuario usuario)
        {
            string  result = AES256.encryptPassword(usuario.password);
            usuario user   = db.usuarios.FirstOrDefault(u => u.correo == usuario.correo && u.password == result);

            if (user == null)
            {
                return(NotFound());
            }
            user.rol = db.rols.Find(user.id_rol);
            db.Entry(user.rol).Collection(p => p.permisos).Load();
            sesion sesion = new sesion();

            sesion.fecha      = DateTime.Now;
            sesion.id_usuario = user.id_usuario;
            db.sesions.Add(sesion);
            Bitacora.getInstance().addBitacora(BitacoraActions.SIGN_IN, user.id_usuario);
            db.SaveChanges();
            return(Ok(user));
        }
Exemplo n.º 27
0
        public ActionResult LoginIn(LoginINM login)
        {
            if (login != null)
            {
                AES256 aES256Enc = new AES256();
                login.Pwd = aES256Enc.EncryptString(login.Pwd.Trim(), ConfigurationManager.AppSettings["AESkey1"].ToString());

                using (SecurityDBEntities gMSEntities = new SecurityDBEntities())
                {
                    List <logindetails_get_Result> dbresult = gMSEntities.logindetails_get(login.UserName, login.Pwd).ToList();
                    if (dbresult.Count > 0)
                    {
                        foreach (logindetails_get_Result result in dbresult)
                        {
                            SessionSet session = new SessionSet();
                            session.SeeionSetLogin(result.UserId, result.UserName, result.Pwd, result.ProfileId, result.ProfileCode, result.ProfileName, result.CustName, result.ClientName, result.BranchName, result.ClustrNme, result.SiteName, result.ClientId, result.CustId, result.BranchId, result.ClustrId, result.SiteId);
                        }
                        //List<Menudetails_get_Result> menuresult = new List<Menudetails_get_Result>();
                        //var menudb = gMSEntities.Menudetails_get((int)Session["ProfileId"], Session["GMS"].ToString(), Session["EPS"].ToString(), Session["OMS"].ToString());
                        //foreach (Menudetails_get_Result mrs in menudb)
                        //{
                        //    menuresult.Add(mrs);
                        //}
                        //Session["MenuMaster"] = menuresult;
                        //Session["SessionId"] = Session.SessionID;

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        TempData["StatusMsg"] = "Invalid User and Password.";
                        return(RedirectToAction("Login", "Login"));
                    }
                }
            }
            else
            {
                TempData["StatusMsg"] = "UserName and Password cannot be Empty";
            }
            return(RedirectToAction("Login", "Login"));
        }
Exemplo n.º 28
0
    public void AESEncryptBytes()
    {
        var sampleBytes = new byte[1024];
        var rnd         = new System.Random();

        rnd.NextBytes(sampleBytes);

        string key = "z,mv--342krnsdrfJDSf33dq2423nsda";
        string iv  = "12325346457462343654867843523421";

        var aes = new AES256(key, iv);

        var encryptedBytes = aes.Encrypt(sampleBytes);
        var decryptedBytes = aes.Decrypt(encryptedBytes);

        var bytesLen1 = sampleBytes.Length;
        var bytesLen2 = decryptedBytes.Length;

        True(sampleBytes.Length == decryptedBytes.Length, "not match," + " bytesLen1:" + bytesLen1 + " bytesLen2:" + bytesLen2);
        True(sampleBytes.SequenceEqual(decryptedBytes), "not match");
    }
Exemplo n.º 29
0
        public async Task <List <UserDto> > GetAll()
        {
            var users = await _service.GetAllAsync();

            var userDtos = new List <UserDto>();

            foreach (var item in users)
            {
                userDtos.Add(new UserDto
                {
                    Email     = AES256.DecodeAndDecrypt(item.Email),
                    Password  = AES256.DecodeAndDecrypt(item.Password),
                    CompanyId = item.CompanyId,
                    FirstName = item.FirstName,
                    LastName  = item.LastName,
                    Status    = item.Status,
                });
            }

            return(userDtos);
        }
Exemplo n.º 30
0
        public void ManagerProcess(InfoTypes types, string account, string password)
        {
            string encryptPassword = new AES256().AESEncrypt256(password);

            switch (types)
            {
            case InfoTypes.Gamezone:
                main.gamezoneAccount   = account;
                main.gamezonePassword  = encryptPassword;
                panel_Gamezone.Visible = false;
                OutSystemMessage($"{main.gamezoneAccount}, {main.gamezonePassword}");
                main.toolStripMenuItem_ProcessStart.Enabled = true;
                main.needView = checkBox_needView.Checked;
                TodayPanel_Initialize();
                break;

            case InfoTypes.Today:
                main.todayAccount   = account;
                main.todayPassword  = encryptPassword;
                panel_Today.Visible = false;
                OutSystemMessage($"{main.todayAccount}, {main.todayPassword}");
                main.needView1 = checkBox_needView1.Checked;
                this.Close();
                //NaverPanel_Initialize();
                break;

            case InfoTypes.Naver:
                main.naverAccount  = account;
                main.naverPassword = encryptPassword;
                OutSystemMessage($"{main.naverAccount}, {password} => {main.naverPassword}");
                main.needView2 = checkBox_needView2.Checked;
                main.toolStripMenuItem_ProcessStart.Enabled = true;
                this.Close();
                break;

            default:
                MessageBox.Show("Exec Error");
                break;
            }
        }