Encrypt() public method

public Encrypt ( string TextValue ) : byte[]
TextValue string
return byte[]
Ejemplo n.º 1
0
 private void SaveCaptions()
 {
     var json = JsonConvert.SerializeObject(_captions);
     byte[] encryptedBytes = _simpleAES.Encrypt(json);
     File.WriteAllBytes(_captionFileName, encryptedBytes);
    
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Encrypts and writes a string to the NetworkStream.
        /// </summary>
        /// <param name="str">The string to encrypt and send</param>
        public void Write(string str)
        {
            var m = SecureMessage.FormMessage(++messageCount, str, isServer);

            streamWriter.WriteLine(sessionAES.Encrypt(m));
            streamWriter.Flush();
        }
Ejemplo n.º 3
0
 public void SaveSetting(UserSetting userSetting)
 {
     userSetting.server_address = server;
     userSetting.db_name        = database;
     userSetting.user_id        = uid;
     userSetting.user_pw        = aes_crypter.Encrypt(password);
     userSetting.check_interval = chk_interval;
 }
Ejemplo n.º 4
0
        public Response <AuthorizationTokenResponse> GetRequesterAuthorizer(string CardNum)
        {
            if (CardNum != null)
            {
                var simpleAES = new SimpleAES();

                return(new Response <AuthorizationTokenResponse>
                {
                    Success = true,
                    Data = new AuthorizationTokenResponse
                    {
                        requester = getBase64(simpleAES.Encrypt(CardNum)),
                        authorizer = getBase64(simpleAES.Encrypt(DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss:fff")))
                    }
                });
            }
            return(null);
        }
Ejemplo n.º 5
0
    private void Send(string message, int channelId)
    {
        string msgBar = message + "|º";

        //string sMsg = simpleAES.Encrypt(message);
        byte[] msg = simpleAES.Encrypt(msgBar);
        simpleAES = new SimpleAES();
        Debug.Log("El byte Array que envia el cliente es de: " + msg.Length);
        NetworkTransport.Send(hostId, connectionId, channelId, msg, message.Length * sizeof(char), out error);
    }
        public static void Run(BigInteger secretPhrase)
        {
            //Have to use the same IV
            Random r = new Random();

            byte[] iv = new byte[16];
            r.NextBytes(iv);

            byte[] a = SimpleAES.GenerateEncryptionVector();

            SimpleAES aes1 = new SimpleAES(secretPhrase.GetBytes(), iv);
            SimpleAES aes2 = new SimpleAES(secretPhrase.GetBytes(), iv);

            int numberOfRuns = 10000;

            Stopwatch timer = new Stopwatch();

            timer.Start();

            for (int i = 0; i < numberOfRuns; i++)
            {
                r.NextBytes(iv);
                aes1.SetIV(iv);
                //aes2.SetIV(iv);
                byte[] encrypted = aes1.Encrypt(randomPacket, randomPacket.Length);
                byte[] decrypted = aes2.Decrypt(encrypted, encrypted.Length);
#if DEBUG
                for (int j = 0; j < randomPacket.Length; j++)
                {
                    Debug.Assert(decrypted[j] == randomPacket[j]);
                }
#endif
            }

            for (int i = 0; i < numberOfRuns; i++)
            {
                r.NextBytes(iv);
                aes1.SetIV(iv);
                //aes2.SetIV(iv);
                byte[] encrypted = aes2.Encrypt(randomPacket, randomPacket.Length);
                byte[] decrypted = aes1.Decrypt(encrypted, encrypted.Length);

#if DEBUG
                for (int j = 0; j < randomPacket.Length; j++)
                {
                    Debug.Assert(decrypted[j] == randomPacket[j]);
                }
#endif
            }


            timer.Stop();
            Console.WriteLine("AESProfiler took " + timer.ElapsedMilliseconds + " millseconds.");
            Console.WriteLine("or " + (double)timer.ElapsedMilliseconds / (double)(numberOfRuns + numberOfRuns) + " millseconds per encrypt + decrypt");
        }
 /// <summary>
 ///     Override write page to write encrypted data
 /// </summary>
 public override void WritePage(uint pageID, byte[] buffer)
 {
     if (pageID == 0)
     {
         base.WritePage(pageID, buffer);
     }
     else
     {
         base.WritePage(pageID, _crypto.Encrypt(buffer));
     }
 }
Ejemplo n.º 8
0
        protected void btnEncryptPasswords_onClick(object sender, EventArgs e)
        {
            MembershipBs bs = new MembershipBs();

            var upl = bs.GetAllUserProfiles();

            foreach (var up in upl)
            {
                //up.password = MembershipBs.GeneratePassword();
                up.password = _aes.Encrypt(up.password);
                bs.ProcessNurseProfile();
            }
        }
Ejemplo n.º 9
0
        public string encrypt_string(string cleartextValue)
        {
            if (string.IsNullOrWhiteSpace(cleartextValue))
            {
                return(null);
            }

            var decryptedByteArray = Encoding.UTF8.GetBytes(cleartextValue);
            var encryptedByteArray = simpleAes.Encrypt(decryptedByteArray);
            var encryptedString    = Convert.ToBase64String(encryptedByteArray);

            return(encryptedString);
        }
Ejemplo n.º 10
0
    private void OnClick()
    {
        string text       = CacheGameObject.Find("InputServerName").GetComponent <UIInput>().label.text;
        int    maxPlayers = int.Parse(CacheGameObject.Find("InputMaxPlayer").GetComponent <UIInput>().label.text);
        int    num        = int.Parse(CacheGameObject.Find("InputMaxTime").GetComponent <UIInput>().label.text);
        string selection  = CacheGameObject.Find("PopupListMap").GetComponent <UIPopupList>().selection;
        string text2      = (!CacheGameObject.Find("CheckboxHard").GetComponent <UICheckbox>().isChecked) ? ((!CacheGameObject.Find("CheckboxAbnormal").GetComponent <UICheckbox>().isChecked) ? "normal" : "abnormal") : "hard";
        string text3      = string.Empty;

        if (IN_GAME_MAIN_CAMERA.DayLight == DayLight.Day)
        {
            text3 = "day";
        }
        if (IN_GAME_MAIN_CAMERA.DayLight == DayLight.Dawn)
        {
            text3 = "dawn";
        }
        if (IN_GAME_MAIN_CAMERA.DayLight == DayLight.Night)
        {
            text3 = "night";
        }
        string text4 = CacheGameObject.Find("InputStartServerPWD").GetComponent <UIInput>().label.text;

        if (text4.Length > 0)
        {
            SimpleAES simpleAES = new SimpleAES();
            text4 = simpleAES.Encrypt(text4);
        }
        text = string.Concat(new object[]
        {
            text,
            "`",
            selection,
            "`",
            text2,
            "`",
            num,
            "`",
            text3,
            "`",
            text4,
            "`",
            UnityEngine.Random.Range(0, 50000)
        });
        PhotonNetwork.CreateRoom(text, new RoomOptions()
        {
            isOpen = true, isVisible = true, maxPlayers = maxPlayers
        }, null);
    }
Ejemplo n.º 11
0
    protected void RunEncyrptionTest2()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendLine("<table>");

        string pt1 = "Mediclinic_0001" + "__" + 54950.ToString().PadLeft(6, '0');

        sb.AppendLine("<t><td>" + pt1 + "</td><td>" + SimpleAES.Encrypt(SimpleAES.KeyType.EmailUnsubscribe, pt1) + "</td><td>" + SimpleAES.Decrypt(SimpleAES.KeyType.EmailUnsubscribe, SimpleAES.Encrypt(SimpleAES.KeyType.EmailUnsubscribe, pt1)) + "</td><td><a href=\"" + Patient.GetUnsubscribeLink(54950, Session["DB"].ToString()) + "\">Unsubscribe</a></td></tr>");

        string pt2 = "Mediclinic_0001" + "__" + 68335.ToString().PadLeft(6, '0');

        sb.AppendLine("<t><td>" + pt2 + "</td><td>" + SimpleAES.Encrypt(SimpleAES.KeyType.EmailUnsubscribe, pt2) + "</td><td>" + SimpleAES.Decrypt(SimpleAES.KeyType.EmailUnsubscribe, SimpleAES.Encrypt(SimpleAES.KeyType.EmailUnsubscribe, pt2)) + "</td><td><a href=\"" + Patient.GetUnsubscribeLink(68335, Session["DB"].ToString()) + "\">Unsubscribe</a></td></tr>");

        sb.AppendLine("</table>");
        lblOutput.Text = sb.ToString() + "<br />";
    }
Ejemplo n.º 12
0
        public void NullSafeSet(IDbCommand cmd, object value, int index)
        {
            object paramVal = DBNull.Value;
            if (value != null)
            {
                // get the keys from the files
                var privateKey = File.ReadAllBytes(@"C:\Users\David Peel\Documents\key.txt");
                var sharedIV = File.ReadAllBytes(@"C:\Users\David Peel\Documents\iv.txt");

                // encrpt a string and store result
                var simpleAES = new SimpleAES(privateKey, sharedIV);
                paramVal = simpleAES.Encrypt((string)value);
            }
            IDataParameter parameter = (IDataParameter)cmd.Parameters[index];
            parameter.Value = paramVal;
        }
Ejemplo n.º 13
0
        public void EncryptDecrypt_WhaenCalled_ReturnsSameValue()
        {
            // Get key for the encryption/decryption
            var privateKey = SimpleAES.GenerateEncryptionKey();
            // get an IV for the operation
            var privateIV = SimpleAES.GenerateEncryptionVector();

            // encrpt a string and store result
            const string SecretString = "jdhsbdsb87dubdlvbd8v7dvd7 my bank details here";
            var simpleAES = new SimpleAES(privateKey, privateIV);
            var encryptedSecret = simpleAES.Encrypt(SecretString);

            // decrypt result and assert the same string returned 
            var decryptedSecret = simpleAES.Decrypt(encryptedSecret);
            Assert.That(decryptedSecret, Is.EqualTo(SecretString));
        }
Ejemplo n.º 14
0
        private string GeneratePassword(string username)
        {
            string hexPwd;

            System.Text.StringBuilder hexString = new System.Text.StringBuilder(64);

            byte[] bytes = new byte[username.Length * sizeof(char)];
            System.Buffer.BlockCopy(username.ToCharArray(), 0, bytes, 0, bytes.Length);

            SimpleAES aes = new SimpleAES();

            byte[] b = aes.Encrypt(bytes);

            for (int i = 0; i < b.Length; i++)
            {
                hexString.Append(String.Format("{0:X2}", b[i]));
            }

            // remove similar characters (I and 1, 0 and O)
            hexPwd = Regex.Replace(hexString.ToString().ToUpper(), "(I|1|0|O)", "");

            return(hexPwd.Substring(1, 8));
        }
Ejemplo n.º 15
0
        public int WriteUserOptions(IStream pOptionsStream, string pszKey)
        {
            try
            {
                string value;
                switch (pszKey)
                {
                case _strSolutionPersistanceKey + _strUsername:
                    value = _settings.Username;
                    break;

                case _strSolutionPersistanceKey + _strPassword:
                    value = _settings.Password;
                    break;

                default:
                    return(VSConstants.S_OK);
                }

                using (var aes = new SimpleAES())
                {
                    value = aes.Encrypt(value);
                    using (StreamEater wrapper = new StreamEater(pOptionsStream))
                    {
                        using (var bw = new System.IO.BinaryWriter(wrapper))
                        {
                            bw.Write(value);
                        }
                    }
                }
                return(VSConstants.S_OK);
            }
            finally
            {
                Marshal.ReleaseComObject(pOptionsStream);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Client:
        /// 1) send: "client"||R1
        /// 2) recieve R2 || HE("server" || R1, K_pass)
        ///     2.1 check R1
        ///     2.2 check ID_server for "server" and size
        /// 3) send HE("client" || R2 || RSA_public, k_pass)
        /// 4) recieve HE("server" || E(Key_session || IV_session, RSA_public), k_pass)
        ///
        /// HE(x||y, k) --> E(H(x||y)||x||y, k)
        ///
        /// </summary>
        /// <returns>true if key exchange is succssesful</returns>
        public bool exchangeKeys()
        {
            sessionId_ = isServer ? SERVER : CLIENT;
            if (isServer)
            {
                string messageRecieved  = streamReader.ReadLine(); //1
                var    others_sessionID = messageRecieved.Substring(0, SESSION_ID_LENGTH);
                string random1          = messageRecieved.Substring(SESSION_ID_LENGTH);
                if (random1.Length != RANDOM_SIZE_BASE64)
                {
                    return(false);
                }
                if (others_sessionID != CLIENT)
                {
                    return(false);
                }

                string random2          = generateRandomString(RANDOM_SIZE_BYTES);
                string messageEncrypted = passAES.Encrypt(HashedMessage.FormMessage(sessionId_ + random1));
                streamWriter.WriteLine(random2 + messageEncrypted); //2
                streamWriter.Flush();

                var hashedMessage = new HashedMessage(passAES.Decrypt(streamReader.ReadLine())); //3
                messageRecieved = hashedMessage.Message;
                if (!hashedMessage.hashMatched)
                {
                    return(false);
                }
                if (messageRecieved.Substring(0, SESSION_ID_LENGTH) != others_sessionID)
                {
                    return(false);
                }
                string receivedRandom2 = messageRecieved.Substring(SESSION_ID_LENGTH, RANDOM_SIZE_BASE64);
                if (random2 != receivedRandom2)
                {
                    return(false);
                }
                string rsaPublic             = messageRecieved.Substring(SESSION_ID_LENGTH + RANDOM_SIZE_BASE64);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(rsaPublic);
                if (verbose)
                {
                    Console.WriteLine("RSA Public Key: " + rsaPublic + "\n");
                }

                sessionAES         = new SimpleAES(aesKeySize);
                sessionAES.verbose = verbose;
                string encryptedPart = Convert.ToBase64String(rsa.Encrypt(sessionAES.key, true));
                streamWriter.WriteLine(passAES.Encrypt(HashedMessage.FormMessage(sessionId_ + encryptedPart))); //4
                streamWriter.Flush();

                if (verbose)
                {
                    Console.WriteLine("SessionKey: " + Convert.ToBase64String(sessionAES.key));
                }
            }
            else ///client
            {
                string random1 = generateRandomString(RANDOM_SIZE_BYTES);
                streamWriter.WriteLine(sessionId_ + random1);  // 1
                streamWriter.Flush();

                string messageRecieved  = streamReader.ReadLine(); //2
                string random2          = messageRecieved.Substring(0, RANDOM_SIZE_BASE64);
                string messageEncrypted = messageRecieved.Substring(RANDOM_SIZE_BASE64);

                messageRecieved = passAES.Decrypt(messageEncrypted); // ID_server || R1
                var hashedMessage = new HashedMessage(messageRecieved);
                messageRecieved = hashedMessage.Message;
                if (!hashedMessage.hashMatched)
                {
                    return(false);
                }
                var others_sessionID = messageRecieved.Substring(0, SESSION_ID_LENGTH);
                if (others_sessionID != SERVER) //2.2
                {
                    return(false);
                }
                string recievedRandom1 = messageRecieved.Substring(SESSION_ID_LENGTH);
                if (recievedRandom1 != random1) // 2.1
                {
                    return(false);
                }

                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(rsaKeySize);
                string publicKey             = rsa.ToXmlString(false);
                if (verbose)
                {
                    Console.WriteLine("RSA Public Key: " + publicKey + "\n");
                }
                string message = sessionId_ + random2 + publicKey;
                streamWriter.WriteLine(passAES.Encrypt(HashedMessage.FormMessage(message))); // 3
                streamWriter.Flush();

                hashedMessage   = new HashedMessage(passAES.Decrypt(streamReader.ReadLine())); //4
                messageRecieved = hashedMessage.Message;                                       //4
                if (messageRecieved.Substring(0, SESSION_ID_LENGTH) != others_sessionID)
                {
                    return(false);
                }
                string restOfMessage = messageRecieved.Substring(SESSION_ID_LENGTH);
                byte[] sessionKey    = rsa.Decrypt(Convert.FromBase64String(restOfMessage), true);
                sessionAES         = new SimpleAES(sessionKey);
                sessionAES.verbose = verbose;

                if (verbose)
                {
                    Console.WriteLine("SessionKey: " + Convert.ToBase64String(sessionAES.key));
                }
            }
            return(true);
        }
Ejemplo n.º 17
0
    public static string EncodeUnsubscribeHash(int patientID, string DB)
    {
        string inString = DB + "__" + patientID.ToString().PadLeft(6, '0');

        return(SimpleAES.Encrypt(SimpleAES.KeyType.EmailUnsubscribe, inString));
    }
Ejemplo n.º 18
0
    public static string EncodeInvoiceHash(int invoiceID, string DB)
    {
        string inString = DB + "__" + invoiceID.ToString().PadLeft(6, '0');

        return(SimpleAES.Encrypt(SimpleAES.KeyType.Invoices, inString));
    }