public static void WriteFile(ApikeyPrefs account) { string accountJson = JsonUtility.ToJson(account); byte[] encryptedBinary = RijndaelEncryption.Encrypt(Encoding.ASCII.GetBytes(accountJson), EncyptPassword); File.WriteAllBytes(RecordFilePath, encryptedBinary); }
private static void DirectoryCipher(string sourceDirName, string password) { // If the destination directory doesn't exist, create it. string destDirName = Path.Combine(sourceDirName, "Ciphered"); if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } foreach (string folderPath in Directory.GetDirectories(sourceDirName, "*", SearchOption.AllDirectories)) { if (!Directory.Exists(folderPath.Replace(sourceDirName, destDirName)) && folderPath.IndexOf("Ciphered") < 0) { Directory.CreateDirectory(folderPath.Replace(sourceDirName, destDirName)); } } foreach (string filePath in Directory.GetFiles(sourceDirName, "*.*", SearchOption.AllDirectories)) { var fileDirName = Path.GetDirectoryName(filePath).Replace("\\", "/"); var fileName = Path.GetFileName(filePath); string newFilePath = Path.Combine(fileDirName.Replace(sourceDirName, destDirName), fileName); File.WriteAllBytes(newFilePath, RijndaelEncryption.Encrypt(File.ReadAllBytes(filePath), password)); } }
public void ExecuteEncrypt() { string planeText = textInput.text; string passwordText = passwordInput.text; string encrypted = RijndaelEncryption.Encrypt(planeText, passwordText); resultText.text = encrypted; }
private static string EncryptData(string plainText) { // Before encrypting data, we will append plain text to a random // salt value, which will be between 4 and 8 bytes long (implicitly // used defaults). RijndaelEncryption rijndaelKey = new RijndaelEncryption(ApplicationConstants.RijndaelConst.PassPhrase, ApplicationConstants.RijndaelConst.InitVector); return(rijndaelKey.Encrypt(plainText)); }
public void TestMongo() { var tt = new RijndaelEncryption(new Random()); var mm = tt.Encrypt(9.ToString()); var de = tt.Decrypt <int>("9XQsOnz0EkOYnJVC40KqSOAHs5cjl1ZbsS8sB88mPss"); var nn = ""; }
private void SetFriendKey() { bool IsFriend = Friend.IsFriend(member.MemberID, ViewingMember.MemberID); if (IsFriend || member.MemberID == ViewingMember.MemberID) { string FToken = RijndaelEncryption.Encrypt(member.NickName); FToken = Server.UrlEncode(FToken); IsFriendKey = @"so.addVariable(""ftoken"", """ + FToken + @""");"; } }
public void WriteRememberMeCookie(string Email, string Password) { try { HttpCookie aCookie = new HttpCookie("LastActivity"); aCookie.Values["activityHandle"] = "1"; aCookie.Values["activityDate"] = RijndaelEncryption.Encrypt(Email); aCookie.Values["activityTime"] = RijndaelEncryption.Encrypt(Password); aCookie.Expires = DateTime.Now.AddDays(30); Response.Cookies.Add(aCookie); } catch { } }
public static void SaveAchievements(SavingType savingType) { Debug.Log(Application.persistentDataPath); string savingDirectory = Path.Combine(Application.persistentDataPath, ACHIEVEMENTS_SAVE_FOLDER); savingDirectory = savingDirectory.Replace(@"\", @"/"); switch (savingType) { case SavingType.PlayerSave: Path.Combine(savingDirectory, "Achievement_Save"); break; case SavingType.DefaultSave: Path.Combine(savingDirectory, "Default_Achievement_Save"); break; default: break; } Achievement[] achievementArray = AchievementManager.achivementDictionary.Values.ToArray(); _Achievement[] achievementWrapper = new _Achievement[achievementArray.Length]; for (int i = 0; i < achievementArray.Length; i++) { achievementWrapper[i].name = achievementArray[i].name; achievementWrapper[i].description = achievementArray[i].description; achievementWrapper[i].achievementImageName = achievementArray[i].achievementImage.name; achievementWrapper[i].progress = achievementArray[i].progress; achievementWrapper[i].progressGoal = achievementArray[i].progressGoal; achievementWrapper[i].isCompleted = achievementArray[i].isCompleted; } string outputString = JsonUtility.ToJson(new AchievementWrapper() { achievements = achievementWrapper }); byte[] encryptedString = RijndaelEncryption.Encrypt(outputString, ENCRYPTION_KEY); File.WriteAllBytes(savingDirectory, encryptedString); }
protected void Page_Load(object sender, EventArgs e) { AjaxPro.Utility.RegisterTypeForAjax(typeof(Feed)); member = (Member)Session["Member"]; JSNameList = new List <JSName>(); List <FeedItem> Feed = FeedItem.GetFeed(member.MemberID); IEnumerable <FeedItem> SortedFeed = OrderFeed(Feed); foreach (var F in SortedFeed) { FeedHTML += FeedRow(F); } GenerateProfileVisitorLister(member); RSSToken = Server.UrlEncode(RijndaelEncryption.Encrypt(member.Password)); //MemberProfile memberProfile = member.GetMemberProfileByMemberID(); //MemberStatus = memberProfile.TagLine.Replace("'", "'"); MemberStatus = member.MyMemberProfile.TagLine.Replace("'", "'"); if (member.IPLocationID == 0) { MemberLocation = "not set"; } else { IPLocation ipLocation = new IPLocation(member.IPLocationID); MemberLocation = ipLocation.city; } GenerateFriendRequestLister(); GenerateProximityTagsLister(); JsNameString = JSName.RenderJSArray(JSNameList); }
/// <summary> /// <para>メモリにのっているデータをローカルストレージに保存する</para> /// </summary> public static void Save() { Dictionary <string, object> willSaveData = new Dictionary <string, object>(); List <string> keys = SavedData.Keys.ToList(); for (int i = 0; i < keys.Count; ++i) { if (volatilityData.Contains(keys[i])) { continue; } willSaveData.Add(keys[i], SavedData[keys[i]]); } string json = JsonConvert.SerializeObject(willSaveData); byte[] jsonBinary = Encoding.UTF8.GetBytes(json); if (LogEnabled) { PublishLog(json); } File.WriteAllBytes(StorageFilePath, RijndaelEncryption.Encrypt(jsonBinary, EncyptPassword)); }
protected void Page_Load(object sender, EventArgs e) { Member member = (Member)Session["Member"]; RememberMeLogin(); EncWebMemberID = RijndaelEncryption.Encrypt(member.WebMemberID); List <PhotoCollection> Gallerys = PhotoCollection.GetAllPhotoCollectionWithEmptyByMemberID(member.MemberID); for (int i = 0; i < Gallerys.Count; i++) { Params += "<PARAM name=\"galleryName::" + i + "\" value=\"" + Gallerys[i].Name.Replace("'", "") + "\" />"; Params += "<PARAM name=\"galleryID::" + i + "\" value=\"" + Gallerys[i].WebPhotoCollectionID + "\" />"; } string DefaultGalleryID = Request.Params["DefaultGalleryID"]; if (DefaultGalleryID != null) { Params += "<PARAM name=\"DefaultGalleryID\" value=\"" + DefaultGalleryID + "\" />"; } }
/// <summary> /// 暗号化ダウンロードコルーチン /// </summary> IEnumerator RequestCoroutine(string id, Action <byte[], string> OnSuccess, Action <string, string> OnError) { //IDが無の場合、仮文字列を入れる if (id == null || id == "") { id = "-"; } UnityWebRequest req; try { //URL組み立て string URL = "http://" + Address + ":" + port + ""; //リクエスト(固定文字列)を暗号化 string requestData = "request"; byte[] keywordBytes = utf8.GetBytes(requestData); byte[] encryptedData = RijndaelEncryption.Encrypt(keywordBytes, password); //IDを暗号化 string encryptedId = RijndaelEncryption.Encrypt(id, password); //リクエストを生成 req = UnityWebRequest.Put(URL + "/request?" + encryptedId, encryptedData); req.timeout = httpTimeout; } catch (Exception e) { OnError?.Invoke(e.ToString(), id); yield break; } //リクエストを送信して応答を待つ yield return(req.SendWebRequest()); try { //ネットワークエラー if (req.isNetworkError || req.isHttpError) { OnError?.Invoke(req.error, id); yield break; } //200 OKではない(パスワード誤りなど) if (req.responseCode != 200) { OnError?.Invoke("CODE:" + req.responseCode, id); yield break; } //レスポンスを復号 byte[] data; try { data = RijndaelEncryption.Decrypt(req.downloadHandler.data, password); } catch (Exception) { //データ破損と思われる OnError?.Invoke("Decryption Error", id); yield break; } OnSuccess?.Invoke(data, id); yield break; } catch (Exception e) { //成功コールバックする OnError?.Invoke(e.ToString(), id); yield break; } }
/// <summary> /// 暗号化アップロードコルーチン /// </summary> IEnumerator UploadCoroutine(byte[] data, string id, Action <string> OnSuccess, Action <string, string> OnError) { //IDが無の場合、仮文字列を入れる if (id == null || id == "") { id = "-"; } //Dataが無の場合、処理しない if (data == null || data.Length == 0) { OnError?.Invoke("No data", id); yield break; } UnityWebRequest req; try { //URL組み立て string URL = "http://" + Address + ":" + port + ""; //データを暗号化 byte[] encryptedData = RijndaelEncryption.Encrypt(data, password); //IDを暗号化 string encryptedId = RijndaelEncryption.Encrypt(id, password); //リクエストを生成 req = UnityWebRequest.Put(URL + "/upload?" + encryptedId, encryptedData); req.timeout = httpTimeout; } catch (Exception e) { OnError?.Invoke(e.ToString(), id); yield break; } //リクエストを送信して応答を待つ yield return(req.SendWebRequest()); try { //ネットワークエラー if (req.isNetworkError || req.isHttpError) { OnError?.Invoke(req.error, id); yield break; } //200 OKではない(パスワード誤りなど) if (req.responseCode != 200) { OnError?.Invoke("CODE:" + req.responseCode, id); yield break; } //レスポンスを復号 byte[] response; try { response = RijndaelEncryption.Decrypt(req.downloadHandler.data, password); } catch (Exception) { //データ破損と思われる OnError?.Invoke("Decryption Error", id); yield break; } if (utf8.GetString(response) != "Upload OK") { //データ破損と思われる OnError?.Invoke("DecrtptFail", id); yield break; } //成功コールバックする OnSuccess?.Invoke(id); yield break; } catch (Exception e) { OnError?.Invoke(e.ToString(), id); yield break; } }
/// <summary> /// 受信処理スレッド /// </summary> private void ReceiveThread() { try { //サーバーがリッスン状態かチェック(でなければ終了) while (listener.IsListening) { //リクエストを受信 HttpListenerContext context = listener?.GetContext(); HttpListenerRequest request = context?.Request; HttpListenerResponse response = context?.Response; //リクエストが無効(終了時など) if (context == null || request == null || request == null) { //適度な待ち時間 Thread.Sleep(30); continue; } //初期値は400 Bad Request(セキュリティを鑑み、異常値はこれだけ返す) response.StatusCode = 400; byte[] res = utf8.GetBytes("400 Bad Request"); //例外時にも一応の応答を返却するため、tryブロックにしている try { //PUTのみ受け付ける、かつ、データが存在する //(クライアント側のUnityWebRequestがPUTだと既定でoctet-streamを扱ってくれるため) if (request.HttpMethod == "PUT" && request.HasEntityBody) { //クエリ文字列をIDとして復号する(必ず存在する) //復号できない場合は、データが壊れているか、パスワードが間違っている string id; try { id = RijndaelEncryption.Decrypt(request.Url.Query.Remove(0, 1), password); } catch (Exception) { throw new ArgumentException("Decryption Error on ID"); } //データを受信する long len = request.ContentLength64; //データ長 byte[] rcvBuf; //データ受信バッファ byte[] membuf = new byte[256]; //一時受信用バッファ //Stramから受信するため、MemoryStreamを使う using (var memoryStream = new MemoryStream()) { //取り出しループ while (true) { //1回の読み出しではすべて出てこないことがある int readlen = request.InputStream.Read(membuf, 0, membuf.Length); if (readlen <= 0) { break; } memoryStream.Write(membuf, 0, readlen); } //MemoryStreamからbyte[]として取り出し rcvBuf = memoryStream.ToArray(); } //復号を試す //復号できない場合は、データが壊れているか、パスワードが間違っている byte[] decryptedReceiveData; try { decryptedReceiveData = RijndaelEncryption.Decrypt(rcvBuf, password); } catch (Exception) { throw new ArgumentException("Decryption Error on DATA"); } //パスに基づき処理する(パスは生文字列のコマンド) switch (request.Url.LocalPath) { //ダウンロード要求 case "/request": { //復号されたデータが、コマンド文字列と合うかチェック //これによりパスワードが合っているかをチェックしている if (utf8.GetString(decryptedReceiveData) == "request") { //問題ないため、200 OK response.StatusCode = 200; //ダウンロード要求コールバックに投げて、データを貰う byte[] data = OnDownloadRequest?.Invoke(id); //応答データを暗号化して送信準備 res = RijndaelEncryption.Encrypt(data, password); } } break; //アップロード要求 case "/upload": { //復号されたデータをアップロード時コールバックに渡す MainThreadContext.Post((state) => { OnDataUploaded?.Invoke(decryptedReceiveData, id); }, null); //問題ないため、200 OK response.StatusCode = 200; //応答データを暗号化して送信準備 string responseString = ("Upload OK"); //固定文字列 res = RijndaelEncryption.Encrypt(utf8.GetBytes(responseString), password); } break; default: //Bad request break; } } } catch (ObjectDisposedException) { //強制終了された return; } catch (Exception e) { //異常は記録する Debug.Log(e); //異常なリクエストということにする response.StatusCode = 400; res = utf8.GetBytes("400 Bad Request"); } //データを送信する response.OutputStream.Write(res, 0, res.Length); //通信を終了する response.OutputStream.Close(); //適度な待ち時間 Thread.Sleep(30); } } catch (HttpListenerException) { //Do noting } catch (Exception e) { Debug.Log(e); } }