728x90

한국방송통신대학교

암복호화 로직

1. 서버에서 RSA 키 생성 모듈 작성
2. 로그인 페이지 접속 시, 공개키/개인키를 생성하여 개인키는 저장하고 공개키는 클라이언트에게 전송
3. 클라이언트에서 자바스크립트 모듈을 사용하여 공개키로 암호화
4. 서버에서 개인키로 복호화




1-2. 키 생성 후, 클라이언트에게 전송

package java.security;

@RequestMapping(“/createKeyPair.do”)
public String createKeyPair(HttpServletRequest request, ModelMap model){

    //지정된 알고리즘에 대한 KeyPairGenerator를 작성
    KeyPairGenerator generator = KeyPairGenerator.getInstance(“RSA”);

    //임의의 열쇠의 사이즈에 대한 열쇠 페어 제네레이터를 초기화
    generator.initialize(2048);
    //열쇠 페어 생성
    KeyPair keyPair = generator. genKeyPair();

    KeyFactory keyFactory = KeyFactory.getInstance(“RSA”);

    //공개키
    PublicKey publicKey = keyPair.getPublic();
    //개인키
    PrivateKey privateKey = keyPair.getPrivate();
    //세션에 개인키 넣기
    request.getSession().setAttribute(“RsaPrivateKey”, privateKey);

    RSAPublicKeySpec publicSpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);

    model.put(“modulus”, publicSpec.getModulus().toString(16));
    model.put(“publicExponent”, publicSpec.getPublicExponent().toString(16));

    return “testView”;
}


3. 클라이언트 암호화

  • 암호화 라이브러리(.js) 추가
  • 암호화 함수 생성
function encryptParam(id, pw){
    let encryptInfo ={};

    let publicKey = GenerateKey();

    encryptInfo.encId = EncryptTEA(publicKey, id);
    encryptInfo.encPw = EncryptTEA(publicKey, pw);
    encryptInfo.secKey = EncryptRSA(“${modulus}”, “${publicExponent}”, publicKey);

    encryptInfo.publicKey = publicKey;

    return encryptInfo;
}


4. 서버 복호화

  1. 클라이언트가 서버로 넘긴 암호화 파라미터 추출
  2. 세션에 담은 개인키 추출
  3. 복호화
String id = decode(encId, secKey, RsaPrivateKey);
String pw = decode(encPw, secKey, RsaPrivateKey);
public static String decode(String encMsg, String teaKey, PrivateKey rsaKey){

    String decryptMsg = “”;

    String teaKey = decryptRsa(rsaKey, teaKey);
    TEA tea = new TEA(teaKey);

    decryptMsg = tea.decrypt(encMsg);

    return decryptMsg;
    }

    private static String decryptRsa(PrivateKey privateKey, String securedValue){

    Cipher cipher = Cipher.getInstance(“RSA”);

    byte[] encryptedBytes = hexToByteArray(securedValue);
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
    String decryptedValue = new String(decryptedBytes, “utf-8”);

    return decryptedValue;
}




728x90

+ Recent posts