public FieldLevelEncryption(byte[] rawPublicKeyData, byte[] rawPrivateKeyData, Config config, String publicKeyFingerprint, X509KeyStorageFlags keyStorageFlags = X509KeyStorageFlags.DefaultKeySet) { if (rawPublicKeyData != null && rawPublicKeyData.LongLength > 0L) { var tmpPublicCertificate = new X509Certificate2(rawPublicKeyData, String.Empty, keyStorageFlags); this.publicKey = (RSACng)tmpPublicCertificate.GetRSAPublicKey(); if (publicKeyFingerprint != null) { this.publicKeyFingerPrint = publicKeyFingerprint; } else { this.publicKeyFingerPrint = tmpPublicCertificate.Thumbprint; } } if (rawPrivateKeyData != null) { string fullText = Encoding.UTF8.GetString(rawPrivateKeyData); this.privateKey = CryptUtil.GetRSAFromPrivateKeyString(fullText); } this.configuration = config; }
public FieldLevelEncryption(String publicKeyLocation, String privateKeyLocation, Config config, String publicKeyFingerprint, X509KeyStorageFlags keyStorageFlags = X509KeyStorageFlags.DefaultKeySet) { if (publicKeyLocation != null) { var tmpPublicCertificate = new X509Certificate2(publicKeyLocation, String.Empty, keyStorageFlags); this.publicKey = (RSACng)tmpPublicCertificate.GetRSAPublicKey(); if (publicKeyFingerprint != null) { this.publicKeyFingerPrint = publicKeyFingerprint; } else { this.publicKeyFingerPrint = tmpPublicCertificate.Thumbprint; } } if (privateKeyLocation != null) { string fullText = File.ReadAllText(privateKeyLocation); this.privateKey = CryptUtil.GetRSAFromPrivateKeyString(fullText); } this.configuration = config; }
public void TestSalt() { var saltbytes = CryptUtil.CreateIVByRepeatingSalt("re!".ToUtf8()); var decoded = saltbytes.Decode(); Check.That(decoded).Equals("re!re!re!re!re!r"); }
protected void btnLogin_Click(object sender, EventArgs e) { var returnUrl = Request.QueryString["returnUrl"]; bool loginValid = false; var userName = tbUsername.Text; var pw = tbPassword.Text; var ctx = new RedditRSSEntities(); var appUser = ctx.AppUsers.Where(x => x.Username == userName).FirstOrDefault(); if (appUser != null) { var validPW = CryptUtil.ValidatePassword(pw, appUser.HashedPassword); if (validPW) { loginValid = true; Session[AppConstants.SessionKeys.LOGGED_IN_USER_ID] = appUser.ID; Session[AppConstants.SessionKeys.LOGGED_IN_USER_NAME] = appUser.Username; } } if (!loginValid) { lblMessage.Text = "Login invalid. Please check the username and password"; } else { Response.Redirect("~/" + (returnUrl == null ? "": returnUrl)); } }
public string method_1(string url, string string_1) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/octet-stream"; request.CookieContainer = this.cookieContainer; Stream requestStream = request.GetRequestStream(); new StreamWriter(requestStream, Encoding.GetEncoding("utf-8")); byte[] buffer = CryptUtil.smethod_0(string_1); requestStream.Write(buffer, 0, buffer.Length); requestStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); response.Cookies = this.cookieContainer.GetCookies(response.ResponseUri); Stream responseStream = response.GetResponseStream(); ArrayList list = new ArrayList(); int num = -1; while ((num = responseStream.ReadByte()) != -1) { list.Add((byte)num); } int index = 0; byte[] bytes = new byte[list.Count]; foreach (byte num3 in list) { bytes[index] = num3; index++; } responseStream.Close(); return(Encoding.UTF8.GetString(bytes, 0, index)); }
public void TestFullEndToEndEncryptDecrypt() { string certPath = MasterCard.Core.Util.GetCurrenyAssemblyPath() + "\\Test\\certificate.p12"; X509Certificate2 cert = new X509Certificate2(certPath, "", X509KeyStorageFlags.Exportable); var publicKey = cert.GetRSAPublicKey() as RSACng; var privateKey = cert.GetRSAPrivateKey() as RSACng; String data = "*****@*****.**"; Tuple <byte[], byte[], byte[]> aesResult = CryptUtil.EncryptAES(Encoding.UTF8.GetBytes(data), 128, CipherMode.CBC, PaddingMode.PKCS7); byte[] ivBytes = aesResult.Item1; // 5) generate AES SecretKey byte[] secretKeyBytes = aesResult.Item2; // 6) encrypt payload byte[] encryptedDataBytes = aesResult.Item3; byte[] encryptedSecretKey = CryptUtil.EncrytptRSA(secretKeyBytes, publicKey, RSAEncryptionPadding.OaepSHA256); byte[] decryptedSecretKey = CryptUtil.DecryptRSA(encryptedSecretKey, privateKey, RSAEncryptionPadding.OaepSHA256); byte[] decryptedDataBytes = CryptUtil.DecryptAES(ivBytes, decryptedSecretKey, encryptedDataBytes, 128, CipherMode.CBC, PaddingMode.PKCS7); String dataOut = System.Text.Encoding.UTF8.GetString(decryptedDataBytes); Assert.AreEqual(data, dataOut); }
public File GetFile(string fileUId, bool includeData = true) { IQueryable <File> file = _context.Files; if (includeData) { file = _context.Files.Include("Data"); } var f = file.SingleOrDefault(x => x.FileUId == fileUId); if (EncryptFiles && f.Data != null) { var crypt = new CryptUtil(Settings); if (f.Data.StoredData != null) { f.Data.StoredData = crypt.DecryptBytes(f.Data.StoredData); } if (f.Data.StoredThumbData != null) { f.Data.StoredThumbData = crypt.DecryptBytes(f.Data.StoredThumbData); } } return(f); }
private void LoadFromCookie() { ID = Guid.NewGuid(); var cookie = m_httpCtx.Request.Cookies[CookieName]; // decrypt existing and set sessionid if (cookie != null) { try { string sessionIDString = CryptUtil.Decrypt(cookie.Value); Guid temp; if (Guid.TryParse(sessionIDString, out temp)) { ID = temp; } } catch { // if anything fails fallback to new sessionid Debug.WriteLine("Session cookie could not be decrypted!"); SaveToCookie(); } } }
public static bool smethod_0(string string_0) { Form2 form; string str = ""; str = smethod_3() + smethod_4(); CryptUtil.encrypt(str); if (!File.Exists(string_0 + "/支付宝采集.key")) { Clipboard.SetDataObject(str); form = new Form2(); form.textBoxMashine.Text = str; form.textBoxKey.Text = "没有KEY文件!"; form.ShowDialog(); return(false); } string str2 = new StreamReader(string_0 + "/支付宝采集.key").ReadToEnd(); string str3 = CryptUtil.decrypt(str2); if (!str3.Equals(str)) { Clipboard.SetDataObject(str); form = new Form2(); form.textBoxMashine.Text = str; form.textBoxKey.Text = str + "***" + str2 + "***" + str3; form.ShowDialog(); return(false); } return(true); }
public File GetFile(string fileUId, bool includeData = true) { using (var context = new Data.CMSContext()) { IQueryable <File> file = context.Files; if (includeData) { file = context.Files.Include("Data"); } var f = file.SingleOrDefault(x => x.FileUId == fileUId); if (EncryptFiles && f.Data != null) { if (f.Data.StoredData != null) { f.Data.StoredData = CryptUtil.DecryptBytes(f.Data.StoredData); } if (f.Data.StoredThumbData != null) { f.Data.StoredThumbData = CryptUtil.DecryptBytes(f.Data.StoredThumbData); } } return(f); } }
public IDictionary <string, object> Encrypt(IDictionary <string, object> map) { if (map.ContainsKey("cardInfo")) { string text = JsonConvert.SerializeObject((IDictionary <string, object>)map["cardInfo"]); text = CryptUtil.SanitizeJson(text); Tuple <byte[], byte[], byte[]> expr_3D = CryptUtil.EncryptAES(Encoding.UTF8.GetBytes(text)); byte[] item = expr_3D.Item1; byte[] item2 = expr_3D.Item2; byte[] arg_57_0 = expr_3D.Item3; string value = CryptUtil.HexEncode(item); string value2 = CryptUtil.HexEncode(arg_57_0); string value3 = CryptUtil.HexEncode(CryptUtil.EncrytptRSA(item2, this.publicKey)); string value4 = this.publicKeyFingerPrint; Dictionary <string, object> dictionary = new Dictionary <string, object>(); dictionary.Add("publicKeyFingerprint", value4); dictionary.Add("encryptedKey", value3); dictionary.Add("oaepHashingAlgorithm", "SHA256"); dictionary.Add("iv", value); dictionary.Add("encryptedData", value2); map.Remove("cardInfo"); map.Add("cardInfo", dictionary); } return(map); }
public FormLogin(string softwarename, string version) { InitializeComponent(); this.softwarename = softwarename; this.version = version; this.app_path = Directory.GetCurrentDirectory(); this.user_ini_path = this.app_path + "/config/user.ini"; if (File.Exists(this.user_ini_path)) { try { StreamReader reader = new StreamReader(this.user_ini_path); string str = null; while ((str = reader.ReadLine()) != null) { str = CryptUtil.decrypt(str); this.hashtable_0.Add(str.Split(new char[] { '=' })[0], str.Split(new char[] { '=' })[1]); } reader.Close(); reader.Dispose(); this.textBoxUser.Text = (string)this.hashtable_0["username"]; this.textBoxPwd.Text = (string)this.hashtable_0["pwd"]; } catch { } } }
public static string GetPlainValue(EncryptedField field) { if (field == null) { return((string)null); } return(!field.IsEncrypted ? field.Value : CryptUtil.Decrypt(field.Value)); }
public string EncryptPassword() { if (string.IsNullOrEmpty(_password)) { return(null); } return(CryptUtil.EncryptRedditPassword(_password, ConfigurationManager.AppSettings["CryptSharedSecret"])); }
public void TestDes() { String skey = "1234567890123456"; //string ddd = Convert.ToBase64String(Encoding.UTF8.GetBytes("1231313")); string dd = CryptUtil.EncryptDes("15611802686", skey); string cc = CryptUtil.DecryptDes("SWRjRMW1EH6SiDtUq2Pj+4Mtscup+IFzsu4aj4REJZ9cgSI0zD4kEQ==", skey); Assert.AreEqual("Z4bEu0glHasENUzgYotuiw==", dd); }
public void IssueNewKey() { var masterkey = Key.CreateFromBytes("masterkey", CryptUtil.CreateRandomBytesForKey()); var keyRing = new Secrets(); keyRing.Keys.Add(Secrets.IssueKey("user_key_1", masterkey)); keyRing.Keys.Add(Secrets.IssueKey("user_key_2", masterkey)); }
public void TestCryptedtrings() { var b = SomeBytes(20); var k = CryptUtil.CreateEncryptedString("mykey", b); var parsed = CryptUtil.ParseEncryptedString(k); Check.That(parsed?.Bytes).Equals(b); Check.That(parsed?.KeyName == "mykey"); }
/// <summary> /// カレンダーのインポート処理 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ImportButton_Click(object sender, EventArgs e) { try { string kana = "カレンダー"; string file1 = "mcrc"; string file2 = "MCRC"; var dialog = new CommonOpenFileDialog(kana + "ファイルの選択"); // ファイル選択モード dialog.IsFolderPicker = false; dialog.Multiselect = false; dialog.Filters.Add(new CommonFileDialogFilter(file2 + "ファイル(*." + file1 + ")", "*." + file1)); if (dialog.ShowDialog(this.Handle) == CommonFileDialogResult.Ok) { CalendarModel model = null; //新取込 using (StreamReader sr = new StreamReader(dialog.FileName, Encoding.Default)) { string jsonString = sr.ReadToEnd(); try { model = JsonConvert.DeserializeObject <CalendarModel>(jsonString); } catch (Exception) {} } if (model == null) { using (FileStream fs = new FileStream(dialog.FileName, FileMode.Open, FileAccess.Read)) { BinaryFormatter f = new BinaryFormatter(); string jsonString = (string)f.Deserialize(fs); jsonString = CryptUtil.DecryptString(jsonString, StringValue.CRYPT_PASSWORD); model = JsonConvert.DeserializeObject <CalendarModel>(jsonString); } } //IDを更新する model.CalendarId = CalendarInfos.GetNewCalendarModel().CalendarId; DialogResult result = this.ShowInfoDialog("保存確認", kana + "をインポートしますか?", MessageBoxButtons.YesNo, MessageBoxDefaultButton.Button1); if (result == DialogResult.No) { return; } CalendarInfos.GetInstance().CreateCalendarValue(model.CalendarId, model.Description, model, model.CalendarType); LoadCalendarData(); } } catch (Exception ex) { throw Program.ThrowException(ex); } }
public void interfaces() { var res = rv_core.Utils.MacUtil.GetNetworkInterfaces(); Console.WriteLine(res); var mac = rv_core.Utils.MacUtil.GetMacByName(); mac = CryptUtil.Md5Encode(mac); Console.WriteLine("MAC:" + mac); }
public MDESCryptography(string publicKeyLocation, string privateKeyLocation) { X509Certificate2 x509Certificate = new X509Certificate2(publicKeyLocation); this.publicKey = x509Certificate.GetRSAPublicKey(); this.publicKeyFingerPrint = x509Certificate.Thumbprint; string text = File.ReadAllText(privateKeyLocation); this.privateKey = CryptUtil.GetRSAFromPrivateKeyString(text); }
public void TestHexUnHex() { String nonHexed = "*****@*****.**"; String hexed = CryptUtil.HexEncode(nonHexed); byte[] nonHexedBytes = CryptUtil.HexDecode(hexed); String nonHexed2 = System.Text.Encoding.UTF8.GetString(nonHexedBytes); Assert.AreEqual(nonHexed, nonHexed2); }
public void DirectEncrypt() { var plainText = Encoding.UTF8.GetBytes("Hello world"); var iv = SomeBytes(16); var key = SomeBytes(32); var encrypted = CryptUtil.EncryptBytes(key, iv, plainText); var decrypted = CryptUtil.DecryptBytes(key, iv, encrypted); Check.That(decrypted).Equals(plainText); }
public string getMd5() { FileStream fs = new FileStream(this.path, FileMode.Open); byte[] bytes = new byte[fs.Length]; fs.Read(bytes, 0, bytes.Length); string md5 = CryptUtil.GetMD5(bytes); fs.Close(); return(md5); }
public void BeginElement( string name, UnknownObjectReader value, string[] attributeNames, object[] attributeValues) { foreach (string resolvedElement in this._ResolvedElements) { this._Writer.WriteStartElement(resolvedElement); } this._ResolvedElements.Clear(); this._Writer.WriteStartElement(name); if (attributeNames != null && attributeValues != null) { int num = 0; foreach (string attributeName in attributeNames) { this._Writer.WriteAttributeString(attributeName, attributeValues[num++].ToString()); } } if (value == null) { return; } if (value.Value is string || value.Value is IPrimitive) { if (value.Value is PasswordFieldType) { this._Writer.WriteAttributeString("__encrypted", "yes"); this._Writer.WriteCData(CryptUtil.Encrypt(value.Value.ToString())); } else { this._Writer.WriteCData(value.Value.ToString()); } } else if (value.Value is EncryptedField) { this._Writer.WriteAttributeString("__encrypted", "yes"); EncryptedField encryptedField = value.Value as EncryptedField; if (encryptedField.IsEncrypted) { this._Writer.WriteCData(encryptedField.Value); } else { this._Writer.WriteCData(CryptUtil.Encrypt(encryptedField.Value)); } } else { this._Writer.WriteCData(value.Value.ToString().ToLower()); } }
public void TestEncryptDecryptAES() { String data = "*****@*****.**"; Tuple <byte[], byte[], byte[]> tuple = CryptUtil.EncryptAES(System.Text.Encoding.UTF8.GetBytes(data)); byte[] decryptedData = CryptUtil.DecryptAES(tuple.Item1, tuple.Item2, tuple.Item3); String data2 = System.Text.Encoding.UTF8.GetString(decryptedData); Assert.AreEqual(data, data2); }
public MDESCryptography(String publicKeyLocation, String privateKeyLocation) { var tmpPublicCertificate = new X509Certificate2(publicKeyLocation); this.publicKey = tmpPublicCertificate.GetRSAPublicKey(); this.publicKeyFingerPrint = tmpPublicCertificate.Thumbprint; string fullText = File.ReadAllText(privateKeyLocation); this.privateKey = CryptUtil.GetRSAFromPrivateKeyString(fullText) as RSA; }
/* * public override void BeginTransaction() * { * conn.Open(); * transaction = conn.BeginTransaction(); * inTranscation = true; * } * * public override void CommitTransaction() * { * transaction.Commit(); * inTranscation = false; * if (conn.State == ConnectionState.Open) * { * conn.Close(); * } * } * * public override void RollbackTransaction() * { * transaction.Rollback(); * inTranscation = false; * if (conn.State == ConnectionState.Open) * { * conn.Close(); * } * }*/ public override string getMachineCode() { string sql = string.Format("SELECT date_format(CREATE_TIME,'%Y-%m-%d %T') MACCODESOURCE FROM information_schema.TABLES where table_schema=DATABASE() and table_name='SYS_REG'"); DataTable dt = RunSql(sql); if (dt.Rows.Count > 0) { string code = dt.Rows[0]["MACCODESOURCE"].ToString(); return(code.Equals("") ? "" : CryptUtil.GetMd5Hash(code, true)); } return(""); }
/* * public override void BeginTransaction() * { * if (conn.State == ConnectionState.Closed) * { * conn.Open(); * } * transaction = conn.BeginTransaction(); * inTranscation = true; * } * * public override void CommitTransaction() * { * transaction.Commit(); * inTranscation = false; * if (conn.State == ConnectionState.Open) * { * conn.Close(); * } * } * * public override void RollbackTransaction() * { * transaction.Rollback(); * inTranscation = false; * if (conn.State == ConnectionState.Open) * { * conn.Close(); * } * }*/ public override string getMachineCode() { string sql = string.Format("select OBJECT_ID||to_char(CREATED,''yyyy-MM-dd HH24:mi:ss'') AS MACCODESOURCE from USER_OBJECTS WHERE OBJECT_NAME='SYS_REG'"); DataTable dt = RunSql(sql); if (dt.Rows.Count > 0) { string code = dt.Rows[0]["MACCODESOURCE"].ToString(); return(code.Equals("") ? "" : CryptUtil.GetMd5Hash(code, true)); } return(""); }
public override string getMachineCode() { string sql = string.Format("select convert(varchar(20),database_id)+convert(varchar(100),create_date,120) as MACCODESOURCE FROM sys.databases where name='{0}'", dbaseName); DataTable dt = RunSql(sql); if (dt.Rows.Count > 0) { string code = dt.Rows[0]["MACCODESOURCE"].ToString(); return(code.Equals("") ? "" : CryptUtil.GetMd5Hash(code, true)); } return(""); }
public string HashPassword() { if (Password == null) { throw new ArgumentException("Password is null, cannot hash."); } if (this.HashedPassword == null) { HashedPassword = CryptUtil.HashAppUserPassword(Password); } return(HashedPassword); }