@Test
public void test() throws Exception {
// 서버 RSA 생성 및 클라이언트에 공개키 전달
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(KEY_SIZE);
KeyPair keyPair = generator.genKeyPair();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 비밀키
// session.setAttribute("__rsaPrivateKey__", privateKey);
RSAPublicKeySpec publicSpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
String publicKeyModulus = publicSpec.getModulus().toString(16);
String publicKeyExponent = publicSpec.getPublicExponent().toString(16);
// 공개키 정보
// System.out.println(publicKeyModulus);
// System.out.println(publicKeyExponent);
// client
// 공개키 만들기
RSAPublicKeySpec cPublicSpec = new RSAPublicKeySpec(new BigInteger(publicKeyModulus, 16), new BigInteger(publicKeyExponent, 16));
KeyFactory cKeyFactory = KeyFactory.getInstance("RSA");
PublicKey cPublicKey = cKeyFactory.generatePublic(cPublicSpec);
// 공개키 암호화
String password = "aaaa1111";
Cipher cCipher = Cipher.getInstance("RSA");
cCipher.init(Cipher.ENCRYPT_MODE, cPublicKey);
byte[] cArrCipherData = cCipher.doFinal(password.getBytes());
String strCipher = new String(Base64.encodeBase64(cArrCipherData));
// 서버 복호화
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] data = cipher.doFinal(Base64.decodeBase64(strCipher));
System.out.println(new String(data));
}
public byte[] hexToByteArray(String hex) {
if (hex == null || hex.length() % 2 != 0) {
return new byte[] {};
}
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < hex.length(); i += 2) {
byte value = (byte) Integer.parseInt(hex.substring(i, i + 2), 16);
bytes[(int) Math.floor(i / 2)] = value;
}
return bytes;
}
'dev > java' 카테고리의 다른 글
Java Virtual Threads 사용 시 synchronized 주의 (0) | 2024.06.04 |
---|---|
Virtual Threads (0) | 2024.06.02 |
자바 메모리 구조 (0) | 2010.08.26 |
Writing the MINA time server (0) | 2007.04.17 |
MINA Q&A (0) | 2007.04.15 |