【发布时间】:2014-05-07 11:46:57
【问题描述】:
我在网上找到了这个 rsa 代码。我的代码有问题,对于较大的文本,它没有按预期工作。但是,它可以很好地解密几行文本。任何人都可以指出代码或逻辑的错误。谢谢
import java.math.BigInteger;
import java.util.Random;
import java.io.*;
/**
*
* @author Mohtashim
*/
public class RSA {
private BigInteger p;
private BigInteger q;
private BigInteger N;
private BigInteger phi;
private BigInteger e;
private BigInteger d;
private int bitlength = 1024;
private int blocksize = 128; //blocksize in byte
private Random r;
public RSA() {
r = new Random();
p = BigInteger.probablePrime(bitlength, r);
q = BigInteger.probablePrime(bitlength, r);
long startTime= System.nanoTime();
N = p.multiply(q);
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
long endTime= System.nanoTime();
System.out.println((endTime-startTime)/1000);
e = BigInteger.probablePrime(bitlength/2, r);
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0 ) {
e.add(BigInteger.ONE);
}
d = e.modInverse(phi);
System.out.println("p : " + p);
System.out.println("q : " + q);
System.out.println("phiN : " + N);
//System.out.println("gcd : " + gcd);
System.out.println("e : " + e);
System.out.println("d : " + d);
}
private static String bytesToString(byte[] encrypted) {
String test = "";
for (byte b : encrypted) {
test += Byte.toString(b);
}
return test;
}
public RSA(BigInteger e, BigInteger d, BigInteger N) {
this.e = e;
this.d = d;
this.N = N;
}
public byte[] encrypt(byte[] message) {
return (new BigInteger(message)).modPow(e, N).toByteArray();
}
public byte[] decrypt(byte[] message) {
return (new BigInteger(message)).modPow(d, N).toByteArray();
}
public static void main(String[] args) throws IOException {
// TODO code application logic here
RSA objRSA;
objRSA = new RSA();
int intC=0;
byte[] encrypted = objRSA.encrypt("hello bhai jan kia haal hein aaq k hyl".getBytes());
String decrypted = new String (objRSA.decrypt(encrypted));
System.out.println("encrypted: "+ encrypted);
System.out.println("decrypted: "+ decrypted);
}
}
【问题讨论】:
-
看看这个,它可以解释为什么你会遇到更大的明文问题:stackoverflow.com/questions/11822607/…
-
“它没有按预期工作”是一个非常模糊的术语,如果您遇到错误,请始终粘贴错误消息,如果您的代码行为与预期不同,请务必明确您的预期以及代码确实做到了,所以我们可以帮助你
-
我认为他的问题是对如何使用RSA的错误理解。它仅应用作加密协议中的构建块,而不应用作加密整个有效负载的算法。上面的代码按预期工作。问题是用户:-)
-
"textbook" RSA 不能加密比模数更大的任何东西(它是模幂运算,所以这应该不足为奇)。 RSA 的安全模式(例如 OAEP)指定填充,增加了从消息的最大大小中减去的额外开销。
-
@owlstead 这次是你的答案作为评论;)我感染了你吗?
标签: java encryption cryptography public-key-encryption encryption-asymmetric