Java에서 암호화를 하고 Javascript에서 복호화하는 방식
RsaPublic.java (DTO)
package com.coforward.egfwts.workspace.rsaModule.model;
import groovy.transform.ToString;
import groovy.transform.builder.Builder;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@ToString
@NoArgsConstructor // 기본 생성자
@AllArgsConstructor // 모든 필드를 포함하는 생성자
@Builder
public class RsaPublic {
private String modulusHex;
private String publicKeyModulus;
private String publicKeyExponent;
private String privateExponent;
}
RsaModuleService.java
package com.coforward.egfwts.workspace.rsaModule.service;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import com.coforward.egfwts.workspace.rsaModule.model.ResidNo;
import com.coforward.egfwts.workspace.rsaModule.model.RsaPublic;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
public interface RsaModuleService {
RsaPublic setRSAModule(HttpSession session) throws NoSuchAlgorithmException, InvalidKeySpecException;
String setEncData(String requestData, HttpSession session);
}
RsaModuleServiceImpl.java
package com.coforward.egfwts.workspace.rsaModule.service;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.coforward.egfwts.workspace.certification.controller.CertificationController;
import com.coforward.egfwts.workspace.rsaModule.model.ResidNo;
import com.coforward.egfwts.workspace.rsaModule.model.RsaPublic;
import com.coforward.egfwts.util.EncryptUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
@Service
@RequiredArgsConstructor
public class RsaModuleServiceImpl implements RsaModuleService {
private final Logger logger = LoggerFactory.getLogger(CertificationController.class);
@Override
public RsaPublic setRSAModule(HttpSession session) throws NoSuchAlgorithmException, InvalidKeySpecException {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024);
KeyPair keyPair = generator.genKeyPair();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
session.setAttribute("_RSA_PUBLIC_Key_", publicKey); //세션에 RSA 공개키를 세션에 저장한다.
session.setAttribute("_RSA_PRIVATE_Key_", privateKey); //세션에 RSA 개인키를 세션에 저장한다.
RSAPublicKeySpec publicSpec = (RSAPublicKeySpec) keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
String modulus = rsaPrivateKey.getModulus().toString(16);
String publicKeyModulus = publicSpec.getModulus().toString(16); // RSA 공개키
String publicKeyExponent = publicSpec.getPublicExponent().toString(16);
// 개인키 사양 추출
RSAPrivateKeySpec privateSpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);
String privateExponent = privateSpec.getPrivateExponent().toString(16);
RsaPublic rsaPublic = new RsaPublic();
rsaPublic.setModulusHex(modulus);
rsaPublic.setPublicKeyModulus(publicKeyModulus);
rsaPublic.setPublicKeyExponent(publicKeyExponent);
rsaPublic.setPrivateExponent(privateExponent);
return rsaPublic;
}
@Override
public String setEncData(String requestData, HttpSession session) {
PublicKey publicKey = (PublicKey) session.getAttribute("_RSA_PUBLIC_Key_");
return encryptRsa(publicKey, requestData);
}
private String encryptRsa(PublicKey publicKey, String plainText) {
String encryptedHex = "";
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
encryptedHex = byteToHex(encryptedBytes);
} catch(Exception e) {
logger.error("encryptRsa Exception Error", e);
}
return encryptedHex;
}
private String byteToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for(byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
test.java
public class test {
private final RsaModuleService rsaService;
@GetMapping("/RsaTest")
public String test(Model model, HttpSession session) {
RsaPublic rsaPublic = rsaService.setRSAModule(session);
returnData.put("resultCode", rsaService.setEncData(String.valueOf(returnCode), session));
returnData.put("publicKeyModulus", rsaPublic.getPublicKeyModulus());
returnData.put("publicKeyExponent", rsaPublic.getPublicKeyExponent());
returnData.put("privateExponent", rsaPublic.getPrivateExponent());
return "test";
}
}
test.html
<script type="text/javascript" src="/common/js/RSA/jsbn.js"></script>
<script type="text/javascript" src="/common/js/RSA/rsa.js"></script>
<script type="text/javascript" src="/common/js/RSA/prng4.js"></script>
<script type="text/javascript" src="/common/js/RSA/rng.js"></script>
<script type="text/javascript" src="/common/js/RSA/jsrsasign.js"></script>
<script>
function rsaDecrypts(data) {
var rsa = new RSAKey();
rsa.setPrivate($("#RSAModulus").val(), $("#RSAModulus").val(), $("#privateExponent").val());
return rsa.decrypt(data);
}
function ajax() {
.. ajax 코드 생략
const data = await response.json();
$('#RSAModulus').val(data.publicKeyModulus);
$('#publicExponent').val(data.publicKeyExponent);
$('#privateExponent').val(data.privateExponent);
const decrypt = await rsaDecrypts(data.resultCode);
if (decrypt == "200") {
// true
} else {
// false
}
}
</script>
<input type="hidden" id="RSAModulus" value="<%=publicKeyModulus%>" />
<input type="hidden" id="publicExponent" value="<%=publicKeyExponent %>" />
<input type="hidden" id="privateExponent" value="<%=privateExponent %>" />
jsbn.js
0.01MB
jsrsasign.js
0.32MB
prng4.js
0.00MB
rng.js
0.00MB
rsa.js
0.00MB
'java' 카테고리의 다른 글
| Java > C# UDP 통신 / 리틀엔디안(Little Endian)방식 (2) | 2023.08.21 |
|---|---|
| ByteBuffer 객체 생성 및 크기 용량 할당 (1) | 2023.08.11 |
| C# > Java UDP Server 인코딩 (0) | 2023.07.17 |
| 인텔리제이 + 스프링 프로젝트 생성(IntelliJ + Maven) (1) | 2022.08.17 |
| ajax 404에러 발생하는 경우 (2) | 2022.07.08 |