Retrieving Public Key

I’m creating a Java project that is simply based on a client that sends a string to a server.
The server receives it and encrypts/decrypts the data using Private and Public keys generated on the Nitrokey HSM device. I’m using the SunPKCS11 as provider.

When i want to encrypt I use the Private key and it works fine but when i want to decrypt using the Public key it gives me an error like this: init() failed
at javax.crypto.Cipher.init(
at javax.crypto.Cipher.init(
at CriptographyServer.main(
at Method)
… 4 more

This is the code for getting keys:

                    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", hsmProvider);
		KeyPair pair = gen.generateKeyPair();

		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", hsmProvider);
		cipher.init(Cipher.ENCRYPT_MODE, pair.getPrivate());
		byte[] msg = cipher.doFinal(recivedMessage.getBytes());
		String enc = bytesToHex(msg);
		System.out.println("Crypting..." + recivedMessage + "\nCrypted Message...: " + enc);	
		cipher.init(Cipher.DECRYPT_MODE, pair.getPublic());
		byte[] msg1 = cipher.doFinal(msg);
		String dec = bytesToHex(msg1);
		System.out.println("Decrypted Message..." +  dec); 

So i think the “pair.getPublic()” is wrong for retrieving the public key…

Hi A-User22,
It looks like you have it the wrong way: using RSA, you are meant to encrypt with the public key, and decrypt with the private (secret) key, and you are trying to do the opposite.

Yeah, I’ve tried doing like you said but the problem remain. I think the problem it’s how I get the public key.