public void JavaUploadPhoto(String encryptedWebMemberID, String webPhotoCollectionID, String base64StringPhoto, String dateTime) { if (String.IsNullOrEmpty(encryptedWebMemberID)) { throw new ArgumentNullException("encryptedWebMemberID"); } if (String.IsNullOrEmpty(webPhotoCollectionID)) { throw new ArgumentNullException("webPhotoCollectionID"); } if (String.IsNullOrEmpty(base64StringPhoto)) { throw new ArgumentNullException("base64StringPhoto"); } if (String.IsNullOrEmpty(dateTime)) { throw new ArgumentNullException("dateTime"); } Member member = null; try { var webMemberID = RijndaelEncryption.Decrypt(encryptedWebMemberID); member = Member.GetMemberViaWebMemberID(webMemberID); } catch (Exception e) { Log.Logger(String.Format("JavaUploadPhoto exception: {0}", e.Message), Identifier); Trace.Tracer(e.ToString()); throw e; } UploadPhoto(member, webPhotoCollectionID, base64StringPhoto, dateTime, false); }
private void InitializeDatabase() { Task.Factory.StartNew(() => { IEncryptionAgent encryption; string passwd; IDbManager dbManager = new Krokot.Database.Petapoco.PetapocoDbManager(null, null); IFileLoader resourceloader = new ResourceSqlLoader("resource-loader", "SqlFiles", Assembly.GetAssembly(this.GetType())); dbManager.AddSqlLoader(resourceloader); ConnectionStringCollection connections = ApplicationSettings.Instance.Database.Items; foreach (ConnectionStringElement connection in connections) { encryption = new RijndaelEncryption(connection.Key, connection.IV); passwd = encryption.Decrypt(connection.Password); dbManager.ConnectionDescriptor.Add(new ConnectionDescriptor() { ConnectionString = string.Format(connection.ConnectionString, connection.UserId, passwd), IsDefault = connection.IsDefault, Name = connection.Name, ProviderName = connection.ProviderName }); } ObjectPool.Instance.Register <IDbManager>().ImplementedBy(dbManager); }); }
public void ExecuteDecrypt() { string encryptedText = textInput.text; string passwordText = passwordInput.text; string plane = RijndaelEncryption.Decrypt(encryptedText, passwordText); resultText.text = plane; }
public static string DecryptData(string cipherText) { // 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.Decrypt(cipherText)); }
public void TestMongo() { var tt = new RijndaelEncryption(new Random()); var mm = tt.Encrypt(9.ToString()); var de = tt.Decrypt <int>("9XQsOnz0EkOYnJVC40KqSOAHs5cjl1ZbsS8sB88mPss"); var nn = ""; }
//public static double GetDistance(Member member1, Member member2) //{ // // IPLocation ipLoc1 = IPLocation.GetIPLocationByCountry(member1.ISOCountry); // //IPLocation ipLoc2 = IPLocation.GetIPLocationByCountry(member2.ISOCountry); // double lon2 = (double)ipLoc2.longitude; // double lon1 = (double)ipLoc1.longitude; // double lat2 = (double)ipLoc2.latitude; // double lat1 = (double)ipLoc1.latitude; // double dlon = lon2 - lon1; // double dlat = lat2 - lat1; // double a = Math.Pow(Math.Sin(dlat / 2), 2) + Math.Cos(lat1) * Math.Cos(lat2) * Math.Pow(Math.Sin(dlon / 2),2); // double c = 2 * Math.Asin(Math.Min(1,Math.Sqrt(a))); // return RADIUS * c; //} public static void RememberMeLogin() { System.Web.SessionState.HttpSessionState Session = HttpContext.Current.Session; HttpRequest Request = HttpContext.Current.Request; // If we are already signed in if (Session["Member"] != null) { return; } HttpCookie aCookie = Request.Cookies["LastActivity"]; if (aCookie == null) { return; } string autoLogin = aCookie.Values["activityHandle"]; if (autoLogin == "1") { string login = aCookie.Values["activityDate"]; string password = aCookie.Values["activityTime"]; login = RijndaelEncryption.Decrypt(login); password = RijndaelEncryption.Decrypt(password); Member member = Member.WebMemberLogin(login, password); if (member != null) { Session["Member"] = member; OnlineNow now = new OnlineNow(); now.MemberID = member.MemberID; now.DTOnline = DateTime.Now; now.Save(); string PageName = HttpContext.Current.Request.Url.AbsolutePath.ToLower(); if (PageName == "/") { HttpContext.Current.Response.Redirect("/dashboard"); } } } Utility.AddToLoggedIn(); }
public static void LoadAchievements(SavingType savingType) { string loadingDirectory = Path.Combine(Application.persistentDataPath, ACHIEVEMENTS_SAVE_FOLDER); byte[] encryptedJson; string decryptedJson = string.Empty; switch (savingType) { case SavingType.PlayerSave: Path.Combine(loadingDirectory, "Achievement_Save"); break; case SavingType.DefaultSave: Path.Combine(loadingDirectory, "Default_Achievement_Save"); break; default: break; } loadingDirectory = loadingDirectory.Replace(@"\", @"/"); encryptedJson = File.ReadAllBytes(loadingDirectory); decryptedJson = RijndaelEncryption.Decrypt(encryptedJson, ENCRYPTION_KEY); AchievementManager.achivementDictionary.Clear(); foreach (_Achievement achievement in JsonUtility.FromJson <AchievementWrapper>(decryptedJson).achievements) { Achievement dictAchievement = new Achievement(); dictAchievement.name = achievement.name; dictAchievement.description = achievement.description; dictAchievement.achievementImage = Resources.Load <Sprite>(ACHIEVEMENT_ICON_PATH + '/' + achievement.achievementImageName); dictAchievement.progress = achievement.progress; dictAchievement.progressGoal = achievement.progressGoal; dictAchievement.isCompleted = achievement.isCompleted; AchievementManager.achivementDictionary.Add(achievement.name, dictAchievement); } }
/// <summary> /// <para>ローカルストレージに保存されているデータを読み込む</para> /// </summary> public static Dictionary <string, object> Load() { string json = ""; string filePath = StorageFilePath; if (File.Exists(filePath)) { byte[] savedDataJsonBinary = RijndaelEncryption.Decrypt(File.ReadAllBytes(filePath), EncyptPassword); json = Encoding.UTF8.GetString(savedDataJsonBinary); } Dictionary <string, object> parsedJson = new Dictionary <string, object>(); if (!string.IsNullOrEmpty(json)) { parsedJson = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); } if (LogEnabled) { PublishLog(json); } return(parsedJson); }
public void RememberMeLogin() { // If we are already signed in if (Session["Member"] != null) { return; } HttpCookie aCookie = Request.Cookies["LastActivity"]; if (aCookie == null) { return; } string autoLogin = aCookie.Values["activityHandle"]; if (autoLogin == "1") { string login = aCookie.Values["activityDate"]; string password = aCookie.Values["activityTime"]; login = RijndaelEncryption.Decrypt(login); password = RijndaelEncryption.Decrypt(password); Member memberD = Member.WebMemberLogin(login, password); Session["Member"] = memberD; OnlineNow now = new OnlineNow(); now.MemberID = memberD.MemberID; now.DTOnline = DateTime.Now; now.Save(); Utility.AddToLoggedIn(); } }
public static ApikeyPrefs LoadFromFile() { byte[] encryptedBinary = File.ReadAllBytes(RecordFilePath); byte[] accountBinary = RijndaelEncryption.Decrypt(encryptedBinary, EncyptPassword); return(JsonUtility.FromJson <ApikeyPrefs>(Encoding.ASCII.GetString(accountBinary))); }
protected void Page_Load(object sender, EventArgs e) { NickName = Request.Params["nickname"]; Password = Request.Params["token"]; FeedType = Request.Params["feed"]; FriendNick = Request.Params["friend"]; if (NickName != null && Password != null) { try { Password = RijndaelEncryption.Decrypt(Password); member = Member.SafeMemberLogin(NickName, Password); } catch {} } if (FriendNick != null) { try { friendMember = Member.GetMemberViaNickname(FriendNick); } catch { } } dt.Columns.Add("Title"); dt.Columns.Add("Link"); dt.Columns.Add("DTCreated"); dt.Columns.Add("Duration"); dt.Columns.Add("Description"); dt.Columns.Add("ResourceFileThumb"); dt.Columns.Add("ResourceLink"); if (FeedType == null || !(FeedType == "dashboard" || FeedType == "video" || FeedType == "uservideo")) { FeedType = "nofeedtype"; } if (member == null && FeedType == "dashboard") { FeedType = "dashboarderror"; } switch (FeedType) { case "nofeedtype": FeedTitle = "Next2Friends RSS Error"; FeedDescription = "Invalid RSS"; GetInvalidFeedErrorRss(); break; case "dashboarderror": FeedTitle = "Next2Friends RSS Error"; FeedDescription = "Could not logon to your Next2Friends dashboard feed"; GetDashboardErrorRss(); break; case "video": FeedTitle = "Next2Friends Videos"; FeedDescription = "Next2Friends Videos RSS Feed"; GetVideoRss(); break; case "uservideo": if (friendMember != null) { FeedTitle = "Next2Friends: " + friendMember.NickName + "'s Videos"; FeedDescription = "Next2Friends: " + friendMember.NickName + "'s Videos RSS Feed"; GetFriendVideoRss(friendMember); } break; case "photo": FeedTitle = "Photo"; FeedDescription = "Photo RSS Feed"; GetPhotoRss(member.MemberID); break; case "blog": FeedTitle = "Blog"; FeedDescription = "Blog RSS Feed"; GetBlogRss(member.WebMemberID); break; case "dashboard": FeedTitle = member.NickName + "'s Next2Friends Dashboard"; FeedDescription = member.NickName + "'s Dashboard RSS Feed"; GetDashboardRss(member.MemberID); break; case "live": FeedTitle = "live"; FeedDescription = "Live RSS Feed"; GetLiveRss(member.MemberID); break; default: break; } rptRssFeed.DataSource = dt; rptRssFeed.DataBind(); }
/// <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); } }