這僅僅是爲了好玩。這不會用於任何實際的加密。我只是一年級的科學學生和愛密碼學。簡單的RSA加密(JAVA)
這花了很長的時間去工作。在大約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;
}
}
你需要更具體和你所說的「打破」的東西,通過不加密的消息「正確的」,以及它是否具有N個工作<18 or N> 18.此外,因爲它代表你在ECB模式下使用RSA ,而你應該使用混合方案。 – crazyscot
哦,以及閱讀的文本 - Schneier,Ferguson和Kohno的密碼學工程。 – crazyscot
加密工作,但解密與N> 18.感謝不是做爲閱讀的建議,我會從庫中得到它儘快! –