Reputation: 434
I have generated a public and private code with puttygen, the private key is exported as openssl, the name of the peys are public_key.der , private_key.pem but when i try to use java to encrypt it i get this error:
java.io.FileNotFoundException: public_key.der
The codode is :
public static String RSAPublicEncryptuion(String text){
DataInputStream dis = null;
try {
File pubKeyFile = new File("public_key.der");
dis = new DataInputStream(new FileInputStream(pubKeyFile));
byte[] keyBytes = new byte[(int) pubKeyFile.length()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKey publicKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
String textoEncryptado = new String(cipher.doFinal(text.getBytes()), "UTF-8");
return textoEncryptado;
} catch (FileNotFoundException ex) {
Logger.getLogger(RSAEncrypt.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException ex) {
Logger.getLogger(RSAEncrypt.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException | BadPaddingException ex) {
Logger.getLogger(RSAEncrypt.class.getName()).log(Level.SEVERE, null, ex);
}
return "Error";
}
The public_key are in the same package than this class (testras.ras), what i'm doing wrong ? Thanks for all! Sorry for my bad English
Upvotes: 0
Views: 276
Reputation: 171
Your current approach (using a relative filepath) depends on the location of the key file relative to the working directory at runtime, which can be non-obvious.
However, you mention that the public key file is "in the same place where the .class" file is -- you can leverage this fact to gain a more flexible solution. Try using Class.getResourceAsStream, as illustrated below:
InputStream is = RSAEncrypt.class.getResourceAsStream("public_key.der");
Upvotes: 2