Reputation: 31
In Java, how to use RSA_PKCS1_OAEP_PADDING
to encrypt? When I use this below, it shows
javax.crypto.NoSuchPaddingException:RSA/ECB/OAEPPadding unavailable with RSA
cipher = Cipher.getInstance("RSA/ECB/OAEPPadding", provider);
Can you tell me the correct answer?
Upvotes: 1
Views: 2453
Reputation: 1699
Bit late to the party but this could help:
private const val ALGORITHM = "RSA"
private const val CIPHER = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"
private const val SHA_256 = "SHA-256"
private const val MGF1 = "MGF1"
private const val PUBLIC_KEY_RSA_PKCS1_OAEP_PADDING = "FpMUwRxHsWFXlnAE1iSFC4q3d0bI...." // your public key
val keyBytes: ByteArray = Base64.decode(PUBLIC_KEY_RSA_PKCS1_OAEP_PADDING.replace("\n", "").replace("\r", ""), Base64.NO_WRAP)
val keyFactory = KeyFactory.getInstance(ALGORITHM)
val publicKeySpec = X509EncodedKeySpec(keyBytes)
val publicKey = keyFactory.generatePublic(publicKeySpec)
val cipher = Cipher.getInstance(CIPHER)
val oaepParams = OAEPParameterSpec(SHA_256, MGF1, MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT)
cipher.init(Cipher.ENCRYPT_MODE, publicKey, oaepParams)
val encryptedData = cipher.doFinal(dataToEncrypt.toByteArray(Charsets.UTF_8))
val encryptedStringInUtf8 = Base64.encode(encryptedData, Base64.NO_WRAP).toUtf8String()
utf8 helper method:
fun ByteArray.toUtf8String() = toString(UTF_8)
Upvotes: 3
Reputation: 269627
Try without specifying a provider, that is:
cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");
If you want to use a specific provider, provide more information about which provider you are using, and what evidence you have that the provider supports OAEP padding.
There is meta-data in the provider itself about the services it provides and their details. We can look into that further if needed, but I think the answer here is simply that this provider doesn't make any provision for OAEP.
Upvotes: 1