I want to write my own RSA encrypter without libaries!
Code:
import java.util.Random;
public class Main {
public static void main(String[] args) {
System.out.println(createPrime());
}
private static byte encrypt(byte message) {
double p = createPrime();
double q = createPrime();
double e = 2 ^ new Random().nextInt(100) % (p * q);
byte ciphered = Math.pow(message, e);
return ciphered;
}
private static double createPrime() {
double testPow;
do {
int test = new Random().nextInt(20);
int power = new Random().nextInt(20);
test += 1;
power +=1;
testPow = Math.pow(test, power);
System.out.println("Double Math.pow: " + testPow);
} while (!testPrime(testPow));
return testPow;
}
private static Boolean testPrime(Double test) {
int factor = 2;
int lastFactor = 1;
while (test > 1) {
if (test % factor == 0) {
lastFactor = factor;
test /= factor;
while (test % factor == 0) {
test /开发者_JAVA百科= factor;
}
}
factor++;
}
Boolean isPrime = false;
if (test == lastFactor) {
isPrime = true;
}
return isPrime;
}
}
This is what I have for encrypting. I don't know what I should do to correct this, but I have pretty much done this by hand before trying this.
So I know that the equation to encrypt is c = m^e (mod N) and decryption m = c^d (mod N)
where p, q are prime numbers - m is message - c is ciphered text - e is totient of N - N is p times q - totient of N is (p-1)(q-1)
Any help is appreciated
The first thing to do is to have a look at the class java.math.BigInteger. This class will help you a lot to implement "School-book" RSA.
You didn't ask a real question, but I see a couple of problems anyways
double e = 2 ^ new Random().nextInt(100) % (p * q);
I don't know what this is supposed to do, but it's wrong. Did you mean Math.Pow()
rather than ^
? In any case, usually you just use some small constant with very few set bits for e
to make encryption fast. e=3
or e=65
would work fine.
You don't seem to be calculating the private key (d
), or even storing the public key (e
, p*q
) at all.
When you start using large numbers, int
and double
(??) will not be able to hold them. Use BigInteger
instead.
do {
testPow = Math.pow(test, power);
} while (!testPrime(testPow));
If power > 1
, testPow will never be prime...
I have not looked at testPrime()
, but you should be able to write some quick unit tests to convince yourself whether or not it probably works.
I'd suggest reading/copying an existing implementation for reference, such as BouncyCastle: http://www.docjar.com/html/api/org/bouncycastle/crypto/engines/RSACoreEngine.java.html
By the way, if you want this to be at all secure, you should be using java.security.SecureRandom, not java.util.Random
Java has built-in encryption algorithms under the java.security
package. Check this. So no need for external libraries. I see no production need to implement it yourself. Only if it is homework (which you didn't tag)
精彩评论