简体   繁体   中英

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. 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.

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. A simple int won't work.

See also

My own humble attempt at RSA encryption in Java:
http://david.tribble.com/src/java/tribble/crypto/RSACipher.java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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