如何用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();
}
}
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您还没有真正提出具体问题,所以我将为您提供一个有点切题的答案。
众所周知,DIY 加密有点像 DIY 核电。
如果您想了解加密编码并使用它而不是自己动手,我建议您阅读 充气城堡。
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.
不确定您在问什么,但对于 RSA 加密,如果您的模数为 n 位宽,则您的公钥也将为 n 位宽。简单的
int
不起作用。另请参阅
我自己在 Java 中对 RSA 加密的拙劣尝试:
http://david.tribble.com/src/java/tribble/crypto /RSACipher.java
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