Created
March 3, 2017 08:38
-
-
Save eliaperantoni/85c9e81bd0d566eb52b9549a575bcaa1 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 javax.crypto.Cipher; | |
import javax.crypto.KeyGenerator; | |
import javax.crypto.SecretKey; | |
import javax.crypto.spec.SecretKeySpec; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.util.Base64; | |
public class CryptoUtils { | |
private String mAlgorithm; | |
private String mTransformation; | |
public CryptoUtils(String algorithm, String transformation){ | |
this.mAlgorithm=algorithm; | |
this.mTransformation=transformation; | |
} | |
public String run(File inputFile, File outputFile, int cipherMode, String encodedKey) throws Exception{ | |
SecretKey secretKey = null; | |
byte[] binary = null; | |
if(cipherMode==Cipher.ENCRYPT_MODE) { | |
KeyGenerator keyGen = KeyGenerator.getInstance("AES"); | |
keyGen.init(128); | |
secretKey = keyGen.generateKey(); | |
}else if(cipherMode==Cipher.DECRYPT_MODE){ | |
byte[] decodedKey = Base64.getDecoder().decode(encodedKey); | |
secretKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES"); | |
} | |
Cipher cipher = Cipher.getInstance(mTransformation); | |
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(); | |
return Base64.getEncoder().encodeToString(secretKey.getEncoded()); | |
} | |
static String encrypt(File inputFile,File outputFile) throws Exception{ | |
int mode = Cipher.ENCRYPT_MODE; | |
String key = new CryptoUtils("AES","AES").run(inputFile, outputFile, mode, null); | |
return key; | |
} | |
static void decrypt(File inputFile,File outputFile, String key) throws Exception{ | |
int mode = Cipher.DECRYPT_MODE; | |
new CryptoUtils("AES","AES").run(inputFile, outputFile, mode, key); | |
} | |
public String getmAlgorithm() { | |
return mAlgorithm; | |
} | |
public void setmAlgorithm(String mAlgorithm) { | |
this.mAlgorithm = mAlgorithm; | |
} | |
public String getmTransformation() { | |
return mTransformation; | |
} | |
public void setmTransformation(String mTransformation) { | |
this.mTransformation = mTransformation; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment