简体   繁体   English

如何在Java中实现RSA加密和解密

[英]How to implement RSA encrypt and decrypt in Java

I have the public and private key generation working. 我有公钥和私钥生成工作。 My next step is to create 2 more methods - encrypt and decrypt. 我的下一步是创建另外2种方法-加密和解密。 I'm just not sure about how to implement the encrypt and decrypt. 我只是不确定如何实现加密和解密。 I have a few ideas, but nothing that seems to be a good solution. 我有一些想法,但是似乎没有什么好的解决方案。 Any insights? 有什么见解吗?

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;

    /**
     * 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();
    }
}

Since you haven't really asked a specific question, I'll offer you a somewhat tangential answer. 由于您尚未真正提出具体的问题,因此我将为您提供切切的答案。

DIY Crypto is famously a bit like DIY nuclear power. DIY Crypto有点像DIY核电。

I recommend reading bouncy castle if you want to learn about crypto coding, and using it rather than rolling your own. 如果您想学习有关加密编码的知识,我建议阅读有弹性的城堡 ,并使用它而不是自己动手做。

Not sure what you're asking, but for RSA crypto, if your modulus is n bits wide, your public key will also be n bits wide. 不确定您要问什么,但是对于RSA加密,如果您的模数为n位宽,那么您的公钥也将为n位宽。 A simple int won't work. 一个简单的int无效。

See also 也可以看看

My own humble attempt at RSA encryption in Java: 我对Java RSA加密的谦卑尝试:
http://david.tribble.com/src/java/tribble/crypto/RSACipher.java http://david.tribble.com/src/java/tribble/crypto/RSACipher.java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM