【发布时间】:2017-05-29 08:13:44
【问题描述】:
我有一个包含公钥和私钥的 pfx 文件,我想使用这些密钥在我的机器上本地加密和解密文件。 那是我的代码:
public static void encryptFile(File file, PublicKey key,
String transformation) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, IOException,
InvalidAlgorithmParameterException, NoSuchProviderException {
Cipher c = Cipher.getInstance(transformation, "SunJCE");
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyb, "AES");
c.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec);
FileInputStream is = new FileInputStream(file);
CipherOutputStream os = new CipherOutputStream(new FileOutputStream(
new File(file.getName() + "_enc")), c);
copy(is, os);
}
public static void decryptFile(File encryptedFile, File decryptedFile,
Key privateKey, String transformation) {
try {
Cipher c = Cipher.getInstance(transformation, "SunJCE");
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
byte[] keyb = privateKey.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyb, "AES");
c.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec);
CipherInputStream is = new CipherInputStream(new FileInputStream(
encryptedFile), c);
FileOutputStream os = new FileOutputStream(decryptedFile);
copy(is, os);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copy(InputStream is, OutputStream os) {
try {
byte[] buf = new byte[1024];
long total = 0;
while (true) {
int r = is.read(buf);
if (r == -1) {
break;
}
os.write(buf, 0, r);
total += r;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
os.flush();
os.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
我这样称呼它:
CertificateHandler.encryptFile(new File("test.pdf"), pb, "AES/CBC/PKCS5Padding");
CertificateHandler.decryptFile(new File("test.pdf_enc"), new File("test.enc.pdf"), pk, "AES/CBC/NoPadding");
但我收到此错误:
java.security.InvalidKeyException: Invalid AES key length: 294 bytes
我使用了 Unlimited JCE Policy,但没有任何改变。当我尝试使用摘要密钥时,我认为它不起作用,因为它切断了密钥并且不再有效
有什么建议吗?
【问题讨论】:
-
您使用的“转换”参数是什么?尽管您在写答案时似乎遗漏了一些重要概念..
-
@gusto2 我使用“AES/CBC/PKCS5Padding”
标签: java encryption rsa x509certificate jce