|
| 1 | +package com.baeldung.encrypt; |
| 2 | + |
| 3 | +import javax.crypto.*; |
| 4 | +import javax.crypto.spec.IvParameterSpec; |
| 5 | +import java.io.FileInputStream; |
| 6 | +import java.io.FileOutputStream; |
| 7 | +import java.io.IOException; |
| 8 | +import java.io.InputStreamReader; |
| 9 | +import java.security.InvalidAlgorithmParameterException; |
| 10 | +import java.security.InvalidKeyException; |
| 11 | +import java.security.NoSuchAlgorithmException; |
| 12 | + |
| 13 | +class FileEncrypterDecrypter { |
| 14 | + |
| 15 | + private SecretKey secretKey; |
| 16 | + private Cipher cipher; |
| 17 | + |
| 18 | + FileEncrypterDecrypter(SecretKey secretKey, String cipher) throws NoSuchPaddingException, NoSuchAlgorithmException { |
| 19 | + this.secretKey = secretKey; |
| 20 | + this.cipher = Cipher.getInstance(cipher); |
| 21 | + } |
| 22 | + |
| 23 | + void encrypt(String content, String fileName) throws InvalidKeyException, IOException { |
| 24 | + cipher.init(Cipher.ENCRYPT_MODE, secretKey); |
| 25 | + byte[] iv = cipher.getIV(); |
| 26 | + |
| 27 | + try ( |
| 28 | + FileOutputStream fileOut = new FileOutputStream(fileName); |
| 29 | + CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher) |
| 30 | + ) { |
| 31 | + fileOut.write(iv); |
| 32 | + cipherOut.write(content.getBytes()); |
| 33 | + } |
| 34 | + |
| 35 | + } |
| 36 | + |
| 37 | + String decrypt(String fileName) throws InvalidAlgorithmParameterException, InvalidKeyException, IOException { |
| 38 | + |
| 39 | + String content; |
| 40 | + |
| 41 | + try (FileInputStream fileIn = new FileInputStream(fileName)) { |
| 42 | + byte[] fileIv = new byte[16]; |
| 43 | + fileIn.read(fileIv); |
| 44 | + cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(fileIv)); |
| 45 | + |
| 46 | + try (CipherInputStream cipherIn = new CipherInputStream(fileIn, cipher)) { |
| 47 | + InputStreamReader inReader = new InputStreamReader(cipherIn); |
| 48 | + |
| 49 | + StringBuilder sb = new StringBuilder(); |
| 50 | + int c = inReader.read(); |
| 51 | + while (c != -1) { |
| 52 | + sb.append((char) c); |
| 53 | + c = inReader.read(); |
| 54 | + } |
| 55 | + content = sb.toString(); |
| 56 | + } |
| 57 | + |
| 58 | + } |
| 59 | + return content; |
| 60 | + } |
| 61 | +} |
0 commit comments