@@ -162,7 +162,7 @@ public ISaslStep Transition(SaslConversation conversation, byte[] bytesReceivedF
162
162
var proof = "p=" + Convert . ToBase64String ( clientProof ) ;
163
163
var clientFinalMessage = clientFinalMessageWithoutProof + "," + proof ;
164
164
165
- return new ClientLast ( encoding . GetBytes ( clientFinalMessage ) , Convert . ToBase64String ( serverSignature ) ) ;
165
+ return new ClientLast ( encoding . GetBytes ( clientFinalMessage ) , serverSignature ) ;
166
166
}
167
167
168
168
private static byte [ ] XOR ( byte [ ] a , byte [ ] b )
@@ -204,9 +204,9 @@ private static byte[] HMAC(UTF8Encoding encoding, byte[] data, string key)
204
204
private class ClientLast : ISaslStep
205
205
{
206
206
private readonly byte [ ] _bytesToSendToServer ;
207
- private readonly string _serverSignature64 ;
207
+ private readonly byte [ ] _serverSignature64 ;
208
208
209
- public ClientLast ( byte [ ] bytesToSendToServer , string serverSignature64 )
209
+ public ClientLast ( byte [ ] bytesToSendToServer , byte [ ] serverSignature64 )
210
210
{
211
211
_bytesToSendToServer = bytesToSendToServer ;
212
212
_serverSignature64 = serverSignature64 ;
@@ -226,16 +226,26 @@ public ISaslStep Transition(SaslConversation conversation, byte[] bytesReceivedF
226
226
{
227
227
var encoding = Utf8Encodings . Strict ;
228
228
var map = NVParser . Parse ( encoding . GetString ( bytesReceivedFromServer ) ) ;
229
+ var serverSignature = Convert . FromBase64String ( map [ 'v' ] ) ;
229
230
230
- var serverSignature = map [ 'v' ] ;
231
-
232
- if ( _serverSignature64 != serverSignature )
231
+ if ( ! ConstantTimeEquals ( _serverSignature64 , serverSignature ) )
233
232
{
234
233
throw new MongoAuthenticationException ( conversation . ConnectionId , message : "Server signature was invalid." ) ;
235
234
}
236
235
237
236
return new CompletedStep ( ) ;
238
237
}
238
+
239
+ private bool ConstantTimeEquals ( byte [ ] a , byte [ ] b )
240
+ {
241
+ var diff = a . Length ^ b . Length ;
242
+ for ( var i = 0 ; i < a . Length && i < b . Length ; i ++ )
243
+ {
244
+ diff |= a [ i ] ^ b [ i ] ;
245
+ }
246
+
247
+ return diff == 0 ;
248
+ }
239
249
}
240
250
241
251
private class NVParser
0 commit comments