Java 中的 RSA 解密,未使用 RSA 库

RSA decryption in Java, RSA libraries not used

我正在编写一个程序来使用 RSA 加密和解密文本。 P、Q 和 E 的值由用户提供并检查它们是否为素数。程序找到N和D,加密和解密都出错了。我已经查看了这里的一些问题,其中大多数问题都使用了我不打算在本次作业中使用的库。加密代码片段:

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 检查了 dec 的值,这是完全错误的,但我不明白为什么。任何帮助,将不胜感激。除了 enc 和 dec,我不能做任何 BigInteger。

答案很简单:您正在使用 Math.pow

Math.pow 适用于 double 值 - 因此它使用浮点数。浮点数从来都不是精确的,因此你的结果在那个时候已经搞砸了。

如果您真的想手动计算 RSA,可以使用 BigInteger.modPow(..)

但是您的项目不是学习项目,我强烈建议您使用 Java 密码学扩展。因此,使用 BigInteger 值并创建一个 RSAPrivateKeySpec/RSAPublicKeySpec 并将它们与 Cipher class.

一起使用

例如这个问题:Generating RSA keys for given modulus and exponent