当前位置: 首页 > 面试题库 >

BadPaddingException:无效的密文

奚才良
2023-03-14
问题内容

我需要一些帮助,因为这是我第一次编码密码。

加密代码似乎可以正常工作,但是解密会引发错误。

我得到的错误是:

de.flexiprovider.api.exceptions.BadPaddingException:无效的密文

在代码末尾的 解密函数中 ,该标记为注释

//这里抛出错误!....................................

我已包括所有进口商品,请原谅,因为这可能与问题有关。

非常感谢您对我做错事的任何帮助。

码:

import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import de.flexiprovider.common.ies.IESParameterSpec;
import de.flexiprovider.core.FlexiCoreProvider;
import de.flexiprovider.ec.FlexiECProvider;
import de.flexiprovider.ec.parameters.CurveParams;
import de.flexiprovider.ec.parameters.CurveRegistry.BrainpoolP384r1;
import de.flexiprovider.pki.PKCS8EncodedKeySpec;
import de.flexiprovider.pki.X509EncodedKeySpec;

public class MainActivity extends Activity {

private static PublicKey PublicKey;
private static PrivateKey PrivateKey;
private static String PubKey;
private static String PrvKey;
private static String message = "Hello World";
private static String encryptedMessage;
private static String decryptedMessage;

private final static String TAG = "ERROR: ";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        Security.addProvider(new FlexiCoreProvider());
        Security.addProvider(new FlexiECProvider());

        // instantiate the elliptic curve key pair generator
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECIES", "FlexiEC");

        // choose the curve
        CurveParams ecParams = new BrainpoolP384r1();

        // Initialize the key pair generator
        kpg.initialize(ecParams, new SecureRandom());
        KeyPair keyPair = kpg.generateKeyPair();

        // generate the public key
        PublicKey = keyPair.getPublic();

        // generate private key
        PrivateKey = keyPair.getPrivate();
    }
    catch (Exception e) {
        Log.e(TAG, e.toString());
    }

    // I'm converting keys to strings here as the public keys will be stored on a server
    // database and the private keys will be stored in the application preferences file
    // this private key storage is maybe not optimum, but at this point I just want to
    // simulate a messaging encryption/decryption process for testing purposes

    // convert public key to a string
    PubKey = Base64.encodeToString(PublicKey.getEncoded(), Base64.DEFAULT);
    Log.d("PubKey: ", PubKey);

    // convert private key to a string
    PrvKey = Base64.encodeToString(PrivateKey.getEncoded(), Base64.DEFAULT);
    Log.d("PrvKey: ", PrvKey);

    // encrypt the message with the public key
    encryptedMessage = encryptMessage(PubKey, message);

    // report if the public key has not been regenerated correctly
    if (encryptedMessage == null) {
        Log.d("PUBLIC_KEY_REGENERATE_ERROR: ", encryptedMessage);
    }

    // decrypt the message with the private key
    decryptedMessage = decryptMessage(PrvKey, encryptedMessage);

    // report if the private key has not been regenerated correctly
    if (encryptedMessage == null) {
        Log.d("PRIVATE_KEY_REGENERATE_ERROR: ", decryptedMessage);
    }
}

// encrypt function
public static String encryptMessage(String publicKey, String message) {

    KeyFactory keyFactory = null;
    PublicKey pubkey = null;
    Cipher cipher = null;

    byte[] PLAINTEXT_MESSAGE = message.getBytes();
    Log.d("PLAINTEXT_MESSAGE: ", message);

    Security.addProvider(new FlexiCoreProvider());
    Security.addProvider(new FlexiECProvider());

    // Base64 decode the publicKey string into a byte array
    byte[] decodedPublicKey = Base64.decode(publicKey, Base64.DEFAULT);

    try {
        // instantiate a X509EncodedKeySpec
        X509EncodedKeySpec X509spec = new X509EncodedKeySpec(decodedPublicKey);

        keyFactory = KeyFactory.getInstance("ECIES", "FlexiEC");

        // re-generate the public key
        pubkey = keyFactory.generatePublic(X509spec);

        // sanity check, return null on inequality
        if (!pubkey.equals(PublicKey)) {
            return null;
        }

        cipher = Cipher.getInstance("ECIES", "FlexiEC");
        IESParameterSpec IESspec = new IESParameterSpec("AES256_CBC", "HmacSHA512", null, null);
        cipher.init(Cipher.ENCRYPT_MODE, pubkey, IESspec);
    }
    catch (Exception e) {
        Log.e(TAG, e.toString());
    }

    // encrypt the message
    byte[] encryptedData = null;

    try {
        encryptedData = cipher.doFinal(PLAINTEXT_MESSAGE);
    }
    catch (IllegalBlockSizeException e) {
        Log.e(TAG, e.toString());
    }
    catch (BadPaddingException e) {
        Log.e(TAG, e.toString());
    }

    String encryptedMessage = null;

    try {
        encryptedMessage = new String(encryptedData, "UTF-8");
    }
    catch (UnsupportedEncodingException e) {
        Log.e(TAG, e.toString());
    }
    Log.d("encryptedMessage: ", encryptedMessage);
    return encryptedMessage;
}

// decrypt function
public static String decryptMessage(String privateKey, String message) {

    KeyFactory keyFactory = null;
    PrivateKey prvkey = null;
    Cipher cipher = null;

    byte[] ENCRYPTED_MESSAGE = message.getBytes();
    Log.d("ENCRYPTED_MESSAGE: ", message);

    Security.addProvider(new FlexiCoreProvider());
    Security.addProvider(new FlexiECProvider());

    try {
        // Base64 decode the privateKey string into a byte array
        byte[] decodedPrivateKey = Base64.decode(privateKey, Base64.DEFAULT);

        // instantiate a PKCS8EncodedKeySpec
        PKCS8EncodedKeySpec PKCS8spec = new PKCS8EncodedKeySpec(decodedPrivateKey);

        keyFactory = KeyFactory.getInstance("ECIES", "FlexiEC");

        // re-generate the private key
        prvkey = keyFactory.generatePrivate(PKCS8spec);

        // sanity check, return null on inequality
        if (!prvkey.equals(PrivateKey)) {
            return null;
        }

        cipher = Cipher.getInstance("ECIES", "FlexiEC");
        IESParameterSpec IESspec = new IESParameterSpec("AES256_CBC", "HmacSHA512", null, null);
        cipher.init(Cipher.DECRYPT_MODE, prvkey, IESspec);
    }
    catch (Exception e) {
        Log.e(TAG, e.toString());
    }

    // decrypt the message
    byte[] decryptedData = null;

    try {
        decryptedData = cipher.doFinal(ENCRYPTED_MESSAGE);

        // ERROR THROWN HERE! ..............................
        // de.flexiprovider.api.exceptions.BadPaddingException: invalid ciphertext
    }
    catch (IllegalBlockSizeException e) {
        Log.e(TAG, e.toString());
    }
    catch (BadPaddingException e) {
        Log.e(TAG, e.toString());
    }

    String decryptedMessage = null;

    try {
        decryptedMessage = new String(decryptedData, "UTF-8");
    }
    catch (UnsupportedEncodingException e) {
        Log.e(TAG, e.toString());
    }
    Log.d("decryptedMessage: ", decryptedMessage);
    return decryptedMessage;
}

}


问题答案:

您不能String像在此行中那样将密文用作构造函数的输入:

encryptedMessage = new String(encryptedData, "UTF-8");

如果 要使用字符串而不是字节来传达密文, 必须像使用密钥那样使用诸如Base 64之类的编码。

加密将导致数据看起来像随机字节。并非所有字节都有等效的字符。转换的结果取决于字符编码。UTF-8可能会使用许多字节,并且许多组合都不会产生正确的字符。Java会静默转换它们,请检查Charset和相关类以获取更多信息。



 类似资料:
  • 问题内容: 我正在编写一个从控制台输入的程序- 一个zip文件的名称,一个将包含从第一个zip文件生成的(解密)加密文件的zip文件的名称以及一个包含公钥的文件。解密时出现异常: 无法弄清楚为什么会出现此异常? 公钥: 私钥: 该程序的代码如下。任何帮助都很好:) PS:更新了方法。仍然给出相同的错误。 问题答案: 约瑟夫是对的。 使用默认参数创建密码时,默认密码为“ RSA / ECB / PK

  • 问题内容: 我是Android安全概念的新手。 我一直在阅读一些博客,以了解我们可以使用公钥加密数据并可以使用各自的私钥解密数据。加密似乎没有任何问题,但是当我尝试对其进行解密时,它会抛出: javax.crypto.BadPaddingException:错误:0407106B:rsa例程:RSA_padding_check_PKCS1_type_2:块类型不是02。 我的代码如下: 堆栈跟踪如

  • 我正在尝试创建AES加密/解密方法,但是如果不使用AES / ECB / NoPadding,我似乎无法获得原始输入。现在我正在尝试使用AES / CBC / PKCS7Padding。我已经确认在文件中读取和写入字节工作正常。使用PKCS7填充,我从中得到一个糟糕的填充异常 在解密方法中。没有填充,没有例外 - 但是输出是混乱的。我花了很多时间浏览有关此完全相同问题的其他帖子,但我似乎找不到适合

  • 在我的应用程序中,当用户在最初的设置(指纹注册)中扫描手指时,我保存了用户访问代码的加密版本。当用户稍后试图解锁应用程序时,我将尝试使用指纹API[指纹验证]解密此访问代码。 但是,在解密时引发以下异常: 指纹扫描仪显示在中。无论是否注册或验证指纹,都始终按照构造函数的顺序调用以下函数。 初始化密钥库:

  • 尝试将数据解密为用AES-128加密的字节数组,使用字符串密钥"keykeykeykey1" 代码: 给我BadPaddingExc0019。我错过了什么?

  • 问题内容: 这是我的加密设置: 这是我要解密的代码: 这是我要加密的代码: 错误: 解密时出现BadPaddingException异常,为什么?该消息正好是168个字符,在填充后为176个字符(可被16整除) 问题答案: 从我最初的评论: 一种典型的情况是密钥与另一侧使用的密钥不同。这是最可能的原因,但是您可能还想检查处理流的方式,因为您确实缺少.close()以及可能缺少.flush()语句。