본문 바로가기

IT노트(구)/Java

간단한 자바 RSA 암호화 예제

간단한 자바 RSA 암호화 예제를 소개합니다.

외부 라이브러리 없이 순수 JDK로만 짜여진 소스입니다.(jar가 전혀 필요없음!)

직관적으로 이해할 수 있을 것입니다!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
 
import javax.crypto.Cipher;
 
public class TestRSA {
    public static void main(String[] args) {
        try {
            //공개키 및 개인키 생성
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            
            KeyPair keyPair = keyPairGenerator.genKeyPair();
            Key publicKey = keyPair.getPublic(); // 공개키
            Key privateKey = keyPair.getPrivate(); // 개인키
            
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec publicKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
            RSAPrivateKeySpec privateKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);
 
            //System.out.println("public key modulus(" + publicKeySpec.getModulus() + ") exponent(" + publicKeySpec.getPublicExponent() + ")");
            //System.out.println("private key modulus(" + privateKeySpec.getModulus() + ") exponent(" + privateKeySpec.getPrivateExponent() + ")");
 
            
            // 암호화(Encryption) 예제
            String inputStr = "세이프123"// "세이프123"을 암호화한다!
 
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] arrCipherData = cipher.doFinal(inputStr.getBytes()); // 암호화된 데이터(byte 배열)
            String strCipher = new String(arrCipherData);
            
            System.out.println(strCipher); // 암호화 결과물 출력(눈으로 보이기에는 깨질 수 있음)
 
            
            // 복호화(Decryption) 예제
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] arrData = cipher.doFinal(arrCipherData);
            String strResult = new String(arrData);
 
            System.out.println(strResult); // 복호화 결과물 출력(다시 "세이프123"이 출력됨)
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
cs