Skip to content

Commit

Permalink
Eliminate temporary array.
Browse files Browse the repository at this point in the history
  • Loading branch information
bgrainger committed Jan 14, 2024
1 parent 71ef33a commit db551d4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
9 changes: 3 additions & 6 deletions src/MySqlConnector/Core/ServerSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -679,8 +679,7 @@ private async Task<PayloadData> SwitchAuthenticationAsync(ConnectionSettings cs,
}

// send the password as a NULL-terminated UTF-8 string
var passwordBytes = Encoding.UTF8.GetBytes(password);
Array.Resize(ref passwordBytes, passwordBytes.Length + 1);
var passwordBytes = AuthenticationUtility.GetNullTerminatedPasswordBytes(password);
payload = new(passwordBytes);
await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);
return await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
Expand Down Expand Up @@ -736,8 +735,7 @@ private async Task<PayloadData> SwitchAuthenticationAsync(ConnectionSettings cs,
private async Task<PayloadData> SendClearPasswordAsync(string password, IOBehavior ioBehavior, CancellationToken cancellationToken)
{
// add NUL terminator to password
var passwordBytes = Encoding.UTF8.GetBytes(password);
Array.Resize(ref passwordBytes, passwordBytes.Length + 1);
var passwordBytes = AuthenticationUtility.GetNullTerminatedPasswordBytes(password);

// send plaintext password
var payload = new PayloadData(passwordBytes);
Expand Down Expand Up @@ -780,8 +778,7 @@ private async Task<PayloadData> SendClearPasswordAsync(string password, IOBehavi
#endif

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

// XOR the password bytes with the challenge
AuthPluginData = Utility.TrimZeroByte(switchRequestData);
Expand Down
11 changes: 11 additions & 0 deletions src/MySqlConnector/Protocol/Serialization/AuthenticationUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ namespace MySqlConnector.Protocol.Serialization;

internal static class AuthenticationUtility
{
/// <summary>
/// Returns the UTF-8 bytes for <paramref name="password"/>, followed by a null byte.
/// </summary>
public static byte[] GetNullTerminatedPasswordBytes(string password)
{
var passwordByteCount = Encoding.UTF8.GetByteCount(password);
var passwordBytes = new byte[passwordByteCount + 1];
Encoding.UTF8.GetBytes(password.AsSpan(), passwordBytes);
return passwordBytes;
}

public static byte[] CreateAuthenticationResponse(ReadOnlySpan<byte> challenge, string password) =>
string.IsNullOrEmpty(password) ? [] : HashPassword(challenge, password);

Expand Down

0 comments on commit db551d4

Please sign in to comment.