I have to encrypt a file to pgp format. I have my public key in .asc format.
The cipher init() method needs a public key to be passed in. What is way to load that key from the file like this? In my case it is .asc file. And the details ablout the key file is described below:
I am getting an error: " java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format " when I am trying to encrypt a file.
Here is my encrypt method:
public static CipherOutputStream encrypt(OutputStream outputStream, String publicKeyPath)
{
Cipher cipher;
Key publicKey = null;
try
{
cipher = Cipher.getInstance("RSA", "BC");
} catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) {
String msg = "failed to create output stream";
System.out.println( msg + " : " + e.getMessage());
e.printStackTrace();
throw new RuntimeException( msg, e );
}
try {
publicKey = getPublicKey(publicKeyPath);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ( new CipherOutputStream(outputStream, cipher));
}
I am getting error: java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
My getPublicKey method looks like :
public static PublicKey getPublicKey(String filename)
throws Exception {
File pubKeyFile = new File(filename);
DataInputStream dis = new DataInputStream(new FileInputStream(pubKeyFile));
byte\[\] pubKeyBytes = new byte\[(int)pubKeyFile.length()\];
dis.readFully(pubKeyBytes);
dis.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// decode public key
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
return keyFactory.generatePublic(pubSpec);
}
Public_key.asc looks like :
-----BEGIN PGP PUBLIC KEY BLOCK----- Version: Encryption Desktop 10.3.2 (Build 16127) mQENBFYhXNoBCACgX/u03wm8cLqmTZiKGx6H/1ZUoBsfaDB2rdG2D8jYQzvaq4MA hZWBEVhA2BGKrNI+a2SDhKGAY4OK7aUZVAVG1bfQNVdNe80TbEF8g/wO2FreYPkb ojPtkwgyzsvb1BKwgRM1UMjkM5OWnhAPDhFDc39SFbmHLsXrURqFqJd9T3xzF6ty ................................................................ D4WXvHpPXCJcwCBe+/81ZpjxlrLkUu8bO79jxZdKcI5ZRpmIe/VPJoDUVKLvl9n3 ANvDJGdGcW3x6RyL9QOnoRDf6njimqcTm8UqImdLCz4TFdv94dvM4K0NOWuFdYal E9Q+U0Q7aiaWn+Kt+OYpd6++m7wnJRH/q0H69LIR9v3Td3udzOaxv/gzXF1BFuAS DQs6iA== =ckOV -----END PGP PUBLIC KEY BLOCK-----
Here are the properties of this key:
