void ProcessIntent(Intent intent) { IParcelable[] rawMsg = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages); NdefMessage msg = (NdefMessage)rawMsg[0]; string datagram = Encoding.UTF8.GetString(msg.GetRecords()[0].GetPayload()); contactName = datagram.Split(',')[0]; Padbook friendBook = pm.GetPadbookForUsername(contactName); friendBook.AppendPads(datagram.Split(',')[1].Split('#')); // keys are seperated with a hash }
/// <summary> /// Retrieves a message from the server, and if it exists decrypts and displays it /// </summary> private string RetrieveMessage() { // endpoint: GET /messages/:to/:from; in this case, we want to find a message to me, from the user we are viewing string url = "http://safe-inlet-16663.herokuapp.com/messages/" + Identity.Username + "/" + contactName; string msg = wc.DownloadString(url); // Debug: //Toast.MakeText(ApplicationContext, url, ToastLength.Long).Show(); // Decrypt message by using pad from padbook // If no pad exists, returns empty string Padbook pb = pm.GetPadbookForUsername(contactName); long pbSize = pb.BytesLeft(); AesManaged aes = new AesManaged(); KeySizes[] ks = aes.LegalKeySizes; string decryptedMsg = ""; if (pbSize >= (aes.LegalKeySizes[0].MaxSize + aes.LegalBlockSizes[0].MaxSize / 8) * 2) { string pad = pb.GetNextPad(); if (pad != null && pad.Length > 0) { decryptedMsg = Encoding.UTF8.GetString(Crypto.XorStrings(msg, pad)); // Decrypt message using pad } } else // use AES { List <byte> key = new List <byte>(); List <byte> IV = new List <byte>(); List <string> pads = new List <string>(); while (key.Count * sizeof(byte) < 128) { pads.Add(pb.GetNextPad()); byte[] f = Encoding.UTF8.GetBytes(pads.Last()); foreach (byte b in f) { key.Add(b); } } while (IV.Count * sizeof(byte) < 128 / 8) { pads.Add(pb.GetNextPad()); byte[] f = Encoding.UTF8.GetBytes(pads.Last()); foreach (byte b in f) { IV.Add(b); } } //resave the pads so AES can be used again pb.AppendPads(pads.ToArray()); aes.Key = key.ToArray(); aes.IV = IV.ToArray(); ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); using (MemoryStream msDecrypt = new MemoryStream(Encoding.UTF8.GetBytes(msg))) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. decryptedMsg = srDecrypt.ReadToEnd(); } } } } return(decryptedMsg); }