2016-06-14 79 views
0

我正在編寫使用RSA加密和解密文本的程序。 P,Q和E的值由用戶提供,並檢查它們是否爲素數。程序找到N和D.加密和解密出現故障。我已經看過這裏的一些問題,其中大部分都使用了庫,我不打算使用這些庫。加密代碼片段:Java中的RSA解密,未使用的RSA庫

JMenuItem mntmEncrypt = new JMenuItem("Encrypt"); 
mntmEncrypt.addActionListener(new ActionListener() { 
    @SuppressWarnings("null") 
    public void actionPerformed(ActionEvent ev) { 

     textArea_1.setText(""); 
     String blah = textArea.getText(); 
     int something; 

     for(int i=0; i<blah.length();i++){ 
      something =(int)(blah.charAt(i)); 

      enc = BigInteger.valueOf((long) (Math.pow(something, e)%n)); 

      textArea_1.append(blah.valueOf(enc) + " "); 
     } 

而且故障解密:

JMenuItem mntmDecrypt = new JMenuItem("Decrypt"); 
mntmDecrypt.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent em) { 
     textArea_1.setText(""); 
     String blah2 = textArea.getText(); 
     String[] somethingElse = blah2.split(" "); 
     char character; 
     for(int i=0;i<somethingElse.length;i++){ 
      int cipher = Integer.parseInt(somethingElse[i]);      

      dec = BigInteger.valueOf((long)Math.pow(cipher, d)%n); 

      System.out.println("Cipher: "+cipher); //print check 

      System.out.println("d: "+d); //print check 

      System.out.println("n: "+n); //print check 

      System.out.println("dec: "+dec); //print check 

      BigInteger x = BigInteger.valueOf(dec); 
      int x2 = x.intValue(); 
      char c = (char) x2; 

      System.out.println(cipher + " " + dec); 
      String textBack = new String(dec.toByteArray()); 

      textArea_1.append(String.valueOf(dec)); 
     } 
    } 
}); 

我使用this calculator檢查十進制的價值,這是完全錯誤的,但我不明白爲什麼。任何幫助,將不勝感激。除了enc和dec之外,我無法創建任何BigInteger。

回答

1

答案很簡單:您正在使用Math.pow

Math.pow工作在double值 - 因此它使用浮點數。浮點數從來不是確切的,因此你的結果已經在這一點上搞砸了。

如果你真的想手工計算RSA,你可以使用BigInteger.modPow(..)

但是,您的項目不是一個學習項目我強烈建議使用Java加密擴展。因此,請使用BigInteger值並創建一個RSAPrivateKeySpec/RSAPublicKeySpec並將它們與Cipher類一起使用。

例如見這個問題:Generating RSA keys for given modulus and exponent

+0

好了,但切換到BigInteger.modPow()將要求其參數都BigIntegers首先,對吧?無法投射=他們必須先是BigIntegers。這導致了很多問題,包括n =(p-1)(q-1)。從BigIntegers中減去一個是一個痛苦。我會如何去做這件事? 我寧願使用密碼擴展,但手工解決它是一個要求。 – Goblinette

+1

你明白了,你必須擁有BigInteger的一切 - 如果你的號碼不適合'long',每次計算。你可以很容易地減少:'value = value.subtract(BigInteger.ONE)' – Robert

+0

我試圖讓它工作,但因爲我使用for循環來檢查我有的數字是否爲素數還有更多的問題現在解決=(BigInteger有一個probablePrime方法,但不是一個CheckIfPrime方法 – Goblinette