We have a client server system where client(Android phone) and server(spring ) both are using java.security.KeyFactory to get an instance of java.security.KeyFactory as shown below:
KeyFactory factory = KeyFactory.getInstance("RSA"); But if we do that, when we use this factory to encrypt data, the server gives a different output and the client gives different output. When we checked providers, it was coming to SunRsaSign for server and was OpenSSLRSA for the client. So we tried to set the same on the client using the following:
KeyFactory factory = KeyFactory.getInstance("RSA", "SunRsaSign"); But we get java.security.NoSuchProviderException error. Similarly when we try to set OpenSSLRSA on server, they also face the same error.
Complete code to encrypt is same on server and client is following:
String pubKey = "<key here>" byte[] keyData = DatatypeConverter.parseHexBinary(pubKey); System.out.println("key data" + Arrays.toString(keyData)); KeyFactory factory = KeyFactory.getInstance("RSA"); //System.out.println("provide = " + factory.getProvider()); PublicKey pub = factory.generatePublic(new X509EncodedKeySpec(keyData)); Cipher encryptCipher = Cipher.getInstance("RSA"); encryptCipher.init(Cipher.ENCRYPT_MODE, pub); byte[] secretMessageBytes = msg.getBytes(StandardCharsets.UTF_8); System.out.println("secret msg" +Arrays.toString(secretMessageBytes)); byte[] encryptedMessageBytes = encryptCipher.doFinal(secretMessageBytes); System.out.println("enc data" +Arrays.toString(encryptedMessageBytes)); encryptedMessageBytes generated are different. Can that be a problem? I think it is because of different Providers being used by different platform.
Can somebody pls help me on how to set the provider for KeyFactory or how to remove the decryption error(javax.crypto.BadPaddingException)?
Cipher.getInstance("RSA/ECB/PKCS1Padding"). Possibly different padding defaults on each side.