aspose file tools*
The moose likes Sockets and Internet Protocols and the fly likes RSA algorithm Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Reply locked New topic
Author

RSA algorithm

Rohan Tadphale
Greenhorn

Joined: Dec 28, 2013
Posts: 8

import java.math.BigInteger;
import java.security.SecureRandom;


public class RSA {
private final static BigInteger one = new BigInteger("1");
private final static SecureRandom random = new SecureRandom();

private BigInteger privateKey;
private BigInteger publicKey;
private BigInteger modulus;

// generate an N-bit (roughly) public and private key
RSA(int N) {
BigInteger p = BigInteger.probablePrime(N/2, random);
BigInteger q = BigInteger.probablePrime(N/2, random);
BigInteger phi = (p.subtract(one)).multiply(q.subtract(one));

modulus = p.multiply(q);
publicKey = new BigInteger("65537"); // common value in practice = 2^16 + 1
privateKey = publicKey.modInverse(phi);
}


BigInteger encrypt(BigInteger message) {
return message.modPow(publicKey, modulus);
}

BigInteger decrypt(BigInteger encrypted) {
return encrypted.modPow(privateKey, modulus);
}

public String toString() {
String s = "";
s += "public = " + publicKey + "\n";
s += "private = " + privateKey + "\n";
s += "modulus = " + modulus;
return s;
}

public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
RSA key = new RSA(N);
System.out.println(key);

// create random message, encrypt and decrypt
BigInteger message = new BigInteger(N-1, random);

//// create message by converting string to integer
// String s = "test";
// byte[] bytes = s.getBytes();
// BigInteger message = new BigInteger(s);

BigInteger encrypt = key.encrypt(message);
BigInteger decrypt = key.decrypt(encrypt);
System.out.println("message = " + message);
System.out.println("encrpyted = " + encrypt);
System.out.println("decrypted = " + decrypt);
}
}




------------------------------------OUTPUT--------------------------

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at rsaTest.RSAtest.main(RSAtest.java:70)
-----------------------------------------------------------------------

I am trying to Generate an N-bit public and private RSA key and use to encrypt and decrypt a random message.
help please?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18999
    
  40


Please refer to your other topic for responses...

http://www.coderanch.com/t/637880/java/java/RSA-algorithm

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: RSA algorithm