Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. public class Crypter {
  2.  
  3. public static void encrypt(String path, String password) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
  4. FileInputStream fis = new FileInputStream(path);
  5. FileOutputStream fos = new FileOutputStream(path.concat(".crypt"));
  6. byte[] key = ("someRandomSaltlol" + password).getBytes(StandardCharsets.UTF_8);
  7. MessageDigest sha = MessageDigest.getInstance("SHA-1");
  8. key = sha.digest(key);
  9. key = Arrays.copyOf(key, 16);
  10. SecretKeySpec sks = new SecretKeySpec(key, "AES");
  11. Cipher cipher = Cipher.getInstance("AES");
  12. cipher.init(Cipher.ENCRYPT_MODE, sks);
  13. CipherOutputStream cos = new CipherOutputStream(fos, cipher);
  14. int b;
  15. byte[] d = new byte[8];
  16. while ((b = fis.read(d)) != -1) {
  17. cos.write(d, 0, b);
  18. }
  19. cos.flush();
  20. cos.close();
  21. fis.close();
  22. new File(path).delete();
  23. }
  24.  
  25. public static void decrypt(String path, String password, String outPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
  26. FileInputStream fis = new FileInputStream(path);
  27. FileOutputStream fos = new FileOutputStream(new File(outPath));
  28. byte[] key = ("someRandomSaltlol" + password).getBytes("UTF-8");
  29. MessageDigest sha = MessageDigest.getInstance("SHA-1");
  30. key = sha.digest(key);
  31. key = Arrays.copyOf(key, 16);
  32. SecretKeySpec sks = new SecretKeySpec(key, "AES");
  33. Cipher cipher = Cipher.getInstance("AES");
  34. cipher.init(Cipher.DECRYPT_MODE, sks);
  35. CipherInputStream cis = new CipherInputStream(fis, cipher);
  36. int b;
  37. byte[] d = new byte[8];
  38. while ((b = cis.read(d)) != -1) {
  39. fos.write(d, 0, b);
  40. }
  41. fos.flush();
  42. fos.close();
  43. cis.close();
  44. new File(path).delete();
  45. }
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement