java - 使用 BigInteger 实现的 RSA 算法没有得到正确的输出

标签 java algorithm encryption rsa

我是编程和网络安全方面的新手。我正在尝试为我的类作业实现 RSA 算法,但我没有得到正确的输出,所以请帮助我,它在解密时没有给出相同的纯文本。

以下是我的代码

import java.security.*;
import java.lang.*;
import java.math.*;

public class RSAalgo
{
    BigInteger p,q,n,d,e,ph,t;
    SecureRandom r;

    public RSAalgo()
    {
        r=new SecureRandom();
        p=new BigInteger(512,100,r);
        q=new BigInteger(512,100,r);

        System.out.println("\n RSA ALGO");
        System.out.println("\n Prime No P : "+p.intValue());
        System.out.println("\n Prime no Q : "+q.intValue());

        n=p.multiply(q);
        ph=(p.subtract(new BigInteger("1")));

        e = new BigInteger("2");

        while((ph.gcd(e).intValue()>1)||(e.compareTo(ph)!=-1))
        e=e.add(new BigInteger("1"));

        d=e.modInverse(ph);

        System.out.println("public key = "+n.intValue()+", "+e.intValue());
        System.out.println("Private key = "+n.intValue()+", "+d.intValue());

        BigInteger msg=new BigInteger("21");        
        System.out.println("Message is "+msg);

        BigInteger enmsg=encrypt(msg,e,n);      
        System.out.println("Encrypted message is "+enmsg.intValue());

        BigInteger demsg=decrypt(enmsg,d,n);
        System.out.println("Decrypted message is "+demsg.intValue());

    }

    BigInteger encrypt(BigInteger msg,BigInteger e, BigInteger n)
    {
        return msg.modPow(e,n);
    }

    BigInteger decrypt(BigInteger msg,BigInteger d, BigInteger n)
    {
        return msg.modPow(d,n);
    }


    public static void main(String args[])
    {
        new RSAalgo();
    }
}

输入:21

每次加密的消息和解密的消息都是随机的

最佳答案

您的 phi 计算不正确。它必须是 phi = (p - 1)x(q - 1),但实际上是 phi = (p - 1)。你忘了乘以一个附加项。或者换句话说:

ph = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));

请参阅关于 RSA 的维基百科文章.


其他注意事项:

Unpadded(教科书)RSA 是不安全的。您需要实现安全填充,例如 OAEP。

RSA 本身只能加密在数值上小于模数的东西。如果您的明文较大(不要忘记填充),那么您需要 hybrid encryption .

关于java - 使用 BigInteger 实现的 RSA 算法没有得到正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39165521/

相关文章:

java - postman 表单数据发送带有文件的复杂对象

algorithm - 证明和反驳 BigO

algorithm - 组合优化

objective-c - 在 Cocoa 中使用 CFSocket/CFStream 时如何设置 SSL 密码?

java - 使用 JAVA 使用 AES 加密大文件

java - 如何加载文件并将其保存在 Android 的对象列表中?

java - 使用 Java 映射访问模式在 Mongo 中进行不同查询

Java OpenCV - 缺少 org.opencv.core.Core rectangle() 方法

algorithm - 如何找到多面体的边和面?

c - GNU GMP 库的 Cramer-Shoup 加密方案实现失败