Skip to content

Commit db551d4

Browse files
committed
Eliminate temporary array.
1 parent 71ef33a commit db551d4

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

src/MySqlConnector/Core/ServerSession.cs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -679,8 +679,7 @@ private async Task<PayloadData> SwitchAuthenticationAsync(ConnectionSettings cs,
679679
}
680680

681681
// send the password as a NULL-terminated UTF-8 string
682-
var passwordBytes = Encoding.UTF8.GetBytes(password);
683-
Array.Resize(ref passwordBytes, passwordBytes.Length + 1);
682+
var passwordBytes = AuthenticationUtility.GetNullTerminatedPasswordBytes(password);
684683
payload = new(passwordBytes);
685684
await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);
686685
return await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
@@ -736,8 +735,7 @@ private async Task<PayloadData> SwitchAuthenticationAsync(ConnectionSettings cs,
736735
private async Task<PayloadData> SendClearPasswordAsync(string password, IOBehavior ioBehavior, CancellationToken cancellationToken)
737736
{
738737
// add NUL terminator to password
739-
var passwordBytes = Encoding.UTF8.GetBytes(password);
740-
Array.Resize(ref passwordBytes, passwordBytes.Length + 1);
738+
var passwordBytes = AuthenticationUtility.GetNullTerminatedPasswordBytes(password);
741739

742740
// send plaintext password
743741
var payload = new PayloadData(passwordBytes);
@@ -780,8 +778,7 @@ private async Task<PayloadData> SendEncryptedPasswordAsync(
780778
#endif
781779

782780
// add NUL terminator to password
783-
var passwordBytes = Encoding.UTF8.GetBytes(password);
784-
Array.Resize(ref passwordBytes, passwordBytes.Length + 1);
781+
var passwordBytes = AuthenticationUtility.GetNullTerminatedPasswordBytes(password);
785782

786783
// XOR the password bytes with the challenge
787784
AuthPluginData = Utility.TrimZeroByte(switchRequestData);

src/MySqlConnector/Protocol/Serialization/AuthenticationUtility.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,17 @@ namespace MySqlConnector.Protocol.Serialization;
99

1010
internal static class AuthenticationUtility
1111
{
12+
/// <summary>
13+
/// Returns the UTF-8 bytes for <paramref name="password"/>, followed by a null byte.
14+
/// </summary>
15+
public static byte[] GetNullTerminatedPasswordBytes(string password)
16+
{
17+
var passwordByteCount = Encoding.UTF8.GetByteCount(password);
18+
var passwordBytes = new byte[passwordByteCount + 1];
19+
Encoding.UTF8.GetBytes(password.AsSpan(), passwordBytes);
20+
return passwordBytes;
21+
}
22+
1223
public static byte[] CreateAuthenticationResponse(ReadOnlySpan<byte> challenge, string password) =>
1324
string.IsNullOrEmpty(password) ? [] : HashPassword(challenge, password);
1425

0 commit comments

Comments
 (0)