public static bool IsValidInvoiceHash(string inString) { if (inString == null) { return(false); } inString = inString.Replace(" ", "+"); string result = SimpleAES.Decrypt(SimpleAES.KeyType.Invoices, inString); if (result == null || !System.Text.RegularExpressions.Regex.IsMatch(result, @"^Mediclinic_\d{4}__\d+$")) { return(false); } string[] resultSplit = result.Split(new string[] { "__" }, StringSplitOptions.None); string DB = resultSplit[0]; string invNbr = resultSplit[1]; if (!Utilities.IsValidDB(DB.Substring(DB.Length - 4))) { return(false); } if (InvoiceDB.GetByID(Convert.ToInt32(invNbr), DB) == null) { return(false); } return(true); }
private void LoadCaptionsFromFile() { if (File.Exists(_captionFileName)) { byte[] data = File.ReadAllBytes(_captionFileName); var json = _simpleAES.Decrypt(data); var serializer = new JsonSerializer(); var _listObjects = JsonConvert.DeserializeObject<List<string>>(json.ToString()); if (_listObjects != null) { foreach (string caption in _listObjects) { lstCaptions.Items.Add(caption); _captions.Add(caption); } } } else { File.CreateText(_captionFileName); } }
public void LoadSetting(UserSetting userSetting) { server = userSetting.server_address; database = userSetting.db_name; uid = userSetting.user_id; chk_interval = userSetting.check_interval; password = aes_crypter.Decrypt(userSetting.user_pw); }
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"); }
void DoMyWindow(int windowID) { SimpleAES eaes = new SimpleAES(); if (GUI.Button(new Rect(80, 30, 20, 20), "Click")) { NGUITools.SetActive(GameObject.Find("UIRefer").GetComponent <UIMainReferences>().PanelMultiPWD, false); NGUITools.SetActive(GameObject.Find("UIRefer").GetComponent <UIMainReferences>().panelMultiROOM, true); GameObject.Find("PanelMultiROOM").GetComponent <PanelMultiJoin>().refresh(); } GUI.Label(new Rect(20, 60, 150, 150), "<color=white>PWD: " + eaes.Decrypt(Password) + "</color>"); GUI.Label(new Rect(30, 30, 120, 120), "Leave:"); }
public object NullSafeGet(IDataReader rs, string[] names, object owner) { object r = rs[names[0]]; if (r == DBNull.Value) return null; // decrypt result and assert the same string returned // Get key for the encryption/decryption 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); return simpleAES.Decrypt((byte[])r); }
/// <summary> /// Switch the connection in "Application Role" mode with the provided Application Role name /// </summary> /// <see cref="http://technet.microsoft.com/en-us/library/ms188908.aspx"/> public static void SwitchToApplicationRole(this SqlConnection connectionToSwitch, string ApplicationRoleName) { // Get the encrypted version of the key from the DB string encryptedKey = getKeyFromDB(connectionToSwitch); // Get the key decoder SimpleAES decoder = new SimpleAES(); // Execute the required stored procedure if (!performSwitch(connectionToSwitch, decoder.Decrypt(encryptedKey), ApplicationRoleName)) { throw new SynapseCoreException(string.Format("Unable to switch to Application Role '{0}'.", ApplicationRoleName)); } }
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)); }
private void OnClick() { string text = CacheGameObject.Find("InputEnterPWD").GetComponent <UIInput>().label.text; SimpleAES simpleAES = new SimpleAES(); if (text == simpleAES.Decrypt(PanelMultiJoinPWD.Password)) { PhotonNetwork.JoinRoom(PanelMultiJoinPWD.roomName); } else { NGUITools.SetActive(UIMainReferences.Main.PanelMultiPWD, false); NGUITools.SetActive(UIMainReferences.Main.panelMultiROOM, true); CacheGameObject.Find("PanelMultiROOM").GetComponent <PanelMultiJoin>().refresh(); } }
private void OnClick() { string text = CyanMod.CachingsGM.Find("InputEnterPWD").GetComponent <UIInput>().label.text; SimpleAES eaes = new SimpleAES(); if (text != eaes.Decrypt(PanelMultiJoinPWD.Password)) { PhotonNetwork.JoinRoom(PanelMultiJoinPWD.roomName); } else { NGUITools.SetActive(UIMainReferences.instance.PanelMultiPWD, false); NGUITools.SetActive(UIMainReferences.instance.panelMultiROOM, true); CyanMod.CachingsGM.Find("PanelMultiROOM").GetComponent <PanelMultiJoin>().refresh(); } }
private void OnClick() { var text = GGM.Caching.GameObjectCache.Find("InputEnterPWD").GetComponent <UIInput>().label.text; var eaes = new SimpleAES(); if (text == eaes.Decrypt(PanelMultiJoinPWD.Password)) { PhotonNetwork.JoinRoom(PanelMultiJoinPWD.roomName); } else { NGUITools.SetActive(GGM.Caching.GameObjectCache.Find("UIRefer").GetComponent <UIMainReferences>().PanelMultiPWD, false); NGUITools.SetActive(GGM.Caching.GameObjectCache.Find("UIRefer").GetComponent <UIMainReferences>().panelMultiROOM, true); GGM.Caching.GameObjectCache.Find("PanelMultiROOM").GetComponent <PanelMultiJoin>().refresh(); } }
private void OnClick() { string text = GameObject.Find("InputEnterPWD").GetComponent <UIInput>().label.text; SimpleAES simpleAES = new SimpleAES(); if (text == simpleAES.Decrypt(PanelMultiJoinPWD.Password)) { PhotonNetwork.JoinRoom(PanelMultiJoinPWD.RoomName); } else { UIMainReferences ui = GameObject.Find("UIRefer").GetComponent <UIMainReferences>(); NGUITools.SetActive(ui.PanelMultiPWD, state: false); NGUITools.SetActive(ui.panelMultiROOM, state: true); GameObject.Find("PanelMultiROOM").GetComponent <PanelMultiJoin>().Refresh(); } }
/// <summary> /// Override read page decrypting data from disk /// </summary> public override byte[] ReadPage(uint pageID) { var buffer = base.ReadPage(pageID); // when read header, checks passoword if (pageID == 0) { // I know, header page will be double read (it's the price for isolated concerns) var header = (HeaderPage)BasePage.ReadPage(buffer); if (header.DbParams.Password.BinaryCompareTo(_password) != 0) { throw LiteException.DatabaseWrongPassword(); } return(buffer); } return(_crypto.Decrypt(buffer)); }
public static Tuple <string, int> DecodeInvoiceHash(string inString) { if (inString == null) { return(null); } inString = inString.Replace(" ", "+"); string result = SimpleAES.Decrypt(SimpleAES.KeyType.Invoices, inString); if (result == null || !System.Text.RegularExpressions.Regex.IsMatch(result, @"^Mediclinic_\d{4}__\d+$")) { return(null); } string[] resultSplit = result.Split(new string[] { "__" }, StringSplitOptions.None); string DB = resultSplit[0]; string invNbr = resultSplit[1]; return(new Tuple <string, int>(DB, Convert.ToInt32(invNbr))); }
/// <summary> /// Read and decrypts a string from the NetworkStream. /// </summary> /// <returns>The dycrypted string.</returns> public SecureMessage Read() { string encrypted = streamReader.ReadLine(); string unparsed = ""; try { unparsed = sessionAES.Decrypt(encrypted); } catch (Exception) { return(new SecureMessage("Decript Exception Thrown.")); } var sm = new SecureMessage(unparsed, othersMessageCount, isServer); if (sm.isSecure == true) { if (verbose && sm.Count - othersMessageCount > 1) { Console.WriteLine("Missing " + (sm.Count - othersMessageCount).ToString() + "Messages"); } othersMessageCount = sm.Count; } return(sm); }
public int ReadUserOptions(IStream pOptionsStream, string pszKey) { try { using (StreamEater wrapper = new StreamEater(pOptionsStream)) { string value; using (var bReader = new System.IO.BinaryReader(wrapper)) { value = bReader.ReadString(); using (var aes = new SimpleAES()) { value = aes.Decrypt(value); } } switch (pszKey) { case _strSolutionPersistanceKey + _strUsername: _settings.Username = value; break; case _strSolutionPersistanceKey + _strPassword: _settings.Password = value; break; default: break; } } return(VSConstants.S_OK); } finally { Marshal.ReleaseComObject(pOptionsStream); } }
private void Update() { if (!isStarted) { return; } int recHostId; int connectionId; int channelId; byte[] recBuffer = new byte[1024]; int bufferSize = 1024; int dataSize; byte error; NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error); switch (recData) { case NetworkEventType.Nothing: break; case NetworkEventType.ConnectEvent: //ToLog("Player" + connectionId + "Se ha conectado"); OnConnection(connectionId); break; case NetworkEventType.DataEvent: string msg = Encoding.Unicode.GetString(recBuffer, 0, dataSize); ToLog("QUE RECIBO DE CADA CONEXION" + connectionId + ": " + msg); msg = simpleAES.Decrypt(recBuffer); string[] splitData = msg.Split('|'); switch (splitData[0]) { case "NAMEIS": SymfonyConnect(connectionId, splitData[1], splitData[2]); break; case "EMPEZAR": //ToLog("EMPEZAR" + msg); Send("EMPEZAR|", reliableChannel, clients); break; case "INV": inventario(int.Parse(splitData[1]), connectionId, splitData[2]); break; case "AJU": ajustes(int.Parse(splitData[1]), connectionId, splitData[2]); break; case "AJUPASS": ajuPassService(int.Parse(splitData[1]), splitData[3], splitData[2]); break; case "POS1": Send("POS1|" + splitData[1] + "|" + splitData[2], reliableChannel, clients); cantidadJugadores++; if (cantidadJugadores == 2) { Send("SPAWN|a", reliableChannel, clients); } break; case "POS2": Send("POS2|" + splitData[1] + "|" + splitData[2], reliableChannel, clients); break; case "DER": Send("DER|" + splitData[1], reliableChannel, clients); break; case "IZQ": Send("IZQ|" + splitData[1], reliableChannel, clients); break; case "PAR": Send("PAR|" + splitData[1], reliableChannel, clients); break; case "SAL": Send("SAL|" + splitData[1], reliableChannel, clients); break; case "ARR": Send("ARR|" + splitData[1], reliableChannel, clients); break; case "ABA": Send("ABA|" + splitData[1], reliableChannel, clients); break; case "DIS": Send("DIS|" + splitData[1], reliableChannel, clients); break; case "GOL": Send("GOL|" + splitData[1], reliableChannel, clients); break; case "GORSEL": Send("GORSEL|" + splitData[1] + "|" + splitData[2], reliableChannel, clients); break; default: ToLog("Mensaje Invalido" + msg); break; } simpleAES = new SimpleAES(); break; case NetworkEventType.DisconnectEvent: //ToLog("Player" + connectionId + "Se ha desconectado"); break; } }
public static string IRCVars(Type type) { SimpleAES aesAll = new SimpleAES(); return aesAll.Decrypt(Encoding.Default.GetBytes(Strings.Split(Config.IRCSettings[(int)type], Config.FSplit4, -1, CompareMethod.Text)[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); }
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 />"; }