민서네집

사용자 패스워드 암호화 본문

Spring

사용자 패스워드 암호화

브라이언7 2013. 11. 29. 14:20
		
		String password = (String) param.get("userPassword");

		// salt 생성
		java.util.Random random = new java.util.Random();
		byte[] saltBytes = new byte[8];
		random.nextBytes(saltBytes);

		StringBuffer salt = new StringBuffer();
		for (int i = 0; i < saltBytes.length; i++)
		{
			// byte 값을 Hex 값으로 바꾸기.
			salt.append(String.format("%02x",saltBytes[i]));
		}
		param.put("salt", salt.toString());

		// 사용자가 만든 Password와 랜덤으로 생성한 salt를 섞어서 SHA256 암호화를 한다.
		String encrypt = Sha256Util.getEncrypt(password, saltBytes);
		param.put("userPassword", encrypt);

package com.tistory.bryan7.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Sha256Util
{
	public static String getEncrypt(String source, byte[] salt)
	{
		String result = "";
		try
		{
			byte[] a = source.getBytes();
			byte[] bytes = new byte[a.length + salt.length];
			System.arraycopy(a, 0, bytes, 0, a.length);
			System.arraycopy(salt, 0, bytes, a.length, salt.length);

			MessageDigest md = MessageDigest.getInstance("SHA-256");
			md.update(bytes);

			byte[] byteData = md.digest();

			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < byteData.length; ++i)
			{
				sb.append(Integer.toString((byteData[i] & 0xFF) + 256, 16).substring(1));
			}

			result = sb.toString();
		} catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
		}

		return result;
	}
}


Spring Security 를 사용한다면 다음과 같이 간단히 할 수 있다.


Recommended approach

If you are using Spring Security 3.1, the recommended approach would be to go for bcrypt, this automatically generates a salt and concatenates it.


<beans:bean id='bCryptPasswordEncoder' class='org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder'/>

<authentication-manager>
  <authentication-provider user-service-ref="userDetailsService">
          <password-encoder ref="bCryptPasswordEncoder"/>
  </authentication-provider>
</authentication-manager>


You can generate the user password like this:

String password = "p4ssword";
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(password);


[출처] 

http://stackoverflow.com/questions/18653294/how-to-correctly-encode-password-using-shapasswordencoder


Storing a hashed password (Bcrypt) in a Database - type/length of column?


http://stackoverflow.com/questions/5881169/storing-a-hashed-password-bcrypt-in-a-database-type-length-of-column


Javascript SHA-256


http://www.webtoolkit.info/javascript-sha256.html#.UpbcfdJdUqg


자바 랜덤 함수(Java random)


http://h5bak.tistory.com/180


Hex to ASCII and ASCII to Hex in JAVA


http://jovialjava.blogspot.kr/2010/05/hex-to-ascii-conversion-in-java.html


Salted Password Hashing - Doing it Right


https://crackstation.net/hashing-security.htm


Comments