【发布时间】: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 服务提供商来完成。所以我按照here 和this 中提到的步骤进行操作。我正在使用 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