Retrieving Public Key

Hi
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:

java.security.InvalidKeyException: init() failed
at sun.security.pkcs11.P11RSACipher.implInit(P11RSACipher.java:239)
at sun.security.pkcs11.P11RSACipher.engineInit(P11RSACipher.java:168)
at javax.crypto.Cipher.init(Cipher.java:1249)
at javax.crypto.Cipher.init(Cipher.java:1189)
at CriptographyServer.main(CriptographyServer.java:116)
Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_NOT_SUPPORTED
at sun.security.pkcs11.wrapper.PKCS11.C_VerifyRecoverInit(Native Method)
at sun.security.pkcs11.P11RSACipher.initialize(P11RSACipher.java:310)
at sun.security.pkcs11.P11RSACipher.implInit(P11RSACipher.java:237)
… 4 more

This is the code for getting keys:

                    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", hsmProvider);
		gen.initialize(2048);
				
		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.