java - 如何用Java实现RSA加解密

标签 java rsa

我可以生成公钥和私钥。我的下一步是创建另外 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 加密有点像 DIY 核电。

我建议阅读bouncy castle如果您想了解加密编码并使用它而不是自己动手。

关于java - 如何用Java实现RSA加解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4572955/

相关文章:

java - 我在解密使用 RSA 生成的公钥 (.jks) 编码的 128 位 AES key 时遇到 BadPaddingException

java - 在 Java 中为 OpenSSL 格式化 RSA key

java - Spring @Async 注解的方法在调用自身时会阻塞

c# - RSA - 仅使用(!)模数加密?

java - Jar 文件不使用自定义字体

java - 为什么 Java ServerSocket accept() 返回一个与 ServerSocket 具有相同端口的套​​接字?

go - 替代 golang 中的 load_pem_private_key()

android - 在 android 中存储 RSA key 对

java - 错误: Main method not found in java class

java - 为什么在将 json 响应转换为 ArrayList<Object> 时,gson 库将整数值设置为零?