Created
March 1, 2016 16:35
-
-
Save Quiark/1d086bec20bce0f62b59 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
private static final String CR_ALG_AES = "AES/CBC/PKCS5Padding"; | |
private static final String CR_ALG_HMAC = "HmacSHA256"; | |
private static final int CR_SALT_LENGTH = 16; | |
private CryptoHeader prepareHeader() { | |
CryptoHeader header = new CryptoHeader(); | |
header.iv = new byte[16]; | |
rnd.nextBytes(header.iv); | |
header.salt = new byte[CR_SALT_LENGTH]; | |
rnd.nextBytes(header.salt); | |
header.iterations = CR_ITERATIONS; | |
header.version = 1; | |
return header; | |
} | |
private void encryptFile(CryptoHeader header, byte[] encKey, byte[] hmacKey, Path inPath, Path outPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { | |
Cipher cipher = Cipher.getInstance(CR_ALG_AES); | |
cipher.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(header.iv)); | |
Mac hmac = Mac.getInstance(CR_ALG_HMAC); | |
hmac.init(hmacKey); | |
FileInputStream inf = null; | |
FileOutputStream outf = null; | |
CipherOutputStream outCr = null; | |
MacOutputStream outMac = null; | |
try { | |
inf = new FileInputStream(inPath.toFile()); | |
outf = new FileOutputStream(outPath.toFile()); | |
outMac = new MacOutputStream(outf, hmac); | |
outCr = new CipherOutputStream(outMac, cipher); | |
copy(inf, outCr); | |
header.hmac = hmac.doFinal(); | |
} finally { | |
if (outCr != null) outCr.close(); | |
if (outMac != null) outMac.close(); | |
if (outf != null) outf.close(); | |
if (inf != null) inf.close(); | |
} | |
} | |
private void copy(InputStream in, OutputStream out) throws IOException { | |
byte[] buffer = new byte[32 * 1024]; | |
int len; | |
while ((len = in.read(buffer)) != -1) { | |
out.write(buffer, 0, len); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment