这只是为了好玩。这不会用于任何实际加密。我只是第一年的学生和爱密码学。
这需要很长时间才能开始工作。在大约N = 18时,它开始分解。在此之后它不会正确加密消息。我不知道为什么。任何见解?我也非常感谢您可以提供的关于密码学的教程或有趣阅读的任何链接。
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* Cryptography.
*
* Generates public and private keys used in encryption and
* decryption
*
*/
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;
private String cipherText;
/**
* 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();
}
public String encrypt(String plainText)
{
String encrypted = "";
int j = 0;
for(int i = 0; i < plainText.length(); i++){
char m = plainText.charAt(i);
BigInteger bi1 = BigInteger.valueOf(m);
BigInteger bi2 = bi1.modPow(e, n);
j = bi2.intValue();
m = (char) j;
encrypted += m;
}
cipherText = encrypted;
return encrypted;
}
public String decrypt()
{
String decrypted = "";
int j = 0;
for(int i = 0; i < cipherText.length(); i++){
char c = cipherText.charAt(i);
BigInteger bi1 = BigInteger.valueOf(c);
BigInteger bi2 = bi1.modPow(d, n);
j = bi2.intValue();
c = (char) j;
decrypted += c;
}
return decrypted;
}
}
答案 0 :(得分:2)
由于您只有2 ^ 16条不同的消息,因此您的加密可能会非常简单。如果使用正确的填充(OEP),RSA仅是安全的。当然,由于您将一个char映射到一个RSA块,因此cyphertext占用的空间是明文的100倍。
j = bi2.intValue();
m = (char) j;
这两项行动都可怕地溢出。 bi2是BigInteger的原因。它只是不适合32位整数/ 16位字符。由于截断整数会丢失大部分位,因此解密将不起作用,因为您损坏了密文。