단순 코드 기록/Spring

Spring_암호화와 복호화

일일일코_장민기 2024. 2. 24. 09:55
728x90
WEB-INF/lib에 저장

commons-codec-1.16.1.jar
0.35MB
local_policy.jar
0.01MB
US_export_policy.jar
0.01MB

 

porn.xml에 디펜던시 추가
<!--스프링시큐리티 web 라이브러리 -->
<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-web</artifactId>
	<version>5.1.2.RELEASE</version>
</dependency>
<!--스프링시큐리티 core 라이브러리 -->
<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-core</artifactId>
	<version>5.1.2.RELEASE</version>
</dependency>
<!--스프링시큐리티 config 라이브러리 -->
<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-config</artifactId>
	<version>5.1.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
	<groupId>commons-codec</groupId>
	<artifactId>commons-codec</artifactId>
	<version>1.16.1</version>
</dependency>

 

 

servlet-context.xml에 Bean 생성
<!-- 단방향 암호화 -->
<beans:bean id="bcryptPasswordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
 
<!-- 양방향 암호화 -->
<beans:bean id="AES256Util" class="com.controller.AES256Util">
	<beans:constructor-arg>
		<beans:value>1111111111111111</beans:value> <!-- 16자리로 제한 -->
	</beans:constructor-arg>
</beans:bean>

 

더보기

암호화 유틸(AES256Util.java)

package com.controller;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AES256Util {
	
	private String iv;
	private Key keySpec;

	/**
	 * 16자리의 키값을 입력하여 객체를 생성
	 * @param key 암/복호화를 위한 키값
	 * @throws UnsupportedEncodingException 키값의 길이가 16이하일 경우 발생
	 */
	
	public AES256Util(String key) throws UnsupportedEncodingException {
		this.iv = key.substring(0, 16);
		byte[] keyBytes = new byte[16];
		byte[] b = key.getBytes("UTF-8");	//throws 필요
		
		int len = b.length;
		if (len > keyBytes.length) {
			len = keyBytes.length;
		}

		System.arraycopy(b, 0, keyBytes, 0, len);
		SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); // 공통 키 생성
		this.keySpec = keySpec;
	}
	
	/**
	 * AES256 으로 암호화
	 * @param str 암호화할 문자열
	 * @throws NoSuchAlgorithmException
	 * @throws GeneralSecurityException
	 * @throws UnsupportedEncodingException
	 */
	public String encrypt(String str) throws NoSuchAlgorithmException, GeneralSecurityException, UnsupportedEncodingException {
		
		Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding"); // 암호화 패딩 기법 설정	//throws 필요
		c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes()));
		
		byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));
		String enStr = new String(Base64.encodeBase64(encrypted));
		return enStr;

	}

	/**
	 * AES256으로 암호화된 txt를 복호화
	 * @param str 복호화할 문자열
	 * @throws NoSuchAlgorithmException
	 * @throws GeneralSecurityException
	 * @throws UnsupportedEncodingException
	 */
	public String decrypt(String str) throws NoSuchAlgorithmException, GeneralSecurityException, UnsupportedEncodingException {
		Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
		c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes()));
		
		byte[] byteStr = Base64.decodeBase64(str.getBytes());
		return new String(c.doFinal(byteStr), "UTF-8");
	}
}

 

 

SecurityController
package com.controller;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class security {

	@Autowired
	private BCryptPasswordEncoder encoder; 
	
	@RequestMapping("/encodepassword")
	@ResponseBody
	public String bcript() {
		String str = "password";							//DB에 있는 비밀번호
		String encodingStr = encoder.encode(str);			//암호화 처리된 문자열로 리턴(로그인 할 때 비밀번호)
		Boolean result = encoder.matches(str, encodingStr);	//비밀번호 비교
		return "원래 비밀번호: " + str + "<br>--> 이런 식으로 바뀜: " + encodingStr + "<br>" + "str = encodingStr(2개가 같은 지 비교) --> " + result;
	}
	
	@Autowired
	private AES256Util aesutil;

	@ResponseBody
	@RequestMapping("/encodepassword2")
	public String bcript2() throws NoSuchAlgorithmException, UnsupportedEncodingException, GeneralSecurityException {
		
		String str = "jmk0605";								// 받아옴

		String encodingStr = aesutil.encrypt(str); 			// 암호화
		String decodingStr = aesutil.decrypt(encodingStr); // 복호화
		
		return str + " : " + encodingStr + " : " + decodingStr;		
	}
}

'단순 코드 기록 > Spring' 카테고리의 다른 글

Spring_myBatis_DML  (0) 2024.02.15
Spring_myBatis_selectAll  (0) 2024.02.15
Spring_myBatis  (0) 2024.02.15
Spring_RESTFul  (0) 2024.02.15
Spring_Context주소  (0) 2024.02.15