2011-01-09 7 views
1

이것은 단순히 재미를위한 것입니다. 이것은 실제 암호화에 사용되지 않습니다. 나는 1 학년 comp sci 학생이고 사랑의 암호 법입니다.간단한 RSA 암호화 (자바)

작업하는 데 오랜 시간이 걸렸습니다. 대략 N = 18에서, 그것은 분해되기 시작합니다. 그 이후에는 메시지를 제대로 암호화하지 않습니다. 이유가 확실하지 않습니다. 어떤 통찰력? 또한 자습서 나 암호화에 대한 흥미로운 자료를 제공 할 수있는 링크를 제공해 주시면 감사하겠습니다.

import java.math.BigInteger; 
import java.security.SecureRandom; 

/** 
* Cryptography. 
* 
* Generates public and private keys used in encryption and 
* decryption 
* 
*/ 
public class RSA 
{ 
    private final static BigInteger one = new BigInteger("1"); 
    private final static SecureRandom random = new SecureRandom(); 

    // prime numbers 
    private BigInteger p; 
    private BigInteger q; 

    // modulus 
    private BigInteger n; 

    // totient 
    private BigInteger t; 

    // public key 
    private BigInteger e; 

    // private key 
    private BigInteger d; 

    private String cipherText; 

    /** 
    * Constructor for objects of class RSA 
    */ 
    public RSA(int N) 
    { 
     p = BigInteger.probablePrime(N/2, random); 
     q = BigInteger.probablePrime(N/2, random); 

     // initialising modulus 
     n = p.multiply(q); 

     // initialising t by euclid's totient function (p-1)(q-1) 
     t = (p.subtract(one)).multiply(q.subtract(one)); 

     // initialising public key ~ 65537 is common public key 
     e = new BigInteger("65537"); 
    } 

    public int generatePrivateKey() 
    { 
     d = e.modInverse(t); 
     return d.intValue(); 
    } 

    public String encrypt(String plainText) 
    { 
     String encrypted = ""; 
     int j = 0; 
     for(int i = 0; i < plainText.length(); i++){ 
      char m = plainText.charAt(i); 
      BigInteger bi1 = BigInteger.valueOf(m); 
      BigInteger bi2 = bi1.modPow(e, n); 
      j = bi2.intValue(); 
      m = (char) j; 
      encrypted += m; 
     } 
     cipherText = encrypted; 
     return encrypted; 
    } 

    public String decrypt() 
    { 
     String decrypted = ""; 
     int j = 0; 
     for(int i = 0; i < cipherText.length(); i++){ 
      char c = cipherText.charAt(i); 
      BigInteger bi1 = BigInteger.valueOf(c); 
      BigInteger bi2 = bi1.modPow(d, n); 
      j = bi2.intValue(); 
      c = (char) j; 
      decrypted += c; 
     } 
     return decrypted; 
    } 
} 
+0

메시지가 "적절하게"암호화되지 않고 N <18 or N>과 함께 작동하는지 여부에 따라 "깨뜨림"이 의미하는 바를 구체적으로 표현해야합니다. 또한 ECB 모드에서 RSA를 사용하고 있습니다 반면에 하이브리드 방식을 사용해야합니다. – crazyscot

+0

아, 그리고 읽을 텍스트 - Schneier, Ferguson 및 Kohno의 암호화 공학. – crazyscot

+0

암호화는 작동하지만 암호 해독은 N> 18이 아닙니다. 독서 제안에 감사 드리며, 나는 도서관에서 최대한 빨리 가져올 것입니다! –

답변

2

2^16 개의 다른 메시지 만 있기 때문에 암호화가 자주 끊어 질 수 있습니다. RSA는 올바른 패딩 (OEP)이 사용되는 경우에만 안전합니다. 물론 하나의 문자를 하나의 RSA 블록에 매핑하기 때문에 cyphertext는 일반 텍스트의 100 배의 공간을 차지합니다.

j = bi2.intValue(); 
m = (char) j; 

위의 두 가지 작동은 끔찍하게 오버플로됩니다. bi2는 BigInteger입니다. 그냥 32 비트 정수/16 비트 char 적합하지 않습니다. 정수를 잘라내는 것은 대부분의 비트를 잃어 버리기 때문에 암호문을 손상 시켰기 때문에 암호 해독이 작동하지 않습니다.

+0

아, 그건 많은 의미가 있습니다. 감사. 올바른 패딩을 읽을 것입니다. 나는 배울 것이 많다. –