[Java] 整合Argon2 到Spring Boot

以前在hash 物件時, 通常會用到MD5 256 / 512 之類的機制進行. 而在新系統中, 則建議利用Argon2 進行hashing. 示範中會利用Password wrapper 做adapter 去將字串作hashing 又檢驗.

    1. 於build.gradle 中加入以下library.
      dependencies {
         compile("org.springframework.security:spring-security-crypto")
         compile("de.mkammerer:argon2-jvm:2.4")
      }
    2. 建立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());
      	}
      }
      
    3. 進行測試.
      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;
      }

       

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.