【问题标题】:InvalidKeyException while encrypting data加密数据时出现 InvalidKeyException
【发布时间】:2019-11-07 22:41:19
【问题描述】:

我知道这方面有很多线程,但我无法找到解决方案。 问题陈述: 需要加密数据。以下是我的代码:

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import static java.nio.charset.StandardCharsets.UTF_8;

public class CryptoUtil {

    private static final String AES = "AES/ECB/PKCS5Padding";

    public String encryptMessage(final String message, final byte[] dataKey) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(dataKey, AES);
        try {
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedMessage = cipher.doFinal(message.getBytes());
            return Base64.getEncoder().encodeToString(encryptedMessage);
        }
        catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
            throw new Exception("Error while encrypting application credentials", e);
        }
    }
}

我需要使用 BountyCastle 服务提供商来完成。所以我按照herethis 中提到的步骤进行操作。我正在使用 JAVA 11,但我切换到 JAVA 8 以遵循提到的链接。 在我的代码中,我添加了静态块以将 BountyCastle 添加为服务提供者

static {
    BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
    Security.addProvider(bouncyCastleProvider);
  }

但是,它不会被添加为经过验证的提供商。所以我得到了这个问题。 任何想法如何处理。如何将 BouncyCastle 添加为经过验证的提供商。 我在本地机器上运行,需要创建 JAR。

【问题讨论】:

  • 我认为“SecretKeySpec(dataKey, AES);”应该是:SecretKeySpec(dataKey, "AES"); .您没有为 secretkeyspec 指定模式或填充,这是在您创建密码时指定的。见docs.oracle.com/javase/7/docs/technotes/guides/security/…
  • @Chandra 如果正在抛出一个 InvalidKeyException,请给我们堆栈跟踪。
  • @TheGreatContini - 你是对的,应该是 SecretKeySpec skeySpec = new SecretKeySpec(byte[] of key, "AES");

标签: java encryption aes bouncycastle


【解决方案1】:

没有人回答这个问题,所以我将在上面的评论中发布答案。我没有测试过,所以我把这部分留给你。

当您执行Cipher.getInstance() 时,使用“AES/ECB/PKCS5Padding”是正确的(对于“正确”的一些奇怪定义,Java 提供商认为 PKCS5 填充 = PKCS7 填充,但不要介意)。

但是当您创建密钥时,在其中设置模式和填充是不正确的。相反,他们只想要算法。所以试试:

SecretKeySpec secretKey = new SecretKeySpec(dataKey, "AES");

更改是“AES”周围的引号,而不是使用 AES="AES/ECB/PKCS5Padding"。

不确定这是否能解决您的问题,但应该是朝着正确方向迈出的一步(我希望如此)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多