RSA is algorithm used by modern computers to encrypt and decrypt messages. It is an asymmetric cryptographic algorithm. Asymmetric means that there are two different keys. This is also called public key cryptography, because one of them can be given to everyone. The other key must be kept private. It is based on the fact that finding the factors of an integer is hard (the factoring problem). RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman, who first publicly described it in 1978. A user of RSA creates and then publishes the product of two large prime numbers, along with an auxiliary value, as their public key. The prime factors must be kept secret. Anyone can use the public key to encrypt a message, but with currently published methods, if the public key is large enough, only someone with knowledge of the prime factors can feasibly decode the message.
/*
* RSA ALGORITHM performed and executed in NetBeans 7.4
*/
package rsa;
import java.math.*;
import java.security.SecureRandom;
/**
*
* @author Professional Cipher[www.professionalcipher.blogspot.com]
*/
public class RSA {
private static BigInteger one=new BigInteger("1");
private static BigInteger n;
private static BigInteger phi;
private static BigInteger e;
private static BigInteger d;
public RSA()
{
BigInteger p=BigInteger.probablePrime(40, new SecureRandom());
BigInteger q=BigInteger.probablePrime(40, new SecureRandom());
n=p.multiply(q);
phi=(p.subtract(one)).multiply(q.subtract(one));
e=new BigInteger("65537"); //only use prime number
d=e.modInverse(phi);
}
public BigInteger encrypt(BigInteger msg)
{
return msg.modPow(e, n);
}
public BigInteger decrypt(BigInteger msg)
{
return msg.modPow(d, n);
}
@Override
public String toString() {
return "Public key="+e.longValue()+"\nPrivate key="+d.longValue()+"\nModuli="+n.longValue();
}
public static void main(String[] args) {
RSA rsa=new RSA();
System.out.println(rsa);
String msg="BEIT";
System.out.println("Plaintext="+msg);
BigInteger plaintext=new BigInteger(msg.getBytes());
BigInteger ciphertext=rsa.encrypt(plaintext);
System.out.println("Encrypted message="+new String(ciphertext.toByteArray()));
BigInteger dplaintext=rsa.decrypt(ciphertext);
System.out.println("Decrypted message="+new String(dplaintext.toByteArray()));
}
}
/*
run:
Public key=65537
Private key=-7970827358922742135
Moduli=-2156239117027535611
Plaintext=BEIT
Encrypted message='��R�2��]
Decrypted message=BEIT
BUILD SUCCESSFUL (total time: 0 seconds)
*/

## 0 Comments