2011-01-09 20 views
1

これは単に楽しいです。これは実際の暗号化には使用されません。私は初年度のcomp sciの学生と愛の暗号です。シンプルなRSA暗号化(Java)

これには時間がかかりました。約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> 18で動作するかどうかをさらに細分する必要があります。また、ECBモードではRSAを使用していますあなたはハイブリッドスキームを使用しなければなりません。 – crazyscot

+0

ああ、テキストの読み方 - Schneier、Ferguson、Kohnoの暗号化エンジニアリング。 – crazyscot

+0

暗号化は機能しますが、復号化にN> 18は必要ありません。読書のおかげで、ライブラリからすぐに入手できます! –

答えて

2

2^16種類のメッセージしかないため、暗号化が壊れている可能性があります。 RSAは、正しいパディング(OEP)が使用されている場合にのみ安全です。もちろん、1つの文字を1つのRSAブロックにマッピングするので、cyphertextは平文の100倍のスペースを必要とします。

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

これらの操作の両方がひどくオーバーフローします。 bi2はBigIntegerです。 32ビットの整数/ 16ビットのcharには適合しません。整数を切り捨てるとほとんどのビットが失われるため、暗号文を破損したため復号化が機能しません。

+0

ああ、それはたくさんの意味があります。ありがとう。正しいパディングを読み上げます。私は学ぶべきことがたくさんある。 –