Polish Pbkdf2PasswordEncoder

Issue gh-3930
This commit is contained in:
Rob Winch 2016-06-21 11:40:01 -05:00
parent 5f658b3ffc
commit 8f880aea0e
2 changed files with 28 additions and 7 deletions

View File

@ -89,7 +89,7 @@ public class Pbkdf2PasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
byte[] salt = this.saltGenerator.generateKey();
byte[] encoded = encodeAndConcatenate(rawPassword, salt);
byte[] encoded = encode(rawPassword, salt);
return String.valueOf(Hex.encode(encoded));
}
@ -97,11 +97,7 @@ public class Pbkdf2PasswordEncoder implements PasswordEncoder {
public boolean matches(CharSequence rawPassword, String encodedPassword) {
byte[] digested = Hex.decode(encodedPassword);
byte[] salt = subArray(digested, 0, this.saltGenerator.getKeyLength());
return matches(digested, encodeAndConcatenate(rawPassword, salt));
}
private byte[] encodeAndConcatenate(CharSequence rawPassword, byte[] salt) {
return encode(rawPassword, salt);
return matches(digested, encode(rawPassword, salt));
}
/**
@ -130,4 +126,4 @@ public class Pbkdf2PasswordEncoder implements PasswordEncoder {
throw new IllegalStateException("Could not create hash", e);
}
}
}
}

View File

@ -15,8 +15,13 @@
*/
package org.springframework.security.crypto.password;
import java.util.Arrays;
import org.junit.Test;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.keygen.KeyGenerators;
import static org.assertj.core.api.Assertions.assertThat;
public class Pbkdf2PasswordEncoderTests {
@ -50,6 +55,26 @@ public class Pbkdf2PasswordEncoderTests {
assertThat(encodeFirst).isNotEqualTo(encodeSecond);
}
@Test
public void passivity() {
String encodedPassword = "ab1146a8458d4ce4e65789e5a3f60e423373cfa10b01abd23739e5ae2fdc37f8e9ede4ae6da65264";
String rawPassword = "password";
assertThat(this.encoder.matches(rawPassword, encodedPassword)).isTrue();
}
@Test
public void migrate() {
final int saltLength = KeyGenerators.secureRandom().getKeyLength();
String encodedPassword = "ab1146a8458d4ce4e65789e5a3f60e423373cfa10b01abd23739e5ae2fdc37f8e9ede4ae6da65264";
String originalEncodedPassword = "ab1146a8458d4ce4ab1146a8458d4ce4e65789e5a3f60e423373cfa10b01abd23739e5ae2fdc37f8e9ede4ae6da65264";
byte[] originalBytes = Hex.decode(originalEncodedPassword);
byte[] fixedBytes = Arrays.copyOfRange(originalBytes, saltLength,
originalBytes.length);
String fixedHex = String.valueOf(Hex.encode(fixedBytes));
assertThat(fixedHex).isEqualTo(encodedPassword);
}
/**
* Used to find the iteration count that takes .5 seconds.
*/