简体   繁体   中英

javax.crypto.BadPaddingException: Decryption error

Here is the error I have got when run my Encode & Decode Class.

javax.crypto.BadPaddingException: Decryption error
    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:365)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
    at javax.crypto.Cipher.doFinal(Cipher.java:2087)
    at RSAEncDecDemo.decryptData(RSAEncDecDemo.java:64)
    at RSAEncDecDemo.main(RSAEncDecDemo.java:47)
java.lang.NullPointerException
    at java.lang.String.<init>(String.java:556)
    at RSAEncDecDemo.decryptData(RSAEncDecDemo.java:70)
    at RSAEncDecDemo.main(RSAEncDecDemo.java:47)

Here is the source code of RSAEncDecDemo.java class file.

public class RSAEncDecDemo {

    private static final String PUBLIC_KEY_FILE = "lk.public.key";
    private static final String PRIVATE_KEY_FILE = "lk.private.key";

    @SuppressWarnings("restriction")
    public static void main(String[] args) throws IOException {

        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();

            writeStringkey(PUBLIC_KEY_FILE,new BASE64Encoder().encode(publicKey.getEncoded()));
            writeStringkey(PRIVATE_KEY_FILE,new BASE64Encoder().encode(privateKey.getEncoded()));

            String demoString = "123346"; 
            RSAEncDecDemo rsa = new RSAEncDecDemo();
            String decrypted = rsa.decryptData(demoString);
            String msisdn = decrypted.substring(0,decrypted.indexOf("|"));

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    private String decryptData(String strData) throws IOException {
        byte[] data = DatatypeConverter.parseHexBinary(strData);
        byte[] descryptedData = null;

        try {
            PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            descryptedData = cipher.doFinal(data);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return new String(descryptedData);
    }


    @SuppressWarnings("restriction")
    public PrivateKey readPrivateKeyFromFile(String fileName)throws IOException, NoSuchAlgorithmException,InvalidKeySpecException {

        String publicK = readStringKey(fileName);
        byte[] keyBytes = new BASE64Decoder().decodeBuffer(publicK);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        return fact.generatePrivate(keySpec);
    }

    public PrivateKey readPrivateKeyFromFileold(String fileName)throws IOException {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(new File(fileName));
            ois = new ObjectInputStream(fis);

            BigInteger modulus = (BigInteger) ois.readObject();
            BigInteger exponent = (BigInteger) ois.readObject();

            RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);
            KeyFactory fact = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);

            return privateKey;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                ois.close();
                if (fis != null) {
                    fis.close();
                }
            }
        }
        return null;
    }

    public static void writeStringkey(String fileName, String data) {
        try {
            FileWriter out = new FileWriter(new File(fileName));
            out.write(data);
            out.close();
        } catch (IOException e) {
        }
    }

    public static String readStringKey(String fileName) {

        BufferedReader reader = null;
        StringBuffer fileData = null;
        try {

            fileData = new StringBuffer(2048);
            reader = new BufferedReader(new FileReader(fileName));
            char[] buf = new char[1024];
            int numRead = 0;
            while ((numRead = reader.read(buf)) != -1) {
                String readData = String.valueOf(buf, 0, numRead);
                fileData.append(readData);
                buf = new char[1024];
            }

            reader.close();

        } catch (Exception e) {
        } finally {
            if (reader != null) {
                reader = null;
            }
        }
        return fileData.toString();

    }
}

Where is mistaken point.? Decryption part is give that error.
Whole class uploaded here LINK TO SOURCE CODE

-Thanks

In principle a ciphertext should be indistinguishable from random. That said, ciphers do place constraints on the domain (size and possible values). In the case of RSA PKCS#1 - which is the default mode for "RSA" within the Oracle provider - the output must be precisely the key size (in bytes). Furthermore, the value must be smaller than the modulus.

Now assume that you've just shown us a demo value (because the exception doesn't match the input) and the size of the ciphertext is correct. In that case you would get an unpadding exception when either:

  • the private key doesn't match the public key used;
  • the wrong padding mode (eg OAEP) was used to create the ciphertext;
  • the ciphertext was altered (eg due to an invalid conversion to a string).

You would have to try until you find the culprit, without the required information we cannot test this for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM