· 6 years ago · May 01, 2019, 04:52 PM
1 public static void decrypt(File inputFile, final String outputFileName, User currentUser) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, ParserConfigurationException, SAXException, InvalidAlgorithmParameterException, BadPaddingException{
2 SecretKey sessionKey = null;
3 String algorithm, ciphermode;
4 int keySize, blockSize;
5 byte[] encryptedFile;
6 byte[] iv;
7 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
8 DocumentBuilder builder = factory.newDocumentBuilder();
9 Document doc = builder.parse(inputFile);
10 doc.getDocumentElement().normalize();
11 NodeList nList = doc.getElementsByTagName("User");
12 boolean userFound = false;
13 for (int i = 0; i < nList.getLength(); i++) {
14 if (nList.item(i).getFirstChild().getNextSibling().getTextContent().equals(currentUser.getName())){
15 sessionKey = decryptSessionKey(nList.item(i).getFirstChild().getNextSibling().getNextSibling().getNextSibling().getTextContent().getBytes(),currentUser.getPrivateKey());
16 userFound = true;
17 break;
18 }
19 }
20 if (!userFound){
21 sessionKey = generateSessionKey();
22 }
23
24 algorithm = doc.getElementsByTagName("Algorithm").item(0).getTextContent();
25 keySize = Integer.parseInt(doc.getElementsByTagName("KeySize").item(0).getTextContent());
26 blockSize = Integer.parseInt(doc.getElementsByTagName("BlockSize").item(0).getTextContent());
27 ciphermode = doc.getElementsByTagName("CipherMode").item(0).getTextContent();
28 iv = Base64.getDecoder().decode(doc.getElementsByTagName("IV").item(0).getTextContent().getBytes());
29 encryptedFile = Base64.getDecoder().decode(doc.getElementsByTagName("Content").item(0).getTextContent().getBytes());
30
31 //byte[] input = Files.readAllBytes(inputFile.toPath());
32 Cipher cipher = Cipher.getInstance(algorithm+"/"+ciphermode+"/PKCS5Padding");
33
34 if (!"ECB".equals(ciphermode)){
35 IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
36 cipher.init(Cipher.DECRYPT_MODE, sessionKey, ivParameterSpec);
37 } else {
38 cipher.init(Cipher.DECRYPT_MODE, sessionKey);
39 }
40 byte[] plainText = new byte[cipher.getOutputSize(blockSize)];
41 int ptLength = cipher.update(encryptedFile, 0, blockSize, plainText, 0);
42 try{
43 ptLength += cipher.doFinal(plainText, ptLength);
44 } catch (BadPaddingException e){
45 return;
46 }
47 Files.write(new File(inputFile.toPath().getParent().toFile(),outputFileName).toPath(), plainText);
48
49 }