File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Security and the fly likes need to generate RSA keys from txt files Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Engineering » Security
Bookmark "need to generate RSA keys from txt files" Watch "need to generate RSA keys from txt files" New topic
Author

need to generate RSA keys from txt files

Bala Raju Mandala
Ranch Hand

Joined: Sep 21, 2006
Posts: 40
Hi All,

I want to generate RSA keys from the txt files. I wrote the code by refering Google but it is not much fruitful. Please help me to get the keys from txt files.

getKeys(keySize, output, algorithm);
------------------------------------
Create RSA keys and write them to text files.

encrypt();
----------
read Public key from text file (RSA.pub) and encrypt a file.

decrypt();
----------
read a Private key from text file (RSA.pri) and decrypt the file.


Program i am using to write Keys to files are:

import java.io.*;
import java.math.*;
import java.security.*;
import java.security.interfaces.*;
import java.security.spec.KeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.Cipher;

public class JcaKeyPair {
public static void main(String[] a) {
System.out.println("in main");
int keySize = 1024; //1024 bits, 128 bytes
String output = "RSA";
String algorithm = "RSA"; // RSA, DSA
try {
getKeys(keySize, output, algorithm);
//encrypt();
//decrypt();
} catch (Exception e) {
System.out.println("Exception: " + e);
return;
}
}

private static void getKeys(int keySize, String output, String algorithm) throws Exception {
System.out.println("in getKeys method");
KeyPairGenerator kg = KeyPairGenerator.getInstance(algorithm);
kg.initialize(keySize);
System.out.println();
System.out.println("KeyPairGenerator Object Info: ");
System.out.println("Algorithm = " + kg.getAlgorithm());
System.out.println("Provider = " + kg.getProvider());
System.out.println("Key Size = " + keySize);
//System.out.println("toString = " + kg.toString());
KeyPair pair = kg.generateKeyPair();
System.out.println("Key Size = " + keySize);
PrivateKey priKey = pair.getPrivate();
PublicKey pubKey = pair.getPublic();
String fl = output + ".pri";
FileOutputStream out = new FileOutputStream("c:\\encrypt\\" + fl);
byte[] ky = priKey.getEncoded();
out.write(ky);
out.close();
System.out.println();
System.out.println("Private Key Info: ");
System.out.println("Algorithm = " + priKey.getAlgorithm());
System.out.println("Saved File = " + fl);
System.out.println("Size = " + ky.length);
System.out.println("Format = " + priKey.getFormat());
//System.out.println("toString = " + priKey.toString());
fl = output + ".pub";
out = new FileOutputStream("c:\\encrypt\\" + fl);
ky = pubKey.getEncoded();
out.write(ky);
out.close();
System.out.println();
System.out.println("Public Key Info: ");
System.out.println("Algorithm = " + pubKey.getAlgorithm());
System.out.println("Saved File = " + fl);
System.out.println("Size = " + ky.length);
System.out.println("Format = " + pubKey.getFormat());
//System.out.println("toString = " + pubKey.toString());
}

public static void encrypt() {
System.out.println("in Encrypt");
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
String pubKeyFile = "c:\\encrypt\\RSA.pub";
System.out.println("1");
FileInputStream pubKeyStream = new FileInputStream(pubKeyFile);
System.out.println("2");
byte[] pubKeyBytes = new byte[128]; //1024 bits
System.out.println("3");
pubKeyStream.read(pubKeyBytes);
System.out.println("4");
pubKeyStream.close();
System.out.println("5");
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyBytes);
System.out.println("6");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
System.out.println("7");

Cipher cf = Cipher.getInstance("RSA/ECB/NoPadding");
System.out.println("8");
cf.init(Cipher.ENCRYPT_MODE, pubKey);
System.out.println("9");
byte[] data = new byte[128];
byte[] cipher = new byte[128];

FileInputStream fis = new FileInputStream("c:\\encrypt\\Source.txt");
fis.read(data);

cipher = cf.doFinal(data);
System.out.println("3");
FileOutputStream fos = new FileOutputStream("c:\\encrypt\\Data.enc");
fos.write(cipher);
} catch(Exception e) {
System.out.println("Exception in encryption " + e);
}
}

public static void decrypt() {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
String priKeyFile = "C:\\encrypt\\RSA.pri";
FileInputStream priKeyStream = new FileInputStream(priKeyFile);
byte[] priKeyBytes = new byte[128];
priKeyStream.read(priKeyBytes);
priKeyStream.close();
PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(priKeyBytes);
PrivateKey priKey = keyFactory.generatePrivate(priKeySpec);

Cipher cf = Cipher.getInstance("RSA/ECB/NoPadding");
cf.init(Cipher.DECRYPT_MODE, priKey);

byte[] cipher = new byte[128];
byte[] plain = new byte[128];

FileInputStream fis = new FileInputStream("C:\\encrypt\\Data.enc");
fis.read(cipher);

plain = cf.doFinal(cipher);

FileOutputStream fos = new FileOutputStream("C:\\encrypt\\Result.txt");
fos.write(plain);
} catch(Exception e) {
System.out.println("Exception in decryption " + e);
}
}
}

It is giving following error message:

Exception in encryption java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: null
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41574
    
  54
Please edit your post toUseCodeTags. It is unnecessarily hard to read as it is.

In which line of code does the exception occur?


Ping & DNS - my free Android networking tools app
greg stark
Ranch Hand

Joined: Aug 10, 2006
Posts: 220
I have taken the liberty of slightly rewriting the code so that I could eliminate the hard-coded absolute pathnames, and I'll post that here with code tags. I'll comment on the bugs in the next reply.


Nice to meet you.
greg stark
Ranch Hand

Joined: Aug 10, 2006
Posts: 220
Your first mistake occurs in

Note that, while the modulus may be 1024 bits, the public key consists of at least the modulus and the exponent. In fact, it contains even more information, such as the fact the public key algorithm is RSA, and other descriptive information. On my computer, in the one instance I checked, this file was in fact 162 bytes in length. Never assume you know what the length is in advance. Either save the length somewhere (ky.length), or let the filesystem tell you the length. You should become familiar with the DataInputStream and DataOutputStream classes; they are very useful. For example, consider this alternative sequence of Java which produces the correct result:

I have not examined the rest of the code for errors.
Bala Raju Mandala
Ranch Hand

Joined: Sep 21, 2006
Posts: 40
Thank you Ulf and Greg. But these changes are not made any difference, i am getting same exception. I am searching google for references, but they are using MD5 to encode and checking signatures also. I am confused can't we simply read from txt files and recreate the RSA keys? is it is not that simpler? folks please help!
[ September 21, 2008: Message edited by: Bala Raju Mandala ]
greg stark
Ranch Hand

Joined: Aug 10, 2006
Posts: 220
I am confused can't we simply read from txt files and recreate the RSA keys?


I can, using the code fragment I provided.
Bala Raju Mandala
Ranch Hand

Joined: Sep 21, 2006
Posts: 40
Yes, i did some mistakes. Your code is working. Thank you once again.
sergio martinelli
Greenhorn

Joined: Sep 21, 2008
Posts: 5
I suggest you use the API Bouncy Castle OpenPGP are easy to use and well documented.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: need to generate RSA keys from txt files