I have a file called privatekey.der in the same directory as a static class called KeyReader.
I’m having issues with reading the file. It’s giving me invalid stream header. I was wondering how you can go about reading the file.
This is my code:
package server.encryption;
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.*;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class KeyReader {
public static PrivateKey getPrivateKey(InputStream in) throws Exception {
// System.err.println(filename);
// File f = new File(filename);
//DataInputStream dis = new DataInputStream(is);
ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privateKey = fact.generatePrivate(keySpec);
oin.close();
return privateKey;
// PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
// KeyFactory kf = KeyFactory.getInstance("RSA");
// return kf.generatePrivate(spec);
}
public static byte[] rsaDecrypt(byte[] data) throws Exception {
System.err.println(KeyReader.class.getResourceAsStream("privatekey.der").toString());
PrivateKey privateKey = getPrivateKey(KeyReader.class.getResourceAsStream("privatekey.der"));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
}
public static byte[] aesDecrypt(byte[]data, byte[]key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, cipher.getParameters());
byte[] cipherData = cipher.doFinal(data);
return cipherData;
}
}