Topic
  • No replies
SurendharThallapelly
1 Post

Pinned topic Read Private Key from PEM BASE64 encoded file to use it for decrypting

‏2012-03-27T13:24:20Z |
package fileswr;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import com.ibm.security.util.DerValue;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.ibm.misc.BASE64Encoder;
import com.ibm.misc.BASE64Decoder;
import com.ibm.security.util.DerInputStream;
import com.ibm.security.util.DerOutputStream;
import com.ibm.security.x509.X509Key;
import javax.security.auth.x500.X500Principal;
import java.io.ByteArrayOutputStream;
import com.ibm.security.util.DerValue;
import javax.security.auth.x500.X500Principal;
import java.security.*;
import java.security.cert.*;
import java.security.cert.*;
import java.security.KeyFactory;
import java.security.Provider;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
import com.ibm.crypto.fips.provider.RSAPrivateKey;
import com.ibm.misc.BASE64Decoder;
import com.ibm.misc.CharacterDecoder;
import java.io.*;
public class surya {

public static void main(String[] args) throws Exception {
String privKeyFile = "C:\\SignKey.pem";
File pubCertFile = new File(privKeyFile);
BufferedInputStream bis = null;
bis = new BufferedInputStream(new FileInputStream(privKeyFile));
byte[] privKeyBytes = new bytehttp://(int)privKeyFile.length();
bis.read(privKeyBytes);
System.out.println(""+privKeyBytes);
bis.close();
Provider provBC = Security.getProvider("IBMJCEFIPS");
KeyFactory keyFactory = KeyFactory.getInstance("RSA",provBC);
BASE64Decoder b64 = new BASE64Decoder();
String lstr=privKeyBytes.toString();
System.out.println(""+lstr);
byte[] privKeyBytes1=b64.decodeBuffer(lstr);
System.out.println(""+privKeyBytes1.toString());
// decode private key
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes1);
System.out.println("Surya");
KeyFactory kf = KeyFactory.getInstance("RSA", "IBMJCEFIPS");

RSAPrivateKey pk = (RSAPrivateKey) kf.generatePrivate(privSpec);

}
}
Error Exception in thread "main" java.security.spec.InvalidKeySpecException: Inappropriate key specification: DerInputStream.getLength(): lengthTag=127, too big.
at com.ibm.crypto.fips.provider.RSAKeyFactory.b(Unknown Source)
at com.ibm.crypto.fips.provider.RSAKeyFactory.engineGeneratePrivate(Unknown Source)
at java.security.KeyFactory.generatePrivate(Unknown Source)
at fileswr.surya.main(surya.java:60)