@@ -177,7 +177,7 @@ public ISaslStep Transition(SaslConversation conversation, byte[] bytesReceivedF
177
177
var proof = "p=" + Convert . ToBase64String ( clientProof ) ;
178
178
var clientFinalMessage = clientFinalMessageWithoutProof + "," + proof ;
179
179
180
- return new ClientLast ( encoding . GetBytes ( clientFinalMessage ) , Convert . ToBase64String ( serverSignature ) ) ;
180
+ return new ClientLast ( encoding . GetBytes ( clientFinalMessage ) , serverSignature ) ;
181
181
}
182
182
183
183
private static byte [ ] XOR ( byte [ ] a , byte [ ] b )
@@ -219,9 +219,9 @@ private static byte[] HMAC(UTF8Encoding encoding, byte[] data, string key)
219
219
private class ClientLast : ISaslStep
220
220
{
221
221
private readonly byte [ ] _bytesToSendToServer ;
222
- private readonly string _serverSignature64 ;
222
+ private readonly byte [ ] _serverSignature64 ;
223
223
224
- public ClientLast ( byte [ ] bytesToSendToServer , string serverSignature64 )
224
+ public ClientLast ( byte [ ] bytesToSendToServer , byte [ ] serverSignature64 )
225
225
{
226
226
_bytesToSendToServer = bytesToSendToServer ;
227
227
_serverSignature64 = serverSignature64 ;
@@ -241,16 +241,26 @@ public ISaslStep Transition(SaslConversation conversation, byte[] bytesReceivedF
241
241
{
242
242
var encoding = Utf8Encodings . Strict ;
243
243
var map = NVParser . Parse ( encoding . GetString ( bytesReceivedFromServer ) ) ;
244
+ var serverSignature = Convert . FromBase64String ( map [ 'v' ] ) ;
244
245
245
- var serverSignature = map [ 'v' ] ;
246
-
247
- if ( _serverSignature64 != serverSignature )
246
+ if ( ! ConstantTimeEquals ( _serverSignature64 , serverSignature ) )
248
247
{
249
248
throw new MongoAuthenticationException ( conversation . ConnectionId , message : "Server signature was invalid." ) ;
250
249
}
251
250
252
251
return new CompletedStep ( ) ;
253
252
}
253
+
254
+ private bool ConstantTimeEquals ( byte [ ] a , byte [ ] b )
255
+ {
256
+ var diff = a . Length ^ b . Length ;
257
+ for ( var i = 0 ; i < a . Length && i < b . Length ; i ++ )
258
+ {
259
+ diff |= a [ i ] ^ b [ i ] ;
260
+ }
261
+
262
+ return diff == 0 ;
263
+ }
254
264
}
255
265
256
266
private class NVParser
0 commit comments