加密/解密的基本程序:javax.crypto.BadPaddingException:解密错误

时间:2016-09-15 19:33:09

标签: java encryption cryptography

我已经为Encrypt / Decrypt写了一个非常基本的程序,并且现在尝试加密单个字符串。 加密工作正常,但在解密时会抛出错误

  

javax.crypto.BadPaddingException:解密错误。

在下面的行中抛出错误

byte[] decodedData = (rsa.doFinal(decodedValue));

我尝试了多种方法并经历了很多线程但却无法找到解决方案。任何人都可以帮我解决这个问题吗?

该类很简单,只有4种方法,第一种是测试方法,接下来是密钥库加载方法,其余两种方法都是加密和解密。

package XXXX;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


public class EncryptDecryptUtil {
    private String publicKeyStoreFileName = "C:\\Program Files\\Java\\jdk1.8.0_51\\jre\\lib\\security\\cacerts";
    private String pubKeyStorePwd = "XXX";
    private String pubKeyAlias="XXXX";
    private static final String JKS = "JKS";
    private static final int CONST_16 = 16;    

    public String TestMethod(final String clearText) throws InvalidKeyException, NoSuchAlgorithmException,
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, KeyStoreException,
            CertificateException, IOException, UnrecoverableKeyException {    
        byte[] ecryptedAESKey = generateEncryptedData("TEST");
        System.out.println("Encrypted Key = " + ecryptedAESKey);
        System.out.println("Decrypted Key = " + generateDecryptedData(ecryptedAESKey));
        return generateDecryptedData(ecryptedAESKey);
    }

    private KeyStore loadKeyStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
            IOException {
        KeyStore keystore = KeyStore.getInstance(JKS);
        FileInputStream tmp = new FileInputStream(publicKeyStoreFileName);
        keystore.load(tmp, pubKeyStorePwd.toCharArray());
        tmp.close();
        return keystore;
    } 

    private byte[] generateEncryptedData(final String data) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
            KeyStoreException, CertificateException, IOException, UnrecoverableKeyException {
            Base64 base64 = new Base64();
            X509Certificate cert;
            KeyStore keystore = loadKeyStore();
            cert = (java.security.cert.X509Certificate) keystore.getCertificate(pubKeyAlias);
            Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            rsa.init(Cipher.ENCRYPT_MODE, cert);

            byte[] ecrypteddata = (base64.encode(rsa.doFinal(data.getBytes(StandardCharsets.UTF_8))));
            return ecrypteddata;
    }

    public String generateDecryptedData(final byte[] encryptedData) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
            KeyStoreException, CertificateException, IOException, UnrecoverableKeyException {
            Base64 base64 = new Base64();
            X509Certificate cert;
            KeyStore keystore = loadKeyStore();
            cert = (java.security.cert.X509Certificate) keystore.getCertificate(pubKeyAlias);
            Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            rsa.init(Cipher.DECRYPT_MODE, cert);
            byte[] decodedValue = base64.decode(encryptedData);
            byte[] decodedData = (rsa.doFinal(decodedValue));
            return new String(decodedData);
    }    
}

2 个答案:

答案 0 :(得分:0)

Java API在证书和(RSA)私钥之间产生差异。私钥虽然与证书相关联,但不是证书的一部分。 Java(幸运的是)在这方面与Microsoft的.NET API不同,.NET API充满了如此糟糕的设计选择。

当你尝试时:

rsa.init(Cipher.DECRYPT_MODE, cert);

你应该期待一个错误。然而,问题在于该构造有时用于使用公钥原始“解密”基于RSA的签名。因此,尽管您应始终使用私钥进行解密,但未明确禁止使用公钥进行解密(对于Sun提供商)。

因此,请尝试使用KeyStore#getKey或(更现代但更复杂的)KeyStore#getEntry来检索私钥。也就是说:如果你确实在密钥库中有一个私钥,并且密码要检索它。

答案 1 :(得分:-1)

以下是最终的工作代码:

import org.apache.commons.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Created by Suchit Pandya on 9/16/2016.
 */
public class EncryptLogic2 {

    private String publicKeyStoreFileName = "C:\\Program Files\\Java\\jdk1.8.0_51\\jre\\lib\\security\\cacerts";
    private String pubKeyStorePwd = "password";
    private String pubKeyAlias="certName";
    private static final String JKS = "JKS";
    private static final String SHA1PRNG = "SHA1PRNG";
    private static final String RSA = "RSA/ECB/PKCS1Padding";
    private static final int CONST_16 = 16;
    private static byte[] asKey;


    public String TestMethod(final String clearText) throws InvalidKeyException, NoSuchAlgorithmException,
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, KeyStoreException,
            CertificateException, IOException, UnrecoverableKeyException {

        String ecryptedData = generateEncryptedData(clearText);
        String decryptedData = generateDecryptedData(ecryptedData);
        System.out.println("*********** Decrypted Data = " + decryptedData);
        return decryptedData;
    }

    private KeyStore loadKeyStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
            IOException {
        KeyStore keystore = KeyStore.getInstance(JKS);
        FileInputStream tmp = new FileInputStream(publicKeyStoreFileName);
        keystore.load(tmp, pubKeyStorePwd.toCharArray());
        tmp.close();
        return keystore;
    }

    private String generateEncryptedData(final String data) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
            KeyStoreException, CertificateException, IOException, UnrecoverableKeyException {
        Base64 base64 = new Base64();
        X509Certificate cert;
        KeyStore keystore = loadKeyStore();
        cert = (java.security.cert.X509Certificate) keystore.getCertificate(pubKeyAlias);
        Cipher rsa = Cipher.getInstance(RSA);
        Key key = cert.getPublicKey();
        rsa.init(Cipher.ENCRYPT_MODE, key);

        byte[] ecrypteddata = rsa.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBase64String(ecrypteddata);
    }

    public String generateDecryptedData(final String encryptedData) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
            KeyStoreException, CertificateException, IOException, UnrecoverableKeyException {
        Base64 base64 = new Base64();
        X509Certificate cert;
        KeyStore keystore = loadKeyStore();
        Cipher rsa = Cipher.getInstance(RSA);
        Key key = keystore.getKey(pubKeyAlias, pubKeyStorePwd.toCharArray());
        rsa.init(Cipher.DECRYPT_MODE, key);
        byte[] decodedValue = base64.decode(encryptedData);
        byte[] decodedData = (rsa.doFinal(decodedValue));
        return new String(decodedData, StandardCharsets.UTF_8);
    }
}