/// <summary> /// Returns an integer value from an encrypted string. /// Will return a default value if failed. /// </summary> private static int GetDecryptedInt(string val, int defaultValue) { int i = defaultValue; if (!int.TryParse(Crypto.Decrypt(val), out i)) { i = defaultValue; } return(i); }
protected string GetMeta(int retry = 0) { if (retry == 3) { return(null); } try { var meta = File.ReadAllText(SBOX_VALULT_FILE); if (string.IsNullOrEmpty(meta)) { return(string.Empty); } //Console.WriteLine($"meta {meta}"); return(crypto.Decrypt(meta, meta_key)); } catch (Exception ex) { if (ex is FileNotFoundException) { SetupMeta(Environment.CurrentDirectory); return(GetMeta(++retry)); } throw; } }
public string Unhide(string folderPath, string password) { var text = new StringBuilder(); string[] files = Directory.GetFiles(folderPath); foreach (string file in files) { string fileContent = File.ReadAllText(file); string[] words = fileContent.Split(' '); var part = new StringBuilder(); for (int i = 0; i < words.Length; i++) { int wordLength = words[i].Length; int index = wordLength % 4; if (index == wordLength) { index--; } part.Append(words[i][index]); } text.Append(part); } return(_crypto.Decrypt(text.ToString(), _hash.GenerateHash(password))); }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { context.HttpContext.Request.Cookies.TryGetValue("spb", out var spbAuthCookie); if (IsNullOrEmpty(spbAuthCookie)) { context.Result = new UnauthorizedResult(); return; } var decryptedCookie = _crypto.Decrypt(_settings.Value.CryptoSecret, spbAuthCookie); var stravaTokenModel = JsonConvert.DeserializeObject <StravaTokenModel>(decryptedCookie); long.TryParse(stravaTokenModel.ExpiresAt, out var tokenExpiry); if (tokenExpiry - DateTimeOffset.UtcNow.ToUnixTimeSeconds() > 20000) { context.HttpContext.Items["access_token"] = stravaTokenModel.AccessToken; return; } var refreshedAuthenticationResult = await _stravaAuthService.GetRefreshedToken(stravaTokenModel.RefreshToken); if (refreshedAuthenticationResult.Authenticated == false) { context.Result = new UnauthorizedResult(); //TODO: logging/ handle better? } context.HttpContext.Response.Cookies.Append("spb", refreshedAuthenticationResult.EncryptedAuthCookie); context.HttpContext.Items["access_token"] = refreshedAuthenticationResult.AccessToken; }
public (bool success, int length) TryLoad(ReadOnlyMemory <byte> buffer) { int len; if (expectedDataLength == 0) { if (buffer.Length < tagLength + 2) { return(false, tagLength + 2); } // decrypt length Memory <byte> m = new byte[2]; len = aead.Decrypt(nonce.Span, m.Span, buffer.Span); Util.SodiumIncrement(nonce.Span); if (len != 2) { return(false, 0); } expectedDataLength = m.Span[0] * 256 + m.Span[1]; if (expectedDataLength > 0x3fff) { return(false, 0); } } var totalLength = expectedDataLength + 2 * tagLength + 2; if (buffer.Length < totalLength) { return(false, totalLength); } // decrypt data var dataBuffer = buffer.Slice(tagLength + 2); Data = new byte[expectedDataLength]; len = aead.Decrypt(nonce.Span, Data.Span, dataBuffer.Span); Util.SodiumIncrement(nonce.Span); if (len != expectedDataLength) { return(false, 0); } return(true, totalLength); }
/// <summary> /// Decrypts the URL safe. /// </summary> /// <param name="value">The value.</param> /// <returns>System.String.</returns> public string DecryptUrlSafe(string value) { var bytes = HttpServerUtility.UrlTokenDecode(value); var encryptedString = Encoding.Default.GetString(bytes); var decrypt = _crypto.Decrypt(encryptedString); return(decrypt); }
protected async override Task OnBeginRequestAsync(object sender, EventArgs e) { string req; var application = sender as HttpApplication; if (application == null || !ShouldInvokeHandler(application, out req)) { return; } var context = application.Context; var client = DependencyResolver.Current.Get <IClient>(); client.SetApiKeyFromConfig(); var requestLogger = (IRequestLogger)context.Items[RequestLogger.ItemKey]; var cookie = context.Request.Cookies.Get(SessionCookieName); if (cookie != null) { var decrypted = _cryptographicService.Decrypt(cookie.Value); var parts = decrypted.Split(','); requestLogger.SessionId = parts[0]; client.BearerToken = parts[1]; client.RefreshToken = parts[2]; if (parts.Length > 3 && !string.IsNullOrEmpty(parts[3])) { client.SessionToken = parts[3]; } } if (string.IsNullOrEmpty(client.BearerToken) || string.IsNullOrEmpty(requestLogger.SessionId) || string.IsNullOrEmpty(client.SessionToken)) { try { await client.AuthenticateForLimitedPublicAsync(true).ConfigureAwait(false); requestLogger.SessionId = Guid.NewGuid().ToString("n"); } catch (Exception) { //todo: something clever } } context.Items[Constants.ShopperApiClientHttpContextItemKey] = client; ShopperApiClient.AddClient(requestLogger.RequestId, client); // the following code is designed to handle one and only one case: where we are handling the very first request since re-booting the app var zeroGuid = new Guid(); var dummy = ShopperApiClient.GetClient(zeroGuid); if (dummy == null) { ShopperApiClient.AddClient(zeroGuid, client); } else { ShopperApiClient.RemoveClient(zeroGuid); } }
public static string DecryptString(string sourse) { if (sourse == null) { return(null); } ICrypto des = CryptoManager.GetCrypto(CryptoAlgorithm.DES); sourse = sourse.Replace(" ", "+"); //HttpUtility.UrlEncode(sourse); return(des.Decrypt(sourse)); }
public static string Decrypt(string encryptedText, string encryptKey = null, bool useHashing = false) { var type = typeof(T); ICrypto crypto = (ICrypto)Activator.CreateInstance(type); if (crypto != null) { return(crypto.Decrypt(encryptedText, encryptKey, useHashing)); } return(null); }
public static string ReadContentDecrypt(string fileName) { string encrypt = File.ReadAllText(fileName, Encoding.Default); ICrypto crypto = CryptoFactory.Create(CrytoType.TripleDES); string content = crypto.Decrypt(encrypt); byte[] bytes = Encoding.UTF8.GetBytes(content); string result = ""; using (MemoryStream stream = new MemoryStream(bytes)) { stream.Seek(0, SeekOrigin.Begin); result = Encoding.UTF8.GetString(stream.ToArray()); stream.Close(); return(result); } }
/// <summary> /// 解密并进行XML反序列化 /// </summary> /// <param name="xmlFileName">文件路径</param> /// <returns></returns> public static T DeserializeDecrypt <T>(string xmlFileName) { string encrypt = File.ReadAllText(xmlFileName, Encoding.UTF8); ICrypto crypto = CryptoFactory.Create(CrytoType.TripleDES); string content = crypto.Decrypt(encrypt); byte[] bytes = Encoding.UTF8.GetBytes(content); using (MemoryStream stream = new MemoryStream(bytes)) { XmlSerializer formatter = new XmlSerializer(typeof(T)); stream.Seek(0, SeekOrigin.Begin); Object obj = formatter.Deserialize(stream); stream.Close(); return((T)obj); } }
/// <summary> /// Decrypts the specified cipher text using the default credential. /// </summary> /// <param name="crypto">An <see cref="ICrypto"/>.</param> /// <param name="cipherText">The cipher text.</param> /// <returns>The decrypted value as a byte array.</returns> public static byte[] Decrypt(this ICrypto crypto, byte[] cipherText) => crypto?.Decrypt(cipherText, null) ?? throw new ArgumentNullException(nameof(crypto));
private void RunEncryptionPrompt() { Thread.Sleep(1000); Console.WriteLine(); Console.WriteLine($"Starting..."); Console.WriteLine(); while (true) { try { Console.Write("Please enter the text you would like to encrypt: "); string input = Console.ReadLine(); IReadOnlyList <string> credentialNames = GetCredentialNames(); int selectedIndex = Prompt("Select the credential to encrypt the text:", credentialNames); if (selectedIndex == -1) { return; } string encryptCredentialName = credentialNames[selectedIndex]; string encrypted; try { encrypted = _crypto.Encrypt(input, encryptCredentialName); } catch (Exception ex) { Console.WriteLine($"Unable to encrypt using '{encryptCredentialName}'. Error: {ex.Message}"); continue; } Console.WriteLine("Encryption successful: " + encrypted); Console.WriteLine(); selectedIndex = Prompt("Select the credential to decrypt the text:", credentialNames); if (selectedIndex == -1) { return; } string decryptCredentialName = credentialNames[selectedIndex]; string decrypted; try { decrypted = _crypto.Decrypt(encrypted, decryptCredentialName); } catch (Exception ex) { Console.WriteLine($"Unable to decrypt using '{decryptCredentialName}'. Error: {ex.Message}"); continue; } Console.WriteLine("Decryption successful: " + decrypted); } finally { Console.WriteLine("Restarting..."); Console.WriteLine(); Console.WriteLine(); } } }
/// <summary> /// Decrypts the specified cipher text using the default credential. /// </summary> /// <param name="crypto">An <see cref="ICrypto"/>.</param> /// <param name="cipherText">The cipher text.</param> /// <returns>The decrypted value as a byte array.</returns> public static byte[] Decrypt(this ICrypto crypto, byte[] cipherText) => crypto.Decrypt(cipherText, null);
/// <summary> /// Decrypts the specified cipher text using the default credential. /// </summary> /// <param name="crypto">An <see cref="ICrypto"/>.</param> /// <param name="cipherText">The cipher text.</param> /// <returns>The decrypted value as a string.</returns> public static string Decrypt(this ICrypto crypto, string cipherText) => crypto.Decrypt(cipherText, null);
public List <Tuple <string, int> > LookForHiddenFiles() { return(crypto.Decrypt()); }
public static byte[] Decrypt(this string src, ICrypto crypto, bool useSalt = true) { return(crypto.Decrypt(src.Encode <UTF8Encoding>(), useSalt)); }
public static byte[] Decrypt(this byte[] src, ICrypto crypto, bool useSalt = true) { return(crypto.Decrypt(src, useSalt)); }
public async Task <EntryBase> ReadAsync(StreamReader sr, string id, bool ignoreBody) { string tmp = sr.ReadLine(); TextEntry entry; // YAML if (tmp == Identifier) { // Read YAML between the two identifiers. var yamlSB = new StringBuilder(); while (!sr.EndOfStream) { tmp = sr.ReadLine(); if (tmp == Identifier) { break; } yamlSB.AppendLine(tmp); } // Deserialize YAML var deserializer = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .WithTypeConverter(NodaTimeConverter) .Build(); if (ignoreBody) { return(deserializer.Deserialize <EntryMeta>(yamlSB.ToString())); } entry = deserializer.Deserialize <TextEntry>(yamlSB.ToString()); // Read the body entry.Id = id; entry.Body = await sr.ReadToEndAsync(); } // No YAML, read everything to body. else { if (ignoreBody) { return(new EntryMeta() { Id = id, Title = id, }); } else { entry = new TextEntry() { Id = id, Title = id, Body = tmp + await sr.ReadToEndAsync(), }; } } // Decrypt the body if (entry.Encrypted) { try { entry.Body = await Crypto.Decrypt(entry.Body); } catch (InvalidPasswordException) { throw; } } return(entry); }
protected override string GetValueWhenNotNull(DataReaderWrapper dataReader, int columnIndex) { var strVal = dataReader.GetString(columnIndex); return(_crypto.Decrypt(strVal)); }
/// <summary> /// Decrypts the base64key using an internal private key. /// </summary> /// <param name="base64Text">The encrypted string in base64 format.</param> /// <returns>The plaintext string.</returns> public static string Decrypt(string base64Text) { return(_provider.Decrypt(base64Text)); }
public Task <string> Decrypt([FromBody] string text) { return(service.Decrypt(text)); }
public string Decrypt(HttpPostedFileBase file) { return(_crypto.Decrypt(file)); }