Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

RSA Reading Private Key from File

807588Jan 24 2009 — edited Jan 25 2009
Hi,
I've created a code to generate RSA key pairs and save them base64 encoded in different files and now writing the below code to read the private key from its file to try to encrypt another file but it is giving me an error

DerInputStream.getLength(): lengthTag=127, too big

Can someone please have a look on my code and tell me what i have done wrong?

By the way the contents of the private key file are:
¬í tøMIIBawIBADANBgkqhkiG9w0BAQEFAASCAVUwggFRAgEAAkYFDMmTJW82N+UYT6+/mvvaiOEaV/Bc
dUuV2p9QN0fzRjT7ktsHFG6s7yJhSx4wi554JnGtSeQFNDpQWQoxnWzLRypSpaVnAgMBAAECRgTC
OQ1VQEhKQbM4HDglVuFnDSBi79hgm7p5ypivjzia1wCd7K/4BLRmR0ZF7az3Kqzbo6XMWF+IuglX
YymQcVjE7aSiWRkCIysbzzye2Y4417GFMESt9jOtl09gC8dH1LLNPuMAcfr6VjFTAiMd/TMpKFLw
QnpuIyGVaDe1uq/fgVemNvm5rUUR7TIrjcjVHQIjCgZFgstNvAzr25QlTVNG1W2gqgyjsIu7onio
DxGjb8GXGZECIwqCEk81pfoyERxOixIDNqIjDEVQ2RmQ4ehB4pXpe07vm5OxAiMUOb5DmGE2xjo7
re1lVo1kOLqIgg9qJgRg+e5v91p1aliy9w==

Thanks

import java.io.*;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Asymmetric_Encyption {

public static void main(String[] args) throws Exception
{
// Decide mode; Encryption or Decryption
int Choice = 0;
String ChoiceS;

System.out.print("Welcome to the RSA Encryption/Decryption program\nkindly choose between: \n(1) Encrypt a plain file \n(2) Decrypt an encrypted file \nYour Choice: ");

BufferedReader brc = new BufferedReader(new InputStreamReader(System.in));

try {
ChoiceS = brc.readLine();
Choice = Integer.parseInt(ChoiceS);
}

catch (IOException ioex)
{
System.out.println("Input error");
System.exit(1);
}

catch ( NumberFormatException e)
{
System.out.println (e.getMessage() + " is not a valid format for an integer.");
System.exit(1);
}

if (Choice == 1)
{
FileEncryption ();
}
else if (Choice == 2)
{
// FileDecryption ();
}
else
{
System.out.println (Choice + " is not a valid choice");
System.exit(1);
}

}

static void FileEncryption ()throws Exception
{

Security.addProvider(new BouncyCastleProvider());

// Getting the path of the file to be encrypted

System.out.print("Enter the filename to be encrypted\n(full path is needed if not located at the same directory): ");
String FileName = null;
BufferedReader brf = new BufferedReader(new InputStreamReader(System.in));

try
{
FileName = brf.readLine();
}
catch (IOException IOE)
{
System.out.println("IO error trying to read your filename!");
System.exit(1);
}

// Getting the public key

System.out.print("Enter the file name that contains the private key used during encryption\n(full path is needed if not located at the same directory): ");
String KeyFile = null;
BufferedReader brkf = new BufferedReader(new InputStreamReader(System.in));

try
{
KeyFile = brkf.readLine();
}

catch (IOException IOE)
{
System.out.println("IO error trying to read your key file");
System.exit(1);
}

byte privkbuffer[] = new byte[KeyFile.length()];
InputStream kin = new FileInputStream(KeyFile);
int i = kin.read(privkbuffer);
String privkey = new String(privkbuffer);
BASE64Decoder decoder = new BASE64Decoder();
byte[] privKeyBytes = decoder.decodeBuffer(privkey);


KeyFactory keyFactory = KeyFactory.getInstance("RSA");

// decode private key
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);

// Get a Cipher object
Cipher rsacipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
rsacipher.init(Cipher.ENCRYPT_MODE, privKey);

FileInputStream fin = new FileInputStream(FileName);
OutputStream out = new FileOutputStream(FileName+".enc");

byte[] buf = new byte[FileName.length()];
try {
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, rsacipher);

// Read in the clear text bytes and write to out to encrypt
int numRead = 0;
while ((numRead = fin.read(buf)) >= 0) {
out.write(buf, 0, numRead);
}
out.close();
} catch (java.io.IOException ioe) {
}

out.flush();
System.out.println("Encryption is done, the output filename is "+FileName+".enc");

}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 22 2009
Added on Jan 24 2009
2 comments
1,625 views