以前在hash 物件時, 通常會用到MD5 256 / 512 之類的機制進行. 而在新系統中, 則建議利用Argon2 進行hashing. 示範中會利用Password wrapper 做adapter 去將字串作hashing 又檢驗.
-
- 於build.gradle 中加入以下library.
dependencies { compile("org.springframework.security:spring-security-crypto") compile("de.mkammerer:argon2-jvm:2.4") }
- 建立Argo2PasswordEncoder.
import org.springframework.security.crypto.password.PasswordEncoder; import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; public class Argon2PasswordEncoder implements PasswordEncoder { private static final Argon2 ARGON2 = Argon2Factory.create(); private static final int ITERATIONS = 2; private static final int MEMORY= 65536; private static final int PARALLELISM = 1; @Override public String encode(CharSequence rawPassword) { final String hash = ARGON2.hash(ITERATIONS, MEMORY, PARALLELISM, rawPassword.toString()); return hash; } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return ARGON2.verify(encodedPassword, rawPassword.toString()); } }
- 進行測試.
public bool checkPassword(String plainPassword) { PasswordEncoder passwordEncoder=new Argon2PasswordEncoder(); String hashedPassword=passwordEncoder.encode(plainPassword); if(passwordEncoder.matches(plainPassword, hashedPassword)) { authenticationResult = true; } else { authenticationResult = false; } return authenticationResult; }
- 於build.gradle 中加入以下library.
Leave a Reply