簡體   English   中英

如何在Java中實現RSA加密和解密

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

我有公鑰和私鑰生成工作。 我的下一步是創建另外2種方法-加密和解密。 我只是不確定如何實現加密和解密。 我有一些想法,但是似乎沒有什么好的解決方案。 有什么見解嗎?

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

由於您尚未真正提出具體的問題,因此我將為您提供切切的答案。

DIY Crypto有點像DIY核電。

如果您想學習有關加密編碼的知識,我建議閱讀有彈性的城堡 ,並使用它而不是自己動手做。

不確定您要問什么,但是對於RSA加密,如果您的模數為n位寬,那么您的公鑰也將為n位寬。 一個簡單的int無效。

也可以看看

我對Java RSA加密的謙卑嘗試:
http://david.tribble.com/src/java/tribble/crypto/RSACipher.java

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM