I am trying to generate a key pair in asymmetric encryption in Java, but I am getting an invalid key exception
error and it says No installed provider supports this key: sun.security.rsa.RSAPrivateCrtKeyImpl
.
private static byte[] encrypt(byte[] inpBytes, PrivateKey prvk,
String xform) throws Exception {
Cipher cipher = Cipher.getInstance(xform);
cipher.init(Cipher.ENCRYPT_MODE, prvk);
return cipher.doFinal(inpBytes);
}
@Override
public byte[] uploadFile(byte[] data, String name, String file, int size)
throws RemoteException {
// TODO Auto-generated method stub
byte[] keyss=null;
try {
OutputStream out =
new FileOutputStream(new File("C:\\Users\\Amaresh\\Documents\\Cloud\\"
+ name + "\\" + file));
String xform = "DES/CTR/NoPadding";
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); // Original
kpg.initialize(1024); // 512 is the keysize.//try 1024 biit
KeyPair kp = kpg.genKeyPair();
PublicKey pubk = kp.getPublic();
PrivateKey prvk = kp.getPrivate();
keyss = pubk.getEncoded();
byte[] encBytes = encrypt(data, prvk, xform);
System.out.println("Keypair generated");
out.write(encBytes, 0, encBytes.length);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return keyss;
}
I just want to do asymmetric encryption where I encrypt the data with private key and store the public key to decrypt it. I am a beginner and I am sorry for my blunt mistakes.
You are generating the keys correctly.
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair keys = kpg.generateKeyPair();
The problem is in your:
byte[] encBytes = encrypt(data, prvk, xform);
Most likely because you are passing in the String "DES/CTR/NoPadding". You cannot encrypt using DES with an RSA key pair.