We working on RSA encryption/Decryption in Java.
We are able to perform encryption but getting error for decryption
Below is code snippet we are using
public class RSA_Read_Write_Key { static String plainText = "This RSA Crypto Java Code"; public static void main(String[] args) throws Exception { byte[] cipherTextArray = encrypt(plainText, "D:\\TCE\\public.key"); String encryptedText = Base64.getEncoder().encodeToString(cipherTextArray); System.out.println("Encrypted Text : " + encryptedText); String decryptedText = decrypt(cipherTextArray, "D:\\TCE\\private.key"); System.out.println("DeCrypted Text : " + decryptedText); } public static Key readKeyFromFile(String keyFileName) throws IOException { Key key = null; InputStream inputStream = new FileInputStream(keyFileName); ObjectInputStream objectInputStream = new ObjectInputStream(new BufferedInputStream(inputStream)); try { BigInteger modulus = (BigInteger) objectInputStream.readObject(); BigInteger exponent = (BigInteger) objectInputStream.readObject(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); if (keyFileName.startsWith("public")) key = keyFactory.generatePublic(new RSAPublicKeySpec(modulus, exponent)); else key = keyFactory.generatePrivate(new RSAPrivateKeySpec(modulus, exponent)); } catch (Exception e) { e.printStackTrace(); } finally { objectInputStream.close(); } return key; } public static byte[] encrypt(String plainText, String fileName) throws Exception { Key publicKey = readKeyFromFile("D:\\TCE\\public.key"); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] cipherText = cipher.doFinal(plainText.getBytes()); return cipherText; } public static String decrypt(byte[] cipherTextArray, String fileName) throws Exception { Key privateKey = readKeyFromFile("D:\\TCE\\private.key"); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte [] plain = new byte[100]; byte[] decryptedTextArray = cipher.doFinal(cipherTextArray); return new String(decryptedTextArray); } } When we run the code we getting below Error. Can someone help to resolve this?
Exception in thread "main" javax.crypto.BadPaddingException: Decryption error at sun.security.rsa.RSAPadding.unpadV15(Unknown Source) at sun.security.rsa.RSAPadding.unpad(Unknown Source) at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363) at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389) at javax.crypto.Cipher.doFinal(Cipher.java:2164) at RSAcrypto.RsaToy.decrypt(RsaToy.java:108) at RSAcrypto.RsaToy.main(RsaToy.java:34)
KeyStore? This is radically insecure.