RSA는 공개키와 개인키를 사용하는 대표적인 비대칭 암호화 알고리즘입니다. 공개키로 암호화한 데이터는 개인키로만 복호화할 수 있으며, 반대의 경우도 가능합니다.
RSA 주요 특징
- 공개키와 개인키는 서로 독립적으로 생성되며 상호 변환 불가
- 암호화와 디지털 서명 기능 모두 제공
- 대칭키 암호화 방식보다 상대적으로 느림
Java RSA 구현 예제
키 생성 클래스
import java.security.*;
import java.util.HashMap;
import java.util.Map;
public class RSAKeyGenerator {
public static Map<String, Key> generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
Map<String, Key> keys = new HashMap<>();
keys.put("public", keyPair.getPublic());
keys.put("private", keyPair.getPrivate());
return keys;
}
}
암호화/복호화 처리 클래스
import javax.crypto.Cipher;
public class RSACrypto {
public static byte[] encrypt(byte[] data, Key key) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data);
}
public static byte[] decrypt(byte[] encrypted, Key key) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(encrypted);
}
}
실제 사용 예시
import org.junit.Test;
import static org.junit.Assert.*;
public class RSATest {
@Test
public void testEncryption() throws Exception {
Map<String, Key> keys = RSAKeyGenerator.generateKeyPair();
String original = "비밀 메시지";
byte[] encrypted = RSACrypto.encrypt(original.getBytes(), keys.get("public"));
byte[] decrypted = RSACrypto.decrypt(encrypted, keys.get("private"));
assertEquals(original, new String(decrypted));
}
}
RSA 활용 시나리오
- 공개키로 암호화 → 개인키로 복호화 (기밀성 보장)
- 개인키로 서명 → 공개키로 검증 (무결성 및 인증 보장)
주의사항
- RSA는 대량 데이터 암호화에 적합하지 않음
- 실제 구현 시 키 길이는 최소 2048비트 권장
- 키 관리가 보안의 핵심 요소