开发者

How to implement RSA encrypt and decrypt in Java

开发者 https://www.devze.com 2023-02-02 03:48 出处:网络
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 id

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

0

精彩评论

暂无评论...
验证码 换一张
取 消