JAVA RSA 암호화 프로그램 예제 (BigInteger 이용)

황제낙엽 2007.09.08 01:26 조회 수 : 257 추천:105

sitelink1  
sitelink2  
sitelink3 http://1 
sitelink4 http://ko 
extra_vars5 http://blog.naver.com/safinfo?Redirect=Log&logNo=10018946130 
extra_vars6 sitelink1 
자바의 BigInteger 클래스를 이용하여 RSA 로직을 구현하였다.
클래스를 생성하여 콘솔에 출려하면 Public키와 Private키가 출력되고
이를 이용하여 encrypt, decrypt 를 수행 가능하다.
·미리보기 | 소스복사·
  1. import java.math.BigInteger;   
  2. import java.security.SecureRandom;   
  3.        
  4.   
  5. public class RSA {   
  6.    private final static BigInteger one      = new BigInteger("1");   
  7.    private final static SecureRandom random = new SecureRandom();   
  8.   
  9.    private BigInteger privateKey;   
  10.    private BigInteger publicKey;   
  11.    private BigInteger modulus;   
  12.   
  13.    // generate an N-bit (roughly) public and private key   
  14.    RSA(int N) {   
  15.       BigInteger p = BigInteger.probablePrime(N/2, random);   
  16.       BigInteger q = BigInteger.probablePrime(N/2, random);   
  17.       BigInteger phi = (p.subtract(one)).multiply(q.subtract(one));   
  18.   
  19.       modulus    = p.multiply(q);                                     
  20.       publicKey  = new BigInteger("65537");     // common value in practice = 2^16 + 1   
  21.       privateKey = publicKey.modInverse(phi);   
  22.    }   
  23.   
  24.   
  25.    BigInteger encrypt(BigInteger message) {   
  26.       return message.modPow(publicKey, modulus);   
  27.    }   
  28.   
  29.    BigInteger decrypt(BigInteger encrypted) {   
  30.       return encrypted.modPow(privateKey, modulus);   
  31.    }   
  32.   
  33.    public String toString() {   
  34.       String s = "";   
  35.       s += "public  = " + publicKey  + "n";   
  36.       s += "private = " + privateKey + "n";   
  37.       s += "modulus = " + modulus;   
  38.       return s;   
  39.    }   
  40.     
  41.    public static void main(String[] args) {   
  42.       int N = Integer.parseInt(args[0]);   
  43.       RSA key = new RSA(N);   
  44.       System.out.println(key);   
  45.     
  46.       // create random message, encrypt and decrypt   
  47.       BigInteger message = new BigInteger(N-1, random);   
  48.   
  49.       //// create message by converting string to integer   
  50.       // String s = "test";   
  51.       // byte[] bytes = s.getBytes();   
  52.       // BigInteger message = new BigInteger(s);   
  53.   
  54.       BigInteger encrypt = key.encrypt(message);   
  55.       BigInteger decrypt = key.decrypt(encrypt);   
  56.       System.out.println("message   = " + message);   
  57.       System.out.println("encrpyted = " + encrypt);   
  58.       System.out.println("decrypted = " + decrypt);   
  59.    }   
  60. }