2014-06-17 77 views
4

理論上我知道,如果n=33e(public key)=3d(private key)=7我可以用BigIntegermodPow(e, n)加密plaintext,並與modPow(d,n)解密正常工作,但解密後plaintext是不一樣的第一。RSA算法的實現不是在java中

這裏是我的代碼:

public class KeyTest { 
private BigInteger n = new BigInteger("33"); 
private BigInteger e = new BigInteger("3"); 
private BigInteger d = new BigInteger("7"); 

public static void main(String[] args) { 
    KeyTest test = new KeyTest(); 

    BigInteger plaintext = new BigInteger("55"); 
    System.out.println("Plain text: " + plaintext); 

    BigInteger ciphertext = test.encrypt(plaintext); 
    System.out.println("Ciphertext: " + ciphertext); 

    BigInteger decrypted = test.decrypt(ciphertext); 
    System.out.println("Plain text after decryption: " + decrypted); 
} 

public BigInteger encrypt(BigInteger plaintext) { 

    return plaintext.modPow(e, n); 
} 

public BigInteger decrypt(BigInteger ciphertext) { 

    return ciphertext.modPow(d, n); 
} 
} 

輸出是:

Plain text: 55 Ciphertext: 22 Plain text after decryption: 22 
+2

你的 「明文= 55」 是大於 「模數= N = 33」,所以什麼是真正獲取加密是22號(55模33)。也就是這樣,那麼22在模數33下加密再次是22. –

+0

該算法應該是(pow(明文,pubKey)mod n),第一個操作應該是pow,然後mod操作是我不正確? –

回答

3

你的明文(55)比模量(33)大,所以你不能真正加密信息。考慮下面的稍微不同的實施例:

  • p = 11
  • q = 17
  • n = 187
  • phi(n) = 160
  • 選擇e = 3
  • 如果d = 107然後e * d = 321 = 1 mod phi(n)

所以你的代碼更改爲:

private BigInteger n = new BigInteger("187"); 
    private BigInteger e = new BigInteger("3"); 
    private BigInteger d = new BigInteger("107"); 

    public static void main(String[] args) { 
    KeyTest test = new KeyTest(); 

    BigInteger plaintext = new BigInteger("55"); 
    System.out.println("Plain text: " + plaintext); 

    BigInteger ciphertext = test.encrypt(plaintext); 
    System.out.println("Ciphertext: " + ciphertext); 

    BigInteger decrypted = test.decrypt(ciphertext); 
    System.out.println("Plain text after decryption: " + decrypted); 
    } 

    public BigInteger encrypt(BigInteger plaintext) { 

    return plaintext.modPow(e, n); 
    } 

    public BigInteger decrypt(BigInteger ciphertext) { 

    return ciphertext.modPow(d, n); 
    } 
} 

輸出:

Plain text: 55 
Ciphertext: 132 
Plain text after decryption: 55 
+2

我現在明白了爲什麼在我的代碼解密後,我得到了「錯誤的」答案,因爲在mod 33操作之後,不可能計算比33更大的數字。 –