【发布时间】:2011-07-18 13:43:49
【问题描述】:
我正在尝试加密和解密以下代码中提到的消息。基本上我想用公钥加密消息并将加密消息从字节数组转换为字符串。并将此字符串解密为原始文本。这是两种方法。这里加密工作正常,但解密失败(错误是“数据必须从零开始”)。我认为这是因为我将加密的字节数组转换为字符串。
我该如何解决这个问题? (我想将加密的字节数组作为字符串并将其用于解密)有没有其他方法(使用公钥和私钥)
public static String getEncryptedMessage(String publicKeyFilePath,
String plainMessage) {
byte[] encryptedBytes;
try {
Cipher cipher = Cipher.getInstance("RSA");
byte[] publicKeyContentsAsByteArray = getBytesFromFile(publicKeyFilePath);
PublicKey publicKey = getPublicKey(publicKeyContentsAsByteArray);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plainMessage.getBytes());
return new String(encryptedBytes);
} catch (Throwable t) {
}
}
public static String getDecryptedMessage(
String privateKeyFilePath, String encryptedMessage)
{
byte[] decryptedMessage;
try {
Cipher cipher = Cipher.getInstance("RSA");
byte[] privateKeyContentsAsByteArray = getBytesFromFile(privateKeyFilePath);
PrivateKey privateKey = getPrivateKey(privateKeyContentsAsByteArray);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
decryptedMessage = cipher.doFinal(encryptedMessage.getBytes());
return new String(decryptedMessage);
} catch (Throwable t) {
}
【问题讨论】:
-
您不应将加密的字节数组直接转换为字符串。如果您需要以可打印的形式将其转换为 Base64。您可以使用来自 Apache commons 编解码器的 Base64 编码器:[link(]commons.apache.org/codec)
标签: java encoding cryptography public-key-encryption