Created
March 24, 2021 09:41
-
-
Save jogHar/ffd496aa93c654b4c208a17e06a34618 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.UnsupportedEncodingException; | |
import java.security.InvalidKeyException; | |
import java.security.Key; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
import java.util.Arrays; | |
import javax.crypto.BadPaddingException; | |
import javax.crypto.Cipher; | |
import javax.crypto.IllegalBlockSizeException; | |
import javax.crypto.NoSuchPaddingException; | |
import javax.crypto.spec.SecretKeySpec; | |
import com.deltafixes.exception.CryptoException; | |
public class CryptoUtils { | |
public static void encrypt(String key, File inputFile, File outputFile) | |
throws CryptoException { | |
doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile); | |
} | |
public static void decrypt(String key, File inputFile, File outputFile) | |
throws CryptoException { | |
doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile); | |
} | |
private static void doCrypto(int cipherMode, String key, File inputFile, | |
File outputFile) throws CryptoException { | |
try { | |
Key secretKey = new SecretKeySpec(keyDigest(key), "AES"); | |
Cipher cipher = Cipher.getInstance("AES"); | |
cipher.init(cipherMode, secretKey); | |
FileInputStream inputStream = new FileInputStream(inputFile); | |
byte[] inputBytes = new byte[(int) inputFile.length()]; | |
inputStream.read(inputBytes); | |
byte[] outputBytes = cipher.doFinal(inputBytes); | |
FileOutputStream outputStream = new FileOutputStream(outputFile); | |
outputStream.write(outputBytes); | |
inputStream.close(); | |
outputStream.close(); | |
} catch (NoSuchPaddingException | NoSuchAlgorithmException | |
| InvalidKeyException | BadPaddingException | |
| IllegalBlockSizeException | IOException ex) { | |
throw new CryptoException("Error encrypting/decrypting file", ex); | |
} | |
} | |
private static byte[] keyDigest(String key) throws CryptoException { | |
byte[] keyDigest; | |
MessageDigest sha = null; | |
try { | |
keyDigest = key.getBytes("UTF-8"); | |
sha = MessageDigest.getInstance("SHA-1"); | |
keyDigest = sha.digest(keyDigest); | |
return Arrays.copyOf(keyDigest, 16); | |
} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) { | |
throw new CryptoException("Error encrypting/decrypting file", e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment