public void Encrypt_Decrypt_Test() { AesHelper aes = new AesHelper(); string source = "admin"; //byte[] byte[] sourceBytes = source.ToBytes(); byte[] enBytes = aes.Encrypt(sourceBytes); aes.Decrypt(enBytes).ShouldBe(sourceBytes); //string string enstr = aes.Encrypt(source); aes.Decrypt(enstr).ShouldBe(source); aes = new AesHelper(true); //byte[] enBytes = aes.Encrypt(sourceBytes); aes.Decrypt(enBytes).ShouldBe(sourceBytes); //string enstr = aes.Encrypt(source); aes.Decrypt(enstr).ShouldBe(source); }
public static T Load<T>(string file, string key = null) where T : class { if (string.IsNullOrWhiteSpace(file)) throw new ArgumentNullException("file"); if (string.IsNullOrWhiteSpace(key)) key = MachineKey.Value; var path = DefaultPath; if (Path.IsPathRooted(file)) { path = Path.GetDirectoryName(file); } else file = Path.Combine(path, file); if (File.Exists(file)) { var bf = new BinaryFormatter(); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var bytes = (byte[])bf.Deserialize(fs); var a = AesHelper.Decrypt(bytes, key); using (var msm = new MemoryStream(a)) { try { return (T)bf.Deserialize(msm); } catch { return null; } } } } return null; }
public Task <T> ExecuteAsync <T>(string body, WeChatPayOptions options) where T : WeChatPayNotify { if (string.IsNullOrEmpty(body)) { throw new ArgumentNullException(nameof(body)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } if (string.IsNullOrEmpty(options.Key)) { throw new ArgumentNullException(nameof(options.Key)); } var parser = new WeChatPayNotifyXmlParser <T>(); var notify = parser.Parse(body); if (notify is Notify.WeChatPayRefundNotify) { var key = MD5.Compute(options.Key).ToLowerInvariant(); var data = AesHelper.Decrypt((notify as Notify.WeChatPayRefundNotify).ReqInfo, key); //todo PKCS7 Encrypt notify = parser.Parse(body, data); } else { CheckNotifySign(notify, options); } return(Task.FromResult(notify)); }
public void AesErrorTest() { Should.Throw <Exception>(() => { AesHelper.Encrypt("AES加密", "123", "1234567890123456"); }); Should.Throw <Exception>(() => { AesHelper.Encrypt("AES加密", "1234567890123456", "123"); }); Should.Throw <Exception>(() => { AesHelper.Decrypt("B2zgIp4Wvi/SohcgcqQn+Q==", "123", "1234567890123456"); }); Should.Throw <Exception>(() => { AesHelper.Decrypt("B2zgIp4Wvi/SohcgcqQn+Q==", "1234567890123456", "123"); }); }
private static AdminUser LoadCookie() { try { HttpCookie cookie = HttpContext.Current.Request.Cookies["SyUserInfo"]; if (cookie == null) { return(null); } cookie.HttpOnly = true; string loginName = AesHelper.Decrypt(cookie["LoginName"]); string password = AesHelper.Decrypt(cookie["Password"]); if (string.IsNullOrEmpty(loginName) || string.IsNullOrEmpty(password)) { return(null); } if (Login(loginName, password)) { return(null); } } catch (Exception ex) { LogHelper.Error("登录出错:" + ex.Message, ex); } return(HttpContext.Current.Session["SyUserInfo"] as AdminUser); }
// 过滤从游戏服务器收到的消息 public byte[] FilterReceivedBytes(byte[] s) { if (m_bFilterGameServerMsg) { int lengthIndicatorSize = sizeof(uint); System.IO.MemoryStream stream = new System.IO.MemoryStream(s); System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(stream); int packLen = (int)binaryReader.ReadUInt32(); // 消息包的总长度 // 待解密的部分 byte[] ciphertext = binaryReader.ReadBytes(packLen - lengthIndicatorSize); // 解密 byte[] plaintext = m_aesHelper.Decrypt(ciphertext); // 修正packLen packLen = lengthIndicatorSize + plaintext.Length; // 重组新消息包 byte[] outBytes = new byte[packLen]; byte[] packLenBytes = System.BitConverter.GetBytes(packLen); packLenBytes.CopyTo(outBytes, 0); plaintext.CopyTo(outBytes, packLenBytes.Length); // 返回新消息包 return(outBytes); } else { return(s); } }
public void AesDecrypt() { var key = "1234567890123456"; var iv = "1234567890123456"; var data = AesHelper.Decrypt("B2zgIp4Wvi/SohcgcqQn+Q==", key, iv); data.ShouldBe("AES加密"); }
public IActionResult Post([FromBody] Body order) { Console.WriteLine(order.Content); var result = aesHelper.Decrypt(order.Content); Console.WriteLine(result); return(Ok(order)); }
protected T DeserialiseModel <T>(string modelString) { Debug.Assert(!string.IsNullOrEmpty(modelString)); var aesKey = Configuration["Encryption:AesKey"]; var aesIv = Configuration["Encryption:AesInitializationVector"]; modelString = AesHelper.Decrypt(modelString, aesKey, aesIv); return(JsonConvert.DeserializeObject <T>(modelString)); }
public object GenerateReFreshToken(string token) { var configReader = new ConfigurationReader(); var tokenManager = new TokenManager(configReader); var decrypt = AesHelper.Decrypt(token); UserTokenData userTokenData = JsonConvert.DeserializeObject <UserTokenData>(decrypt); return(tokenManager.GenerateUserRefreshToken(userTokenData)); }
public async Task <string> HandleTextResponse(HttpResponseMessage response) { if (response.IsSuccessStatusCode) { if (response.Content.Headers.ContentLength.HasValue && response.Content.Headers.ContentLength.Value == 0) { return(string.Empty); } using var responseBody = new MemoryStream(); await response.Content.CopyToAsync(responseBody); if (responseBody.Position == 0) { return(string.Empty); } responseBody.Position = 0; switch (response.Content.Headers.ContentType.MediaType) { case "text/html": throw new Exception(await response.Content.ReadAsStringAsync()); case "application/json": { using (var reader = new StreamReader(await response.Content.ReadAsStreamAsync())) { return(await reader.ReadToEndAsync()); } } case "application/pink-umbrella": { using (var stream = await response.Content.ReadAsStreamAsync()) { using (var outputStream = new MemoryStream()) { var cipherHeader = response.Content.Headers.GetValues("X-Api-Cipher").First(); var helper = new AesHelper(); stream.Read(helper.IV); var cipherEncrypted = new MemoryStream(Convert.FromBase64String(cipherHeader)); var cipherDecrypted = new MemoryStream(); await new RSAAuthHandlerMsft().DecryptAndVerifyStreamAsync(cipherEncrypted, cipherDecrypted, _keys.Private, _keys.Public, null); helper.Decrypt(stream, outputStream); return(System.Text.Encoding.UTF8.GetString(outputStream.ToArray())); } } } default: throw new Exception($"Invalid response type {response.Content.Headers.ContentType.MediaType}"); } } else { throw new Exception($"Invalid response: {response.StatusCode}, {await response.Content.ReadAsStringAsync()}"); } }
public async Task <OperationContentViewModel> QueryOperationContentAsync(QueryOperationContent query) { var adminLog = await _adminLogRepository.QueryById(query.Id); if (adminLog == null) { return(null); } var aesHelper = new AesHelper(); var decryptAfterContent = aesHelper.Decrypt(adminLog.AfterContent); var decryptBeforeContent = aesHelper.Decrypt(adminLog.BeforeContent); return(new OperationContentViewModel() { AfterContent = decryptAfterContent, BeforeContent = decryptBeforeContent }); }
//Action方法执行之前执行此方法 public override void OnActionExecuting(HttpActionContext actionContext) { //给每一次请求分配一个特定编号 CallContext.SetData(Constants.RequestLogId, DateTime.Now.ToString("yyyyMMddHHmmssfffffff") + CommonHelper.GetTimeStamp()); if (actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any()) { return; } //前期考虑 前端调用直接把userid 以及accid 放在header里边 后期考虑使用token var request = actionContext.Request.Headers; var jsonFormatter = new JsonMediaTypeFormatter { SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() } }; var token = request.SingleOrDefault(x => x.Key.ToLower() == "token"); var oAppkey = request.SingleOrDefault(x => x.Key.ToLower() == "appkey"); var strAppkey = oAppkey.Key == null ? string.Empty : oAppkey.Value.FirstOrDefault(); var userContext = new EntityAccountManager(); //token 授权 if (token.Key != null) { try { var strToken = token.Value.FirstOrDefault(); //解密获得token原始信息 var aesToken = AesHelper.Decrypt(strToken); //添加到用户上下文 userContext = JsonConvert.DeserializeObject <EntityAccountManager>(aesToken); } catch { throw new EmergencyException("api接口请求验证不通过", (int)ErrorCodeEnum.TokenIsExpired); } } else { throw new EmergencyException("api接口请求验证不通过", (int)ErrorCodeEnum.ApiRequestForbidden); } actionContext.Request.Properties[Constants.GlobalUserContextKeyName] = userContext; System.Threading.Thread.CurrentPrincipal = new EmergencyPrincipal { UserContext = userContext }; }
public void Test_AesHelper() { string text = AesHelper.Encrypt(s_input, s_key); string result = AesHelper.Decrypt(text, s_key); Assert.AreEqual(s_input, result); byte[] b1 = s_input.GetBytes(); byte[] b2 = AesHelper.Encrypt(b1, s_key); byte[] b3 = AesHelper.Decrypt(b2, s_key); Assert.IsTrue(ByteTestHelper.AreEqual(b1, b3)); }
public void Aes加密() { string str1 = "aaaaaaaaaaaaaaaaaa"; string password = "******"; // 加密 string base64 = AesHelper.Encrypt(str1, password); // 解密 string str2 = AesHelper.Decrypt(base64, password); Assert.AreEqual(str1, str2); }
/// <summary> /// Step #5 /// /// Read, decrypt and process the code section. /// </summary> /// <returns></returns> private bool Step5() { // Skip decryption if the code section is not encrypted.. if ((this.StubHeader.Flags & (uint)SteamStubDrmFlags.NoEncryption) == (uint)SteamStubDrmFlags.NoEncryption) { this.Log(" --> Code section is not encrypted.", LogMessageType.Debug); return(true); } try { // Obtain the code section.. var codeSection = this.File.Sections[this.CodeSectionIndex]; this.Log($" --> {codeSection.SectionName} linked as main code section.", LogMessageType.Debug); this.Log($" --> {codeSection.SectionName} section is encrypted.", LogMessageType.Debug); if (codeSection.SizeOfRawData == 0) { this.Log($" --> {codeSection.SectionName} section is empty; skipping decryption.", LogMessageType.Debug); this.CodeSectionData = new byte[] { }; return(true); } // Obtain the code section data.. var codeSectionData = new byte[codeSection.SizeOfRawData + this.StubHeader.CodeSectionStolenData.Length]; Array.Copy(this.StubHeader.CodeSectionStolenData, (long)0, codeSectionData, 0, this.StubHeader.CodeSectionStolenData.Length); Array.Copy(this.File.FileData, (long)this.File.GetFileOffsetFromRva(codeSection.VirtualAddress), codeSectionData, this.StubHeader.CodeSectionStolenData.Length, codeSection.SizeOfRawData); // Create the AES decryption helper.. var aes = new AesHelper(this.StubHeader.AES_Key, this.StubHeader.AES_IV); aes.RebuildIv(this.StubHeader.AES_IV); // Decrypt the code section data.. var data = aes.Decrypt(codeSectionData, CipherMode.CBC, PaddingMode.None); if (data == null) { return(false); } // Set the code section override data.. this.CodeSectionData = data; return(true); } catch { this.Log(" --> Error trying to decrypt the files code section data!", LogMessageType.Error); return(false); } }
public async Task <IActionResult> Post([FromBody] RegistrationRequest request, [FromServices] IAuthenticationManager authentication, [FromServices] RemoteBillingService billingService, [FromServices] IEmailConfirmationService emailConfirmationService, [FromServices] ICryptoProviderService cryptoProvider) { try { var value = Convert.FromBase64String(request.InitCms); var xml = new UTF8Encoding(false).GetString(value); var encrypted = XmlSerializationHelper.DeserializeFromXml <string>(xml); var decrypted = AesHelper.Decrypt(encrypted); var isValid = await cryptoProvider.VerifyCMSAsync(xml, request.SignedCms); if (!isValid) { return(Json(ApiResponse.Failed(ApiErrorCode.ValidationError, "Сертификат не прошел проверку"))); } var signUpDateTime = new DateTime(Convert.ToInt64(decrypted)); if ((DateTime.Now - signUpDateTime).Hours > 0) { return(Json(ApiResponse.Failed(ApiErrorCode.AuthenticationFailed, "С момента начала авторизации прошло больше часа"))); } } catch { return(Json(ApiResponse.Failed(ApiErrorCode.AuthenticationFailed, "Сбой дешифрации сообщения"))); } await authentication.RegisterAsync(request, billingService); string code; long userId; if (!request.InvitedUser) { using (var repository = new Repository <User>(_provider)) { var user = repository.Get(x => x.UserName == request.UserAccount.Email).Single(); code = emailConfirmationService.GenerateEmailConfirmationToken(user); repository.Update(user); repository.Commit(); userId = user.Id; } var callbackUrl = Url.Action( "ConfirmEmail", "Registration", new { userId = userId, code = code }, protocol: HttpContext.Request.Scheme); callbackUrl = callbackUrl.Replace("api/Registration/ConfirmEmail", "auth/confirmemail"); emailConfirmationService.SendConfirmationUrl(request.UserAccount.Email, callbackUrl); } return(Json(ApiResponse.Success(true))); }
public string GetUserId(IRequest request) { //不支持 Session //var user = SessionHelper.Get<User>("User"); //if (user != null) // return user.UserID.ToString(); //else // return string.Empty; var cookie = request.Cookies["MsgKey"]; var id = AesHelper.Decrypt(cookie.Value, "56cargo.com"); return(id); }
private static void Method15() { string data = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; string key = Console.ReadLine(); if (key.IsMissing()) { key = AesHelper.GetRandomKey(); } Console.WriteLine($"key: {key}"); data = AesHelper.Encrypt(data, key, true); Console.WriteLine($"encode: {data}"); data = AesHelper.Decrypt(data, key, true); Console.WriteLine($"decode: {data}"); }
GetUserDetailsFromClaims( HttpContext context, ClaimsIdentity identity) { var caseflowReference = identity.FindFirst("caseflow_reference")?.Value; var encryption = context.RequestServices.GetRequiredService <EncryptionSetting>(); var reference = AesHelper.Decrypt(caseflowReference, encryption.AesKey, encryption.AesInitializationVector); var email = identity.FindFirst("email")?.Value; var userId = identity.FindFirst(Constants.CaseflowUserId)?.Value; return(reference, email, userId); }
/// <summary> /// Step #5 /// /// Read, decode, and process the main code section. /// </summary> /// <returns></returns> private bool Step5() { byte[] codeSectionData; // Obtain the main code section (typically .text).. var mainSection = this.File.GetOwnerSection(this.File.GetRvaFromVa(BitConverter.ToUInt32(this.PayloadData.Skip(this.SteamDrmpOffsets[3]).Take(4).ToArray(), 0))); if (mainSection.PointerToRawData == 0 || mainSection.SizeOfRawData == 0) { return(false); } // Save the code section for later use.. this.CodeSection = mainSection; // Determine if we are using encryption on the section.. var flags = BitConverter.ToUInt32(this.PayloadData.Skip(this.SteamDrmpOffsets[0]).Take(4).ToArray(), 0); if ((flags & (uint)DrmFlags.NoEncryption) == (uint)DrmFlags.NoEncryption) { // No encryption was used, just read the original data.. codeSectionData = new byte[mainSection.SizeOfRawData]; Array.Copy(this.File.FileData, this.File.GetFileOffsetFromRva(mainSection.VirtualAddress), codeSectionData, 0, mainSection.SizeOfRawData); } else { // Encryption was used, obtain the encryption information.. var aesKey = this.PayloadData.Skip(this.SteamDrmpOffsets[5]).Take(32).ToArray(); var aesIv = this.PayloadData.Skip(this.SteamDrmpOffsets[6]).Take(16).ToArray(); var codeStolen = this.PayloadData.Skip(this.SteamDrmpOffsets[7]).Take(16).ToArray(); // Restore the stolen data then read the rest of the section data.. codeSectionData = new byte[mainSection.SizeOfRawData + codeStolen.Length]; Array.Copy(codeStolen, 0, codeSectionData, 0, codeStolen.Length); Array.Copy(this.File.FileData, this.File.GetFileOffsetFromRva(mainSection.VirtualAddress), codeSectionData, codeStolen.Length, mainSection.SizeOfRawData); // Decrypt the code section.. var aes = new AesHelper(aesKey, aesIv); aes.RebuildIv(aesIv); codeSectionData = aes.Decrypt(codeSectionData, CipherMode.CBC, PaddingMode.None); } // Store the section data.. this.CodeSectionData = codeSectionData; return(true); }
public string EncryptSourceData(IAlipayRequest <T> request, string body, string encryptType, string encryptKey) { if (!"AES".Equals(encryptType)) { throw new AlipayException("API only support AES!"); } var item = ParseEncryptData(request, body); var bodyIndexContent = body.Substring(0, item.startIndex); var bodyEndexContent = body.Substring(item.endIndex); var bizContent = AesHelper.Decrypt(item.encryptContent, encryptKey); //var bizContent = AesHelper.Decrypt(item.encryptContent, encryptKey, AlipaySignature.AES_IV, CipherMode.CBC, PaddingMode.PKCS7); return(bodyIndexContent + bizContent + bodyEndexContent); }
public static string GetMac2(string asn, string cardTradeNo, int permoney, int tradeMoney, string tradeDate, string tradeTime, string termNo, string ranNum, string mac) { string mac2; if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["Mac2SocketServerHost"])) { mac2 = "FFFFFFFF"; } else { IPAddress ip = IPAddress.Parse(ConfigurationManager.AppSettings["Mac2SocketServerHost"]); IPEndPoint ipe = new IPEndPoint(ip, Convert.ToInt32(ConfigurationManager.AppSettings["Mac2SocketServerPort"])); Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { clientSocket.Connect(ipe); } catch (Exception) { throw new WeChatException("MAC2_ERROR", "生成MAC2失败"); } if (asn.Length > 16) { asn = asn.Right(16); } string permoney16X = permoney.ToString("x8"); string tradeMoney16X = tradeMoney.ToString("x8"); string sendStr = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}", "2061", "1", asn, cardTradeNo.PadLeft(6, '0'), permoney16X.PadLeft(8, '0'), tradeMoney16X.PadLeft(8, '0'), tradeDate, tradeTime, "02", termNo.PadLeft(12, '0'), ranNum.PadLeft(8, '0'), mac.PadLeft(8, '0'), "".PadLeft(64, '0')); byte[] sendBytes = Encoding.ASCII.GetBytes(AesHelper.Encrypt(sendStr)); clientSocket.Send(sendBytes); string recStr = ""; byte[] recBytes = new byte[4096]; int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0); recStr += Encoding.ASCII.GetString(recBytes, 0, bytes); recStr = AesHelper.Decrypt(recStr); if (string.IsNullOrEmpty(recStr) || recStr.Length < 79 || recStr.Substring(0, 4) != "0000") { throw new WeChatException("MAC2_ERROR", "生成MAC2失败:" + recStr); } mac2 = recStr.Substring(79, 8); clientSocket.Close(); } return(mac2); }
/// <summary> /// Step #4 /// /// Read, decode, and process the code section. /// </summary> /// <returns></returns> private bool Step4() { // Do nothing if we are not encrypted.. if ((this.StubHeader.Flags & (uint)DrmFlags.NoEncryption) == (uint)DrmFlags.NoEncryption) { return(true); } // Obtain the main code section that is encrypted.. var mainSection = this.File.GetOwnerSection(this.StubHeader.TextSectionVirtualAddress); if (mainSection.PointerToRawData == 0 || mainSection.SizeOfRawData == 0) { return(false); } // Save the code section for later use.. this.CodeSection = mainSection; try { // Obtain the .text section data.. var textSectionData = new byte[mainSection.SizeOfRawData + this.StubHeader.TextSectionStolenData.Length]; Array.Copy(this.StubHeader.TextSectionStolenData, 0, textSectionData, 0, this.StubHeader.TextSectionStolenData.Length); Array.Copy(this.File.FileData, this.File.GetFileOffsetFromRva(mainSection.VirtualAddress), textSectionData, this.StubHeader.TextSectionStolenData.Length, mainSection.SizeOfRawData); // Create the AES decryption class.. var aes = new AesHelper(this.StubHeader.AES_Key, this.StubHeader.AES_IV, CipherMode.ECB, PaddingMode.PKCS7); aes.RebuildIv(this.StubHeader.AES_IV); var data = aes.Decrypt(textSectionData, CipherMode.CBC, PaddingMode.None); if (data == null) { return(false); } // Set the override section data.. this.CodeSectionData = data; return(true); } catch { return(false); } }
public bool ValidateToken(string token, out string userName) { userName = ""; if (String.IsNullOrEmpty(token)) { return(false); } var configReader = new ConfigurationReader(); var tokenManager = new TokenManager(configReader); var decrypt = AesHelper.Decrypt(token); var userTokenData = JsonConvert.DeserializeObject <UserTokenData>(decrypt); var isValid = tokenManager.IsTokenExpired(userTokenData); if (isValid) { userName = StringCipher.Decrypt(userTokenData.CipherUserName, AuthConstants.Password); } return(isValid); }
public static IEnumerable <AccountProfileInfo> GetProfiles(string dbType) { IEnumerable <AccountProfileInfo> profiles = Enumerable.Empty <AccountProfileInfo>(); if (File.Exists(ProfilePath)) { profiles = ((IEnumerable <AccountProfileInfo>)JsonConvert.DeserializeObject(File.ReadAllText(ProfilePath), typeof(IEnumerable <AccountProfileInfo>))) .Where(item => (item.DatabaseType == dbType || string.IsNullOrEmpty(dbType))); foreach (var profile in profiles) { if (!profile.IntegratedSecurity && !string.IsNullOrEmpty(profile.Password)) { profile.Password = AesHelper.Decrypt(profile.Password); } } } return(profiles); }
public List <SteamAccount> LoadBasicAccounts() { if (encryptionType == Encryption.Basic) { try { byte[] encrypted = File.ReadAllBytes(this.directory + "accounts.ini"); string decrypted = GetString(AesHelper.Decrypt(encrypted, basicPassword)); List <SteamAccount> accountList = JsonConvert.DeserializeObject <List <SteamAccount> >(decrypted); return(accountList); } catch { throw new ApplicationException("mistaaake"); } } else { throw new ArgumentException("Unsupported Encryption type!"); } }
private static string GetConnStr() { string connectString = ConfigurationManager.ConnectionStrings["default"].ConnectionString; string[] strs = connectString.Split(';'); string pwd = string.Empty; for (int i = 0; i < strs.Length; i++) { if (strs[i].ToLower().Contains("password=")) { pwd = strs[i].Trim().Substring(9); break; } } string strBuilder = AesHelper.Decrypt(pwd); connectString = connectString.Replace(pwd, strBuilder.ToString(CultureInfo.InvariantCulture).Trim()); return(connectString); }
private string DecryptJson(string encryptedJson) { var jsonObject = JObject.Parse(encryptedJson); if (!jsonObject.ContainsKey(EncryptedPayloadPropertyName) || !jsonObject.ContainsKey(EncryptedPayloadKeyPropertyName)) { return(encryptedJson); } var encryptedPayloadKey = jsonObject[EncryptedPayloadKeyPropertyName].ToString(); var encryptedPayload = jsonObject[EncryptedPayloadPropertyName].ToString(); string decryptedKey; try { decryptedKey = DecryptDataOaepSha1(LoadCertificate(), encryptedPayloadKey); } catch (Exception e) { var logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.RollingFile("appsettingsdecrypt.log") .CreateLogger(); logger.Error(e, $"An error occurred while fetching AES key from cert. Switching from config. {e}."); decryptedKey = System.Configuration.ConfigurationManager.AppSettings["EncryptionKey"] ?? "UNKNOWN"; } var split = decryptedKey.Split(';'); var aesKey = split[0]; var aesIv = split[1]; return(AesHelper.Decrypt(encryptedPayload, aesKey, aesIv)); }
private static ConnectionInfo SelectConnectionInfo(XElement profileElement) { ConnectionInfo connectionInfo = null; if (profileElement != null) { connectionInfo = new ConnectionInfo(); connectionInfo.Server = profileElement.Element("Server")?.Value; connectionInfo.Port = profileElement.Element("Port")?.Value; connectionInfo.IntegratedSecurity = profileElement.Element("IntegratedSecurity")?.Value.ToString().ToLower() == "true"; connectionInfo.UserId = profileElement.Element("UserId")?.Value; string password = profileElement.Element("Password")?.Value; if (!string.IsNullOrEmpty(password)) { connectionInfo.Password = AesHelper.Decrypt(password); } connectionInfo.Database = profileElement.Element("Database")?.Value; } return(connectionInfo); }
/// <summary> /// Step #4 /// /// Read, decode, and process the code section. /// </summary> /// <returns></returns> private bool Step4() { // Do nothing if we are not encrypted.. if ((this.StubHeader.Flags & (uint)DrmFlags.NoEncryption) == (uint)DrmFlags.NoEncryption) return true; // Obtain the main code section that is encrypted.. var mainSection = this.File.GetOwnerSection(this.StubHeader.TextSectionVirtualAddress); if (mainSection.PointerToRawData == 0 || mainSection.SizeOfRawData == 0) return false; // Save the code section for later use.. this.CodeSection = mainSection; try { // Obtain the .text section data.. var textSectionData = new byte[mainSection.SizeOfRawData + this.StubHeader.TextSectionStolenData.Length]; Array.Copy(this.StubHeader.TextSectionStolenData, 0, textSectionData, 0, this.StubHeader.TextSectionStolenData.Length); Array.Copy(this.File.FileData, this.File.GetFileOffsetFromRva(mainSection.VirtualAddress), textSectionData, this.StubHeader.TextSectionStolenData.Length, mainSection.SizeOfRawData); // Create the AES decryption class.. var aes = new AesHelper(this.StubHeader.AES_Key, this.StubHeader.AES_IV, CipherMode.ECB, PaddingMode.PKCS7); aes.RebuildIv(this.StubHeader.AES_IV); var data = aes.Decrypt(textSectionData, CipherMode.CBC, PaddingMode.None); if (data == null) return false; // Set the override section data.. this.CodeSectionData = data; return true; } catch { return false; } }
/// <summary> /// Step #5 /// /// Read, decode, and process the main code section. /// </summary> /// <returns></returns> private bool Step5() { byte[] codeSectionData; // Obtain the main code section (typically .text).. var mainSection = this.File.GetOwnerSection(this.File.GetRvaFromVa(BitConverter.ToUInt32(this.PayloadData.Skip(this.SteamDrmpOffsets[3]).Take(4).ToArray(), 0))); if (mainSection.PointerToRawData == 0 || mainSection.SizeOfRawData == 0) return false; // Save the code section for later use.. this.CodeSection = mainSection; // Determine if we are using encryption on the section.. var flags = BitConverter.ToUInt32(this.PayloadData.Skip(this.SteamDrmpOffsets[0]).Take(4).ToArray(), 0); if ((flags & (uint)DrmFlags.NoEncryption) == (uint)DrmFlags.NoEncryption) { // No encryption was used, just read the original data.. codeSectionData = new byte[mainSection.SizeOfRawData]; Array.Copy(this.File.FileData, this.File.GetFileOffsetFromRva(mainSection.VirtualAddress), codeSectionData, 0, mainSection.SizeOfRawData); } else { // Encryption was used, obtain the encryption information.. var aesKey = this.PayloadData.Skip(this.SteamDrmpOffsets[5]).Take(32).ToArray(); var aesIv = this.PayloadData.Skip(this.SteamDrmpOffsets[6]).Take(16).ToArray(); var codeStolen = this.PayloadData.Skip(this.SteamDrmpOffsets[7]).Take(16).ToArray(); // Restore the stolen data then read the rest of the section data.. codeSectionData = new byte[mainSection.SizeOfRawData + codeStolen.Length]; Array.Copy(codeStolen, 0, codeSectionData, 0, codeStolen.Length); Array.Copy(this.File.FileData, this.File.GetFileOffsetFromRva(mainSection.VirtualAddress), codeSectionData, codeStolen.Length, mainSection.SizeOfRawData); // Decrypt the code section.. var aes = new AesHelper(aesKey, aesIv); aes.RebuildIv(aesIv); codeSectionData = aes.Decrypt(codeSectionData, CipherMode.CBC, PaddingMode.None); } // Store the section data.. this.CodeSectionData = codeSectionData; return true; }