解密XML時遇到問題,輸入我的文件返回不完整的數據算法和罕見的符號。具有大XML文件類型的不完整RSA解密 - JAVA
public File decryptFile(File fileInput, X509Certificate certificate) throws BadPaddingException, Exception { try (DataInputStream dis = new DataInputStream(new FileInputStream(fileInput))) { byte[] encryptedKeyBytes = new byte[dis.readInt()]; dis.readFully(encryptedKeyBytes); PublicKey publicKey = certificate.getPublicKey(); rsaCipher.init(Cipher.DECRYPT_MODE, publicKey); byte[] rijndaelKeyBytes = rsaCipher.doFinal(encryptedKeyBytes); SecretKey rijndaelKey = new SecretKeySpec(rijndaelKeyBytes, "Rijndael"); byte[] iv = new byte[16]; dis.read(iv); IvParameterSpec spec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("Rijndael/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, rijndaelKey, spec); try (CipherInputStream cis = new CipherInputStream(dis, cipher)) { try (FileOutputStream fos = new FileOutputStream(fileInput.getAbsolutePath() + ".xml")) { byte[] data = new byte[16]; int theByte; while ((theByte = cis.read(data)) != -1) { System.out.print(new String(data)); fos.write(data, 0, theByte); } System.out.println("\n\n"); } } } return new File(fileInput.getAbsolutePath() + ".xml"); }
此代碼返回我的數據
</ctaAbonBenef><distPago>00000</distPago><item>00000</item><pagoPoder>N</p�|���[�[W�Z�5��Q�
我覺得這跟UTF-8的事,但我解決不了。
現在我也可以相信它是使用的加密算法,我爲了以防萬一。
public static void generateFileEncrypt(File fileInput, PrivateKey privateKey, String folderSave) throws Exception { String fileOutput = folderSave + "\" + fileInput.getName() + ENCRYPTED_FILENAME_SUFFIX; DataOutputStream output = new DataOutputStream(new FileOutputStream(fileOutput)); Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsaCipher.init(Cipher.ENCRYPT_MODE, privateKey); KeyGenerator rijndaelKeyGenerator = KeyGenerator.getInstance("Rijndael"); rijndaelKeyGenerator.init(128); Key rijndaelKey = rijndaelKeyGenerator.generateKey(); byte[] encodedKeyBytes = rsaCipher.doFinal(rijndaelKey.getEncoded()); output.writeInt(encodedKeyBytes.length); output.write(encodedKeyBytes); SecureRandom random = new SecureRandom(); byte[] iv = new byte[16]; random.nextBytes(iv); output.write(iv); IvParameterSpec spec = new IvParameterSpec(iv); Cipher symmetricCipher = Cipher.getInstance("Rijndael/CBC/PKCS5Padding"); symmetricCipher.init(Cipher.ENCRYPT_MODE, rijndaelKey, spec); try ( CipherOutputStream cos = new CipherOutputStream(output, symmetricCipher); FileInputStream fis = new FileInputStream(fileInput)) { int theByte; byte[] data = new byte[16]; while ((theByte = fis.read(data)) != -1) { System.out.print(new String(data)); cos.write(data, 0, theByte); } System.out.println("\n\n"); cos.flush(); } }
在此先感謝。
我想要做的是用私鑰加密文件,就像在generateFileEncrypt方法中看到的一樣,但是用公鑰解密文件,它會返回我用奇數符號的數據。 – rodrixd 2014-10-28 19:55:46
@rodrixd查看我的更新。並停止浪費無用的數學週期。 – erickson 2014-10-28 20:37:33