From e216227429c48f84175183a23addeef559d6343e Mon Sep 17 00:00:00 2001 From: Mino Date: Sat, 28 Mar 2020 10:49:21 +0900 Subject: [PATCH] Allocate the buffer at once --- .../SqexArg/EncryptedArgumentExtensions.cs | 36 ++++++++++++------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/Dalamud.Bootstrap/SqexArg/EncryptedArgumentExtensions.cs b/Dalamud.Bootstrap/SqexArg/EncryptedArgumentExtensions.cs index 1876752dc..20c415bc1 100644 --- a/Dalamud.Bootstrap/SqexArg/EncryptedArgumentExtensions.cs +++ b/Dalamud.Bootstrap/SqexArg/EncryptedArgumentExtensions.cs @@ -1,20 +1,25 @@ using System; using System.Buffers; using System.Buffers.Text; +using System.Text; using Dalamud.Bootstrap.Crypto; namespace Dalamud.Bootstrap.SqexArg { internal static class EncryptedArgumentExtensions { - public static void Decrypt(this EncryptedArgument argument, uint key) + public static string Decrypt(this EncryptedArgument argument, uint key) { Span keyBytes = stackalloc byte[8]; CreateKey(key, keyBytes); + var encryptedData = DecodeDataString(argument.Data, out var encryptedDataLength); + var decryptedData = new byte[encryptedData.Length]; + var blowfish = new Blowfish(keyBytes); - - + blowfish.Decrypt(encryptedData, decryptedData); + + return Encoding.UTF8.GetString(decryptedData[..encryptedDataLength]); } /// @@ -31,24 +36,30 @@ namespace Dalamud.Bootstrap.SqexArg } /// - /// Converts the url-safe variant of base64 string to bytes. + /// Converts the data string to bytes. It also allocates more bytes than actual data contained in base64 string for Blowfish. /// /// A url-safe variant of base64 string. - private static byte[] DecodeUrlSafeBase64(string payload) + /// A data length that is actually written to the buffer. + private static byte[] DecodeDataString(string payload, out int dataLength) { var base64Str = payload .Replace('-', '+') .Replace('_', '/'); - try + // base64: 3 bytes per 4 characters + dataLength = (payload.Length / 4) * 3; + + // round to next mutliple of block size which is what Blowfish can process. (i.e. 8 bytes) + var alignedLength = (dataLength + (Blowfish.BlockSize - 1)) & (-Blowfish.BlockSize); + + var buffer = new byte[alignedLength]; + + if (!Convert.TryFromBase64String(base64Str, buffer, out var _)) { - return Convert.FromBase64String(base64Str); - } - catch (FormatException ex) - { - // This is expected to happen if the argument is ill-formed - throw new SqexArgException($"A payload {payload} does not look like a valid encrypted argument.", ex); + throw new SqexArgException($"A payload {payload} does not look like a valid encrypted argument."); } + + return buffer; } private static string EncodeUrlSafeBase64(byte[] payload) @@ -58,7 +69,6 @@ namespace Dalamud.Bootstrap.SqexArg return payloadStr .Replace('+', '-') .Replace('/', '_'); - } } }